From cb3d63ba523edb502e0175385417c8015270c885 Mon Sep 17 00:00:00 2001 From: Damian Hickey <57436+damianh@users.noreply.github.com> Date: Tue, 21 Jan 2025 15:49:25 +0100 Subject: [PATCH] Replace FluentAssertions with Shouldly --- .gitignore | 8 +- identity-server/Duende.IdentityServer.sln | 15 + .../Configuration.IntegrationTests.csproj | 2 +- .../DynamicClientRegistrationTests.cs | 20 +- ...ynamicClientRegistrationValidationTests.cs | 30 +- .../EntityFramework.IntegrationTests.csproj | 2 +- ...yFramework.Storage.IntegrationTests.csproj | 3 +- .../Stores/ClientStoreTests.cs | 8 +- .../Stores/DeviceFlowStoreTests.cs | 49 +-- .../Stores/IdentityProviderStoreTests.cs | 8 +- .../Stores/PersistedGrantStoreTests.cs | 42 +- .../TokenCleanup/TokenCleanupTests.cs | 40 +- .../EntityFramework.Storage.UnitTests.csproj | 2 +- .../IsLocalUrlTests.cs | 4 +- .../Mappers/ApiResourceMappersTests.cs | 24 +- .../Mappers/ClientMappersTests.cs | 39 +- .../Mappers/IdentityProviderMappersTests.cs | 32 +- .../Mappers/IdentityResourcesMappersTests.cs | 8 +- .../Mappers/PersistedGrantMappersTests.cs | 12 +- .../PushedAuthorizationRequestMappersTests.cs | 8 +- .../Mappers/ScopeMappersTests.cs | 42 +- .../Clients/ClientAssertionClient.cs | 40 +- ...ClientCredentialsAndResourceOwnerClient.cs | 10 +- .../Clients/ClientCredentialsClient.cs | 266 ++++++------ .../CustomTokenRequestValidatorClient.cs | 10 +- .../Clients/CustomTokenResponseClients.cs | 186 ++++---- .../Clients/DiscoveryClient.cs | 16 +- .../Clients/ExtensionGrantClient.cs | 366 ++++++++-------- .../Clients/RefreshTokenClient.cs | 138 +++--- .../Clients/ResourceOwnerClient.cs | 180 ++++---- .../Clients/RevocationClient.cs | 8 +- .../Clients/UserInfoClient.cs | 62 +-- .../Common/IdentityServerPipeline.cs | 4 +- .../Basic/ClientAuthenticationTests.cs | 34 +- .../Conformance/Basic/CodeFlowTests.cs | 38 +- .../Conformance/Basic/RedirectUriTests.cs | 26 +- .../Basic/ResponseTypeResponseModeTests.cs | 14 +- .../Conformance/Pkce/PkceTests.cs | 70 +-- .../Endpoints/Authorize/AuthorizeTests.cs | 406 ++++++++--------- .../Endpoints/Authorize/ConsentTests.cs | 90 ++-- .../Authorize/JwtRequestAuthorizeTests.cs | 407 +++++++++--------- .../Authorize/PushedAuthorizationTests.cs | 62 +-- .../Endpoints/Authorize/ResourceTests.cs | 54 +-- .../RestrictAccessTokenViaBrowserTests.cs | 60 +-- .../Endpoints/Authorize/SessionIdTests.cs | 6 +- .../CheckSession/CheckSessionTests.cs | 4 +- .../Endpoints/Ciba/CibaTests.cs | 298 ++++++------- .../DeviceAuthorizationTests.cs | 46 +- .../Discovery/DiscoveryEndpointTests.cs | 41 +- .../Endpoints/EndSession/EndSessionTests.cs | 162 +++---- .../Introspection/IntrospectionTests.cs | 178 ++++---- .../Endpoints/Revocation/RevocationTests.cs | 120 +++--- .../Endpoints/Token/CibaTokenEndpointTests.cs | 140 +++--- .../Endpoints/Token/DPoPTokenEndpointTests.cs | 240 +++++------ .../Endpoints/Token/RefreshTokenTests.cs | 30 +- .../Endpoints/Token/ResourceTests.cs | 124 +++--- .../Endpoints/Token/TokenEndpointTests.cs | 14 +- .../Extensibility/CustomClaimsServiceTests.cs | 6 +- .../CustomProfileServiceTests.cs | 12 +- .../CustomTokenCreationServiceTests.cs | 6 +- .../Hosting/CorsTests.cs | 10 +- .../Hosting/DynamicProvidersTests.cs | 48 +-- .../Hosting/FederatedSignoutTests.cs | 38 +- .../Hosting/IdentityServerMiddlewareTests..cs | 12 +- .../Hosting/LicenseTests.cs | 4 +- .../LocalApiAuthenticationTests.cs | 64 +-- .../Hosting/ServerSideSessionTests.cs | 134 +++--- .../Hosting/SubpathHosting.cs | 4 +- .../IdentityServer.IntegrationTests.csproj | 4 +- .../TestFramework/GenericHost.cs | 6 +- .../TestFramework/TestBrowserClient.cs | 24 +- .../Caches/ResourceStoreCacheTests.cs | 20 +- .../Common/TestEventService.cs | 4 +- .../Cors/PolicyProviderTests.cs | 22 +- .../AuthorizeCallbackEndpointTests.cs | 20 +- .../Authorize/AuthorizeEndpointBaseTests.cs | 30 +- .../Authorize/AuthorizeEndpointTests.cs | 8 +- .../EndSessionCallbackResultTests.cs | 6 +- .../Endpoints/Results/AuthorizeResultTests.cs | 90 ++-- .../Results/CheckSessionResultTests.cs | 26 +- .../Results/EndSessionCallbackResultTests.cs | 36 +- .../Results/EndSessionResultTests.cs | 20 +- .../Events/EventTests.cs | 4 +- ...iResourceSigningAlgorithmSelectionTests.cs | 14 +- .../Extensions/HttpRequestExtensionsTests.cs | 8 +- .../IResourceStoreExtensionsTests.cs | 18 +- ...yServerBuilderExtensionsCacheStoreTests.cs | 6 +- .../Extensions/StringExtensionsTests.cs | 72 ++-- .../Hosting/EndpointRouterTests.cs | 14 +- .../IdentityServer.UnitTests.csproj | 3 +- .../Infrastructure/ObjectSerializerTests.cs | 4 +- .../IdentityServerLicenseValidatorTests.cs | 338 +++++++-------- .../Licensing/v2/LicenseAccessorTests.cs | 38 +- .../Licensing/v2/LicenseUsageTests.cs | 36 +- .../v2/ProtocolRequestCounterTests.cs | 19 +- ...horizeInteractionResponseGeneratorTests.cs | 22 +- ...teractionResponseGeneratorTests_Consent.cs | 78 ++-- ...nteractionResponseGeneratorTests_Custom.cs | 20 +- ...InteractionResponseGeneratorTests_Login.cs | 26 +- ...viceAuthorizationResponseGeneratorTests.cs | 56 +-- .../UserInfoResponseGeneratorTests.cs | 37 +- .../DefaultBackChannelLogoutServiceTests.cs | 4 +- ...elAuthenticationInteractionServiceTests.cs | 64 +-- .../Default/DefaultClaimsServiceTests.cs | 82 ++-- .../Default/DefaultConsentServiceTests.cs | 32 +- .../Default/DefaultCorsPolicyServiceTests.cs | 18 +- .../Default/DefaultEventServiceTests.cs | 4 +- ...ltIdentityServerInteractionServiceTests.cs | 24 +- .../DefaultPersistedGrantServiceTests.cs | 74 ++-- .../DefaultRefreshTokenServiceTests.cs | 74 ++-- .../Default/DefaultTokenServiceTests.cs | 26 +- .../Default/DefaultUserSessionTests.cs | 56 +-- ...ributedDeviceFlowThrottlingServiceTests.cs | 20 +- .../InMemoryKeyStoreCacheTests.cs | 12 +- .../KeyManagement/KeyManagerOptionsTests.cs | 34 +- .../Default/KeyManagement/KeyManagerTests.cs | 252 +++++------ .../Default/NumericUserCodeServiceTests.cs | 6 +- .../Default/OidcReturnUrlParserTests.cs | 18 +- .../Default/ParRedirectUriValidatorTests.cs | 16 +- .../InMemory/InMemoryCorsPolicyService.cs | 14 +- .../Default/CachingResourceStoreTests.cs | 96 ++--- .../DefaultPersistedGrantStoreTests.cs | 96 ++--- ...uthorizationParametersMessageStoreTests.cs | 8 +- .../Stores/InMemoryClientStoreTests.cs | 4 +- .../Stores/InMemoryDeviceFlowStoreTests.cs | 46 +- .../InMemoryPersistedGrantStoreTests.cs | 340 +++++++-------- .../Stores/InMemoryResourcesStoreTests.cs | 8 +- .../Validation/AccessTokenValidation.cs | 72 ++-- .../Authorize_ClientValidation_Code.cs | 26 +- .../Authorize_ClientValidation_IdToken.cs | 6 +- .../Authorize_ClientValidation_Invalid.cs | 6 +- .../Authorize_ClientValidation_Token.cs | 14 +- .../Authorize_ClientValidation_Valid.cs | 28 +- ...rize_ProtocolValidation_CustomValidator.cs | 10 +- .../Authorize_ProtocolValidation_Invalid.cs | 92 ++-- .../Authorize_ProtocolValidation_PAR.cs | 14 +- .../Authorize_ProtocolValidation_PKCE.cs | 40 +- .../Authorize_ProtocolValidation_Resources.cs | 38 +- .../Authorize_ProtocolValidation_Valid.cs | 44 +- .../Validation/BearerTokenUsageValidation.cs | 30 +- .../ClientConfigurationValidation.cs | 38 +- .../Validation/DPoPProofValidatorTests.cs | 209 +++++---- .../DeviceAuthorizationRequestValidation.cs | 98 ++--- .../Validation/DeviceCodeValidation.cs | 36 +- .../EndSessionRequestValidatorTests.cs | 42 +- .../Validation/GrantTypesValidation.cs | 18 +- ...IdentityProviderConfigurationValidation.cs | 34 +- .../Validation/IdentityTokenValidation.cs | 18 +- .../IntrospectionRequestValidatorTests.cs | 46 +- .../Validation/IsLocalUrlTests.cs | 24 +- .../Validation/ResourceValidation.cs | 126 +++--- .../ResponseTypeEqualityComparison.cs | 32 +- .../Validation/RevocationRequestValidation.cs | 32 +- .../BasicAuthenticationCredentialParsing.cs | 48 +-- .../Secrets/ClientAssertionSecretParsing.cs | 22 +- .../Secrets/ClientSecretValidation.cs | 20 +- .../Secrets/FormPostCredentialParsing.cs | 22 +- .../Secrets/HashedSharedSecretValidation.cs | 22 +- .../Secrets/MutualTlsSecretValidation.cs | 18 +- .../PlainTextClientSecretValidation.cs | 22 +- .../Secrets/PrivateKeyJwtSecretValidation.cs | 24 +- .../Validation/Secrets/SecretValidation.cs | 22 +- ...ctRedirectUriValidatorAppAuthValidation.cs | 8 +- ...estValidation_ClientCredentials_Invalid.cs | 48 +-- .../TokenRequestValidation_Code_Invalid.cs | 72 ++-- ...kenRequestValidation_DeviceCode_Invalid.cs | 26 +- ...questValidation_ExtensionGrants_Invalid.cs | 18 +- .../TokenRequestValidation_General_Invalid.cs | 18 +- .../TokenRequestValidation_PKCE.cs | 24 +- ...nRequestValidation_RefreshToken_Invalid.cs | 50 +-- ...RequestValidation_ResourceOwner_Invalid.cs | 62 +-- .../TokenRequestValidation_Valid.cs | 32 +- .../Validation/UserInfoRequestValidation.cs | 12 +- .../ShouldlyExtensions/ShouldlyExtensions.cs | 69 +++ .../ShouldlyExtensions.csproj | 15 + 175 files changed, 4582 insertions(+), 4508 deletions(-) create mode 100644 shared/ShouldlyExtensions/ShouldlyExtensions.cs create mode 100644 shared/ShouldlyExtensions/ShouldlyExtensions.csproj diff --git a/.gitignore b/.gitignore index a91fa0cbc..dad4616ad 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +# MacOs +.DS_Store + # Rider .idea @@ -214,4 +217,7 @@ src/IdentityServer4/host/identityserver.db tempkey.jwk keys *.key -test/Configuration.IntegrationTests/CoverageReports \ No newline at end of file +test/Configuration.IntegrationTests/CoverageReports +Duende.BFF.db +*.db-shm +*.db-wal diff --git a/identity-server/Duende.IdentityServer.sln b/identity-server/Duende.IdentityServer.sln index e67eba2e3..a9bfc4f08 100644 --- a/identity-server/Duende.IdentityServer.sln +++ b/identity-server/Duende.IdentityServer.sln @@ -49,6 +49,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Duende.IdentityServer.Confi EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Configuration.IntegrationTests", "test\Configuration.IntegrationTests\Configuration.IntegrationTests.csproj", "{5882A7DB-BD70-481C-A249-3A422652AFD6}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShouldlyExtensions", "..\shared\ShouldlyExtensions\ShouldlyExtensions.csproj", "{5C742DF6-1262-41BA-AA49-65C7E54435B4}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -287,6 +289,18 @@ Global {5882A7DB-BD70-481C-A249-3A422652AFD6}.Release|x64.Build.0 = Release|Any CPU {5882A7DB-BD70-481C-A249-3A422652AFD6}.Release|x86.ActiveCfg = Release|Any CPU {5882A7DB-BD70-481C-A249-3A422652AFD6}.Release|x86.Build.0 = Release|Any CPU + {5C742DF6-1262-41BA-AA49-65C7E54435B4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5C742DF6-1262-41BA-AA49-65C7E54435B4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5C742DF6-1262-41BA-AA49-65C7E54435B4}.Debug|x64.ActiveCfg = Debug|Any CPU + {5C742DF6-1262-41BA-AA49-65C7E54435B4}.Debug|x64.Build.0 = Debug|Any CPU + {5C742DF6-1262-41BA-AA49-65C7E54435B4}.Debug|x86.ActiveCfg = Debug|Any CPU + {5C742DF6-1262-41BA-AA49-65C7E54435B4}.Debug|x86.Build.0 = Debug|Any CPU + {5C742DF6-1262-41BA-AA49-65C7E54435B4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5C742DF6-1262-41BA-AA49-65C7E54435B4}.Release|Any CPU.Build.0 = Release|Any CPU + {5C742DF6-1262-41BA-AA49-65C7E54435B4}.Release|x64.ActiveCfg = Release|Any CPU + {5C742DF6-1262-41BA-AA49-65C7E54435B4}.Release|x64.Build.0 = Release|Any CPU + {5C742DF6-1262-41BA-AA49-65C7E54435B4}.Release|x86.ActiveCfg = Release|Any CPU + {5C742DF6-1262-41BA-AA49-65C7E54435B4}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -311,6 +325,7 @@ Global {C0AE6878-A605-4EA9-8439-2EBB1EF09AAA} = {D5E9E8E5-4050-4B9A-9F1F-15FA3BDB0684} {754825F1-5386-4343-A3AA-41D31B66179C} = {D5E9E8E5-4050-4B9A-9F1F-15FA3BDB0684} {5882A7DB-BD70-481C-A249-3A422652AFD6} = {DF26567D-46BB-4720-8610-EC3D6AB9793C} + {5C742DF6-1262-41BA-AA49-65C7E54435B4} = {DF26567D-46BB-4720-8610-EC3D6AB9793C} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {FDB095BE-A04A-4440-ACA0-EDD7CF9CFD64} diff --git a/identity-server/test/Configuration.IntegrationTests/Configuration.IntegrationTests.csproj b/identity-server/test/Configuration.IntegrationTests/Configuration.IntegrationTests.csproj index 2949921cf..1bce1f959 100644 --- a/identity-server/test/Configuration.IntegrationTests/Configuration.IntegrationTests.csproj +++ b/identity-server/test/Configuration.IntegrationTests/Configuration.IntegrationTests.csproj @@ -16,7 +16,7 @@ - + diff --git a/identity-server/test/Configuration.IntegrationTests/DynamicClientRegistrationTests.cs b/identity-server/test/Configuration.IntegrationTests/DynamicClientRegistrationTests.cs index 15bc84cfa..1e112aa6e 100644 --- a/identity-server/test/Configuration.IntegrationTests/DynamicClientRegistrationTests.cs +++ b/identity-server/test/Configuration.IntegrationTests/DynamicClientRegistrationTests.cs @@ -2,7 +2,7 @@ // See LICENSE in the project root for license information. -using FluentAssertions; +using Shouldly; using IntegrationTests.TestHosts; using Xunit; using Duende.IdentityServer.Configuration.Models.DynamicClientRegistration; @@ -30,15 +30,15 @@ public async Task valid_request_creates_new_client() var httpResponse = await ConfigurationHost.HttpClient!.PostAsJsonAsync("/connect/dcr", request); var response = await httpResponse.Content.ReadFromJsonAsync(); - response.Should().NotBeNull(); + response.ShouldNotBeNull(); var newClient = await IdentityServerHost.GetClientAsync(response!.ClientId); // Not null already asserted - newClient.Should().NotBeNull(); - newClient.ClientId.Should().Be(response.ClientId); - newClient.AllowedGrantTypes.Should().BeEquivalentTo(request.GrantTypes); - newClient.ClientName.Should().Be(request.ClientName); - newClient.ClientUri.Should().Be(request.ClientUri.ToString()); - newClient.UserSsoLifetime.Should().Be(request.DefaultMaxAge); - newClient.ClientSecrets.Count.Should().Be(1); - newClient.ClientSecrets.Single().Value.Should().Be(response.ClientSecret.Sha256()); + newClient.ShouldNotBeNull(); + newClient.ClientId.ShouldBe(response.ClientId); + newClient.AllowedGrantTypes.ShouldBeEquivalentTo(request.GrantTypes); + newClient.ClientName.ShouldBe(request.ClientName); + newClient.ClientUri.ShouldBe(request.ClientUri.ToString()); + newClient.UserSsoLifetime.ShouldBe(request.DefaultMaxAge); + newClient.ClientSecrets.Count.ShouldBe(1); + newClient.ClientSecrets.Single().Value.ShouldBe(response.ClientSecret.Sha256()); } } diff --git a/identity-server/test/Configuration.IntegrationTests/DynamicClientRegistrationValidationTests.cs b/identity-server/test/Configuration.IntegrationTests/DynamicClientRegistrationValidationTests.cs index 74383dfea..fda405397 100644 --- a/identity-server/test/Configuration.IntegrationTests/DynamicClientRegistrationValidationTests.cs +++ b/identity-server/test/Configuration.IntegrationTests/DynamicClientRegistrationValidationTests.cs @@ -3,7 +3,7 @@ using System.Net; -using FluentAssertions; +using Shouldly; using IntegrationTests.TestHosts; using Xunit; using Duende.IdentityServer.Configuration.Models.DynamicClientRegistration; @@ -18,7 +18,7 @@ public class DynamicClientRegistrationValidationTests : ConfigurationIntegration public async Task http_get_method_should_fail() { var response = await ConfigurationHost.HttpClient!.GetAsync("/connect/dcr"); - response.StatusCode.Should().Be(HttpStatusCode.MethodNotAllowed); + response.StatusCode.ShouldBe(HttpStatusCode.MethodNotAllowed); } [Fact] @@ -29,7 +29,7 @@ public async Task incorrect_content_type_should_fail() { "grant_types", "authorization_code" } }); var response = await ConfigurationHost.HttpClient!.PostAsync("/connect/dcr", content); - response.StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType); + response.StatusCode.ShouldBe(HttpStatusCode.UnsupportedMediaType); } [Fact] @@ -39,10 +39,10 @@ public async Task missing_grant_type_should_fail() { redirect_uris = new[] { "https://example.com/callback" } }); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var error = await response.Content.ReadFromJsonAsync(); - error?.Error.Should().Be("invalid_client_metadata"); + error?.Error.ShouldBe("invalid_client_metadata"); } [Fact] @@ -53,10 +53,10 @@ public async Task unsupported_grant_type_should_fail() redirect_uris = new[] { "https://example.com/callback" }, grant_types = new[] { "password" } }); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var error = await response.Content.ReadFromJsonAsync(); - error?.Error.Should().Be("invalid_client_metadata"); + error?.Error.ShouldBe("invalid_client_metadata"); } [Fact] @@ -67,10 +67,10 @@ public async Task client_credentials_with_redirect_uri_should_fail() redirect_uris = new[] { "https://example.com/callback" }, grant_types = new[] { "client_credentials" } }); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var error = await response.Content.ReadFromJsonAsync(); - error?.Error.Should().Be("invalid_redirect_uri"); + error?.Error.ShouldBe("invalid_redirect_uri"); } [Fact] @@ -80,10 +80,10 @@ public async Task auth_code_without_redirect_uri_should_fail() { grant_types = new[] { "authorization_code", "client_credentials" } }); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var error = await response.Content.ReadFromJsonAsync(); - error?.Error.Should().Be("invalid_redirect_uri"); + error?.Error.ShouldBe("invalid_redirect_uri"); } [Fact] @@ -93,10 +93,10 @@ public async Task client_credentials_and_refresh_token_should_fail() { grant_types = new[] { "client_credentials", "refresh_token" } }); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var error = await response.Content.ReadFromJsonAsync(); - error?.Error.Should().Be("invalid_client_metadata"); + error?.Error.ShouldBe("invalid_client_metadata"); } [Fact] @@ -110,9 +110,9 @@ public async Task jwks_and_jwks_uri_used_together_should_fail() JwksUri = new Uri("https://example.com") } ); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var error = await response.Content.ReadFromJsonAsync(); - error?.Error.Should().Be("invalid_client_metadata"); + error?.Error.ShouldBe("invalid_client_metadata"); } } diff --git a/identity-server/test/EntityFramework.IntegrationTests/EntityFramework.IntegrationTests.csproj b/identity-server/test/EntityFramework.IntegrationTests/EntityFramework.IntegrationTests.csproj index c2edfc586..975e7d7cc 100644 --- a/identity-server/test/EntityFramework.IntegrationTests/EntityFramework.IntegrationTests.csproj +++ b/identity-server/test/EntityFramework.IntegrationTests/EntityFramework.IntegrationTests.csproj @@ -5,7 +5,7 @@ - + diff --git a/identity-server/test/EntityFramework.Storage.IntegrationTests/EntityFramework.Storage.IntegrationTests.csproj b/identity-server/test/EntityFramework.Storage.IntegrationTests/EntityFramework.Storage.IntegrationTests.csproj index fc6c2d40e..908b59673 100644 --- a/identity-server/test/EntityFramework.Storage.IntegrationTests/EntityFramework.Storage.IntegrationTests.csproj +++ b/identity-server/test/EntityFramework.Storage.IntegrationTests/EntityFramework.Storage.IntegrationTests.csproj @@ -9,7 +9,7 @@ - + @@ -28,6 +28,7 @@ + diff --git a/identity-server/test/EntityFramework.Storage.IntegrationTests/Stores/ClientStoreTests.cs b/identity-server/test/EntityFramework.Storage.IntegrationTests/Stores/ClientStoreTests.cs index d9e28015f..053043ba2 100644 --- a/identity-server/test/EntityFramework.Storage.IntegrationTests/Stores/ClientStoreTests.cs +++ b/identity-server/test/EntityFramework.Storage.IntegrationTests/Stores/ClientStoreTests.cs @@ -11,7 +11,7 @@ using Duende.IdentityServer.EntityFramework.Stores; using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; -using FluentAssertions; +using Shouldly; using Microsoft.EntityFrameworkCore; using Xunit; using Xunit.Sdk; @@ -60,7 +60,7 @@ public async Task FindClientByIdAsync_WhenClientExists_ExpectClientReturned(DbCo client = await store.FindClientByIdAsync(testClient.ClientId); } - client.Should().NotBeNull(); + client.ShouldNotBeNull(); } [Theory, MemberData(nameof(TestDatabaseProviders))] @@ -94,7 +94,7 @@ public async Task FindClientByIdAsync_WhenClientExistsWithCollections_ExpectClie client = await store.FindClientByIdAsync(testClient.ClientId); } - client.Should().BeEquivalentTo(testClient); + client.ShouldBeEquivalentTo(testClient); } [Theory, MemberData(nameof(TestDatabaseProviders))] @@ -148,7 +148,7 @@ public async Task FindClientByIdAsync_WhenClientsExistWithManyCollections_Expect #pragma warning disable xUnit1031 // Do not use blocking task operations in test method, suppressed because the task must have completed to enter this block var client = task.Result; #pragma warning restore xUnit1031 // Do not use blocking task operations in test method - client.Should().BeEquivalentTo(testClient); + client.ShouldBeEquivalentTo(testClient); } else { diff --git a/identity-server/test/EntityFramework.Storage.IntegrationTests/Stores/DeviceFlowStoreTests.cs b/identity-server/test/EntityFramework.Storage.IntegrationTests/Stores/DeviceFlowStoreTests.cs index dae7565d5..c98fd545c 100644 --- a/identity-server/test/EntityFramework.Storage.IntegrationTests/Stores/DeviceFlowStoreTests.cs +++ b/identity-server/test/EntityFramework.Storage.IntegrationTests/Stores/DeviceFlowStoreTests.cs @@ -14,7 +14,7 @@ using Duende.IdentityServer.EntityFramework.Stores; using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores.Serialization; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using Microsoft.EntityFrameworkCore.InMemory.Infrastructure.Internal; using Xunit; @@ -57,9 +57,9 @@ public async Task StoreDeviceAuthorizationAsync_WhenSuccessful_ExpectDeviceCodeA { var foundDeviceFlowCodes = context.DeviceFlowCodes.FirstOrDefault(x => x.DeviceCode == deviceCode); - foundDeviceFlowCodes.Should().NotBeNull(); - foundDeviceFlowCodes?.DeviceCode.Should().Be(deviceCode); - foundDeviceFlowCodes?.UserCode.Should().Be(userCode); + foundDeviceFlowCodes.ShouldNotBeNull(); + foundDeviceFlowCodes?.DeviceCode.ShouldBe(deviceCode); + foundDeviceFlowCodes?.UserCode.ShouldBe(userCode); } } @@ -85,12 +85,12 @@ public async Task StoreDeviceAuthorizationAsync_WhenSuccessful_ExpectDataStored( { var foundDeviceFlowCodes = context.DeviceFlowCodes.FirstOrDefault(x => x.DeviceCode == deviceCode); - foundDeviceFlowCodes.Should().NotBeNull(); + foundDeviceFlowCodes.ShouldNotBeNull(); var deserializedData = new PersistentGrantSerializer().Deserialize(foundDeviceFlowCodes?.Data); - deserializedData.CreationTime.Should().BeCloseTo(data.CreationTime, TimeSpan.FromMicroseconds(1)); - deserializedData.ClientId.Should().Be(data.ClientId); - deserializedData.Lifetime.Should().Be(data.Lifetime); + deserializedData.CreationTime.ShouldBeCloseTo(data.CreationTime, TimeSpan.FromMicroseconds(1)); + deserializedData.ClientId.ShouldBe(data.ClientId); + deserializedData.Lifetime.ShouldBe(data.Lifetime); } } @@ -222,11 +222,11 @@ public async Task FindByUserCodeAsync_WhenUserCodeExists_ExpectDataRetrievedCorr var store = new DeviceFlowStore(context, new PersistentGrantSerializer(), FakeLogger.Create(), new NoneCancellationTokenProvider()); code = await store.FindByUserCodeAsync(testUserCode); } - - code.Should().BeEquivalentTo(expectedDeviceCodeData, - assertionOptions => assertionOptions.Excluding(x=> x.Subject)); - code.Subject.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject && x.Value == expectedSubject).Should().NotBeNull(); + code.ShouldBe(expectedDeviceCodeData); + //assertionOptions => assertionOptions.Excluding(x=> x.Subject)); + + code.Subject.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject && x.Value == expectedSubject).ShouldNotBeNull(); } [Theory, MemberData(nameof(TestDatabaseProviders))] @@ -236,7 +236,7 @@ public async Task FindByUserCodeAsync_WhenUserCodeDoesNotExist_ExpectNull(DbCont { var store = new DeviceFlowStore(context, new PersistentGrantSerializer(), FakeLogger.Create(), new NoneCancellationTokenProvider()); var code = await store.FindByUserCodeAsync($"user_{Guid.NewGuid().ToString()}"); - code.Should().BeNull(); + code.ShouldBeNull(); } } @@ -279,10 +279,10 @@ public async Task FindByDeviceCodeAsync_WhenDeviceCodeExists_ExpectDataRetrieved code = await store.FindByDeviceCodeAsync(testDeviceCode); } - code.Should().BeEquivalentTo(expectedDeviceCodeData, - assertionOptions => assertionOptions.Excluding(x => x.Subject)); + code.ShouldBe(expectedDeviceCodeData); + //assertionOptions => assertionOptions.Excluding(x => x.Subject)); - code.Subject.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject && x.Value == expectedSubject).Should().NotBeNull(); + code.Subject.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject && x.Value == expectedSubject).ShouldNotBeNull(); } [Theory, MemberData(nameof(TestDatabaseProviders))] @@ -292,7 +292,7 @@ public async Task FindByDeviceCodeAsync_WhenDeviceCodeDoesNotExist_ExpectNull(Db { var store = new DeviceFlowStore(context, new PersistentGrantSerializer(), FakeLogger.Create(), new NoneCancellationTokenProvider()); var code = await store.FindByDeviceCodeAsync($"device_{Guid.NewGuid().ToString()}"); - code.Should().BeNull(); + code.ShouldBeNull(); } } @@ -351,15 +351,16 @@ public async Task UpdateByUserCodeAsync_WhenDeviceCodeAuthorized_ExpectSubjectAn } // should be unchanged - updatedCodes.DeviceCode.Should().Be(testDeviceCode); - updatedCodes.ClientId.Should().Be(unauthorizedDeviceCode.ClientId); - updatedCodes.CreationTime.Should().Be(unauthorizedDeviceCode.CreationTime); - updatedCodes.Expiration.Should().Be(unauthorizedDeviceCode.CreationTime.AddSeconds(authorizedDeviceCode.Lifetime)); + updatedCodes.DeviceCode.ShouldBe(testDeviceCode); + updatedCodes.ClientId.ShouldBe(unauthorizedDeviceCode.ClientId); + updatedCodes.CreationTime.ShouldBe(unauthorizedDeviceCode.CreationTime); + updatedCodes.Expiration.ShouldBe(unauthorizedDeviceCode.CreationTime.AddSeconds(authorizedDeviceCode.Lifetime)); // should be changed var parsedCode = serializer.Deserialize(updatedCodes.Data); - parsedCode.Should().BeEquivalentTo(authorizedDeviceCode, assertionOptions => assertionOptions.Excluding(x => x.Subject)); - parsedCode.Subject.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject && x.Value == expectedSubject).Should().NotBeNull(); + parsedCode.ShouldBe(authorizedDeviceCode); + //parsedCode.ShouldBeEquivalentTo(authorizedDeviceCode, assertionOptions => assertionOptions.Excluding(x => x.Subject)); + parsedCode.Subject.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject && x.Value == expectedSubject).ShouldNotBeNull(); } [Theory, MemberData(nameof(TestDatabaseProviders))] @@ -399,7 +400,7 @@ public async Task RemoveByDeviceCodeAsync_WhenDeviceCodeExists_ExpectDeviceCodeD using (var context = new PersistedGrantDbContext(options)) { - context.DeviceFlowCodes.FirstOrDefault(x => x.UserCode == testUserCode).Should().BeNull(); + context.DeviceFlowCodes.FirstOrDefault(x => x.UserCode == testUserCode).ShouldBeNull(); } } [Theory, MemberData(nameof(TestDatabaseProviders))] diff --git a/identity-server/test/EntityFramework.Storage.IntegrationTests/Stores/IdentityProviderStoreTests.cs b/identity-server/test/EntityFramework.Storage.IntegrationTests/Stores/IdentityProviderStoreTests.cs index 07f2b1e21..68a6f18f6 100644 --- a/identity-server/test/EntityFramework.Storage.IntegrationTests/Stores/IdentityProviderStoreTests.cs +++ b/identity-server/test/EntityFramework.Storage.IntegrationTests/Stores/IdentityProviderStoreTests.cs @@ -10,7 +10,7 @@ using Duende.IdentityServer.EntityFramework.Stores; using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; -using FluentAssertions; +using Shouldly; using Microsoft.EntityFrameworkCore; using Xunit; @@ -47,7 +47,7 @@ public async Task GetBySchemeAsync_should_find_by_scheme(DbContextOptions.Create(), new NoneCancellationTokenProvider()); var item = await store.GetBySchemeAsync("scheme1"); - item.Should().NotBeNull(); + item.ShouldNotBeNull(); } } @@ -70,7 +70,7 @@ public async Task GetBySchemeAsync_should_filter_by_type(DbContextOptions.Create(), new NoneCancellationTokenProvider()); var item = await store.GetBySchemeAsync("scheme2"); - item.Should().BeNull(); + item.ShouldBeNull(); } } @@ -93,7 +93,7 @@ public async Task GetBySchemeAsync_should_filter_by_scheme_casing(DbContextOptio var store = new IdentityProviderStore(context, FakeLogger.Create(), new NoneCancellationTokenProvider()); var item = await store.GetBySchemeAsync("scheme3"); - item.Should().BeNull(); + item.ShouldBeNull(); } } } \ No newline at end of file diff --git a/identity-server/test/EntityFramework.Storage.IntegrationTests/Stores/PersistedGrantStoreTests.cs b/identity-server/test/EntityFramework.Storage.IntegrationTests/Stores/PersistedGrantStoreTests.cs index 27a8e4b79..05979739b 100644 --- a/identity-server/test/EntityFramework.Storage.IntegrationTests/Stores/PersistedGrantStoreTests.cs +++ b/identity-server/test/EntityFramework.Storage.IntegrationTests/Stores/PersistedGrantStoreTests.cs @@ -13,7 +13,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; -using FluentAssertions; +using Shouldly; using Microsoft.EntityFrameworkCore; using Xunit; @@ -132,57 +132,57 @@ public async Task GetAllAsync_Should_Filter(DbContextOptions x.Key == expiredGrant.Key).Should().BeNull(); + context.PersistedGrants.FirstOrDefault(x => x.Key == expiredGrant.Key).ShouldBeNull(); } } @@ -96,7 +96,7 @@ public async Task CleanupGrantsAsync_WhenValidGrantsExist_ExpectValidGrantsInDb( using (var context = new PersistedGrantDbContext(options)) { - context.PersistedGrants.FirstOrDefault(x => x.Key == validGrant.Key).Should().NotBeNull(); + context.PersistedGrants.FirstOrDefault(x => x.Key == validGrant.Key).ShouldNotBeNull(); } } @@ -142,8 +142,8 @@ public async Task CleanupGrantsAsync_WhenBothExpiredAndValidGrantsExists_ExpectO { var remaining = context.PersistedGrants.ToList(); - remaining.Count.Should().Be(15); - remaining.All(r => r.Key.StartsWith("valid-")).Should().BeTrue(); + remaining.Count.ShouldBe(15); + remaining.All(r => r.Key.StartsWith("valid-")).ShouldBeTrue(); } } @@ -171,7 +171,7 @@ public async Task CleanupGrantsAsync_WhenExpiredDeviceGrantsExist_ExpectExpiredD using (var context = new PersistedGrantDbContext(options)) { - context.DeviceFlowCodes.FirstOrDefault(x => x.DeviceCode == expiredGrant.DeviceCode).Should().BeNull(); + context.DeviceFlowCodes.FirstOrDefault(x => x.DeviceCode == expiredGrant.DeviceCode).ShouldBeNull(); } } @@ -199,7 +199,7 @@ public async Task CleanupGrantsAsync_WhenValidDeviceGrantsExist_ExpectValidDevic using (var context = new PersistedGrantDbContext(options)) { - context.DeviceFlowCodes.FirstOrDefault(x => x.DeviceCode == validGrant.DeviceCode).Should().NotBeNull(); + context.DeviceFlowCodes.FirstOrDefault(x => x.DeviceCode == validGrant.DeviceCode).ShouldNotBeNull(); } } @@ -228,7 +228,7 @@ public async Task CleanupGrantsAsync_WhenFlagIsOnAndConsumedGrantsExist_ExpectCo using (var context = new PersistedGrantDbContext(options)) { - context.PersistedGrants.FirstOrDefault(x => x.Id == consumedGrant.Id).Should().BeNull(); + context.PersistedGrants.FirstOrDefault(x => x.Id == consumedGrant.Id).ShouldBeNull(); } } @@ -256,7 +256,7 @@ public async Task CleanupGrantsAsync_WhenFlagIsOffAndConsumedGrantsExist_ExpectC using (var context = new PersistedGrantDbContext(options)) { - context.PersistedGrants.FirstOrDefault(x => x.Id == consumedGrant.Id).Should().NotBeNull(); + context.PersistedGrants.FirstOrDefault(x => x.Id == consumedGrant.Id).ShouldNotBeNull(); } } @@ -270,7 +270,7 @@ public async Task CleanupGrantsAsync_ExpectBatchSizeIsRespected(DbContextOptions using (var context = new PersistedGrantDbContext(options)) { - context.PersistedGrants.ToList().Should().BeEmpty(); + context.PersistedGrants.ToList().ShouldBeEmpty(); for(int i = 0; i < StoreOptions.TokenCleanupBatchSize * expectedPageCount; i++) { @@ -287,7 +287,7 @@ public async Task CleanupGrantsAsync_ExpectBatchSizeIsRespected(DbContextOptions } context.SaveChanges(); - context.PersistedGrants.Count().Should().Be(StoreOptions.TokenCleanupBatchSize * expectedPageCount); + context.PersistedGrants.Count().ShouldBe(StoreOptions.TokenCleanupBatchSize * expectedPageCount); } @@ -298,18 +298,18 @@ await CreateSut(options, svcs => { }).CleanupGrantsAsync(); // The right number of batches executed - mockNotifications.PersistedGrantNotifications.Count.Should().Be(expectedPageCount); + mockNotifications.PersistedGrantNotifications.Count.ShouldBe(expectedPageCount); // Each batch contained the expected number of grants foreach(var notification in mockNotifications.PersistedGrantNotifications) { - notification.Count().Should().Be(StoreOptions.TokenCleanupBatchSize); + notification.Count().ShouldBe(StoreOptions.TokenCleanupBatchSize); } // All grants are removed because they were all expired using (var context = new PersistedGrantDbContext(options)) { - context.PersistedGrants.ToList().Should().BeEmpty(); + context.PersistedGrants.ToList().ShouldBeEmpty(); } } @@ -366,16 +366,16 @@ await CreateSut(options, svcs => { // Each batch created an extra grant, so we do an extra batch to clean up // the extras - mockNotifications.PersistedGrantNotifications.Count.Should().Be(expectedPageCount + 1); + mockNotifications.PersistedGrantNotifications.Count.ShouldBe(expectedPageCount + 1); // Each batch had the expected number of grants. Most batches had the batch size grants for(int i = 0; i < expectedPageCount; i++) { - mockNotifications.PersistedGrantNotifications[i].Count().Should().Be(StoreOptions.TokenCleanupBatchSize); + mockNotifications.PersistedGrantNotifications[i].Count().ShouldBe(StoreOptions.TokenCleanupBatchSize); } // The last batch had the extras - there is one extra per page - mockNotifications.PersistedGrantNotifications.Last().Count().Should().Be(expectedPageCount); + mockNotifications.PersistedGrantNotifications.Last().Count().ShouldBe(expectedPageCount); // In the end, all but one get deleted // One final grant will be left behind, created by the last notification to fire @@ -383,7 +383,7 @@ await CreateSut(options, svcs => { // we just are able to observe it because it was created in the final batch's notification using (var context = new PersistedGrantDbContext(options)) { - context.PersistedGrants.Count().Should().Be(1); + context.PersistedGrants.Count().ShouldBe(1); } } @@ -427,8 +427,8 @@ public async Task CleanupGrantsAsync_WhenFlagIsOnAndConsumedGrantsExistAndDelayI using (var context = new PersistedGrantDbContext(options)) { - context.PersistedGrants.FirstOrDefault(x => x.Id == newConsumedGrant.Id).Should().NotBeNull(); - context.PersistedGrants.FirstOrDefault(x => x.Id == oldConsumedGrant.Id).Should().BeNull(); + context.PersistedGrants.FirstOrDefault(x => x.Id == newConsumedGrant.Id).ShouldNotBeNull(); + context.PersistedGrants.FirstOrDefault(x => x.Id == oldConsumedGrant.Id).ShouldBeNull(); } } diff --git a/identity-server/test/EntityFramework.Storage.UnitTests/EntityFramework.Storage.UnitTests.csproj b/identity-server/test/EntityFramework.Storage.UnitTests/EntityFramework.Storage.UnitTests.csproj index d77d1eb01..80c514c8a 100644 --- a/identity-server/test/EntityFramework.Storage.UnitTests/EntityFramework.Storage.UnitTests.csproj +++ b/identity-server/test/EntityFramework.Storage.UnitTests/EntityFramework.Storage.UnitTests.csproj @@ -5,7 +5,7 @@ - + diff --git a/identity-server/test/EntityFramework.Storage.UnitTests/IsLocalUrlTests.cs b/identity-server/test/EntityFramework.Storage.UnitTests/IsLocalUrlTests.cs index 8f93f495b..201df7830 100644 --- a/identity-server/test/EntityFramework.Storage.UnitTests/IsLocalUrlTests.cs +++ b/identity-server/test/EntityFramework.Storage.UnitTests/IsLocalUrlTests.cs @@ -1,5 +1,5 @@ using System.Collections.Generic; -using FluentAssertions; +using Shouldly; using Xunit; using Duende.IdentityServer.EntityFramework.Extensions; @@ -57,6 +57,6 @@ public class IsLocalUrlTests [MemberData(nameof(TestCases))] public void IsLocalUrl(string returnUrl, bool expected) { - returnUrl.IsLocalUrl().Should().Be(expected); + returnUrl.IsLocalUrl().ShouldBe(expected); } } \ No newline at end of file diff --git a/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/ApiResourceMappersTests.cs b/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/ApiResourceMappersTests.cs index 5af6af492..e0a5c46b0 100644 --- a/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/ApiResourceMappersTests.cs +++ b/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/ApiResourceMappersTests.cs @@ -4,7 +4,7 @@ using System.Linq; using Duende.IdentityServer.EntityFramework.Mappers; -using FluentAssertions; +using Shouldly; using Xunit; using Models = Duende.IdentityServer.Models; using Entities = Duende.IdentityServer.EntityFramework.Entities; @@ -39,19 +39,19 @@ public void Properties_Map() var mappedEntity = model.ToEntity(); - mappedEntity.Scopes.Count.Should().Be(2); + mappedEntity.Scopes.Count.ShouldBe(2); var foo1 = mappedEntity.Scopes.FirstOrDefault(x => x.Scope == "foo1"); - foo1.Should().NotBeNull(); + foo1.ShouldNotBeNull(); var foo2 = mappedEntity.Scopes.FirstOrDefault(x => x.Scope == "foo2"); - foo2.Should().NotBeNull(); + foo2.ShouldNotBeNull(); var mappedModel = mappedEntity.ToModel(); - mappedModel.Description.Should().Be("description"); - mappedModel.DisplayName.Should().Be("displayname"); - mappedModel.Enabled.Should().BeFalse(); - mappedModel.Name.Should().Be("foo"); + mappedModel.Description.ShouldBe("description"); + mappedModel.DisplayName.ShouldBe("displayname"); + mappedModel.Enabled.ShouldBeFalse(); + mappedModel.Name.ShouldBe("foo"); } [Fact] @@ -73,7 +73,7 @@ public void missing_values_should_use_defaults() }; var model = entity.ToModel(); - model.ApiSecrets.First().Type.Should().Be(def.ApiSecrets.First().Type); + model.ApiSecrets.First().Type.ShouldBe(def.ApiSecrets.First().Type); } [Fact] @@ -93,8 +93,7 @@ public void mapping_model_to_entity_maps_all_properties() source => source.ToEntity(), excludedProperties, out var unmappedMembers) - .Should() - .BeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); + .ShouldBeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); } [Fact] @@ -102,7 +101,6 @@ public void mapping_entity_to_model_maps_all_properties() { MapperTestHelpers .AllPropertiesAreMapped(source => source.ToModel(), out var unmappedMembers) - .Should() - .BeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); + .ShouldBeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); } } diff --git a/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/ClientMappersTests.cs b/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/ClientMappersTests.cs index 67e4e8331..6c00d2045 100644 --- a/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/ClientMappersTests.cs +++ b/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/ClientMappersTests.cs @@ -5,7 +5,7 @@ using System; using System.Linq; using Duende.IdentityServer.EntityFramework.Mappers; -using FluentAssertions; +using Shouldly; using Xunit; using Models = Duende.IdentityServer.Models; using Entities = Duende.IdentityServer.EntityFramework.Entities; @@ -43,23 +43,23 @@ public void Properties_Map() var mappedEntity = model.ToEntity(); - mappedEntity.Properties.Count.Should().Be(2); + mappedEntity.Properties.Count.ShouldBe(2); var foo1 = mappedEntity.Properties.FirstOrDefault(x => x.Key == "foo1"); - foo1.Should().NotBeNull(); - foo1.Value.Should().Be("bar1"); + foo1.ShouldNotBeNull(); + foo1.Value.ShouldBe("bar1"); var foo2 = mappedEntity.Properties.FirstOrDefault(x => x.Key == "foo2"); - foo2.Should().NotBeNull(); - foo2.Value.Should().Be("bar2"); + foo2.ShouldNotBeNull(); + foo2.Value.ShouldBe("bar2"); var mappedModel = mappedEntity.ToModel(); - mappedModel.Properties.Count.Should().Be(2); - mappedModel.Properties.ContainsKey("foo1").Should().BeTrue(); - mappedModel.Properties.ContainsKey("foo2").Should().BeTrue(); - mappedModel.Properties["foo1"].Should().Be("bar1"); - mappedModel.Properties["foo2"].Should().Be("bar2"); + mappedModel.Properties.Count.ShouldBe(2); + mappedModel.Properties.ContainsKey("foo1").ShouldBeTrue(); + mappedModel.Properties.ContainsKey("foo2").ShouldBeTrue(); + mappedModel.Properties["foo1"].ShouldBe("bar1"); + mappedModel.Properties["foo2"].ShouldBe("bar2"); } [Fact] @@ -75,7 +75,7 @@ public void duplicates_properties_in_db_map() }; Action modelAction = () => entity.ToModel(); - modelAction.Should().Throw(); + modelAction.ShouldThrow(); } [Fact] @@ -97,8 +97,8 @@ public void missing_values_should_use_defaults() }; var model = entity.ToModel(); - model.ProtocolType.Should().Be(def.ProtocolType); - model.ClientSecrets.First().Type.Should().Be(def.ClientSecrets.First().Type); + model.ProtocolType.ShouldBe(def.ProtocolType); + model.ClientSecrets.First().Type.ShouldBe(def.ClientSecrets.First().Type); } @@ -131,8 +131,7 @@ public void mapping_model_to_entity_maps_all_properties() source => source.ToEntity(), notMapped, out var unmappedMembers) - .Should() - .BeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); + .ShouldBeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); } [Fact] @@ -142,8 +141,7 @@ public void mapping_entity_to_model_maps_all_properties() .AllPropertiesAreMapped( source => source.ToModel(), out var unmappedMembers) - .Should() - .BeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); + .ShouldBeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); } enum TestEnum @@ -223,8 +221,7 @@ public void forgetting_to_map_properties_is_checked_by_tests() source => source.ToExtendedEntity(), notMapped, out var unmappedMembers) - .Should() - .BeFalse(); - unmappedMembers.Count.Should().Be(CountForgottenProperties()); + .ShouldBeFalse(); + unmappedMembers.Count.ShouldBe(CountForgottenProperties()); } } \ No newline at end of file diff --git a/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/IdentityProviderMappersTests.cs b/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/IdentityProviderMappersTests.cs index a5f68b060..f7513137d 100644 --- a/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/IdentityProviderMappersTests.cs +++ b/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/IdentityProviderMappersTests.cs @@ -3,7 +3,7 @@ using Duende.IdentityServer.EntityFramework.Mappers; -using FluentAssertions; +using Shouldly; using Xunit; using Models = Duende.IdentityServer.Models; using Entities = Duende.IdentityServer.EntityFramework.Entities; @@ -40,22 +40,22 @@ public void Properties_Map() var mappedEntity = model.ToEntity(); - mappedEntity.DisplayName.Should().Be("name"); - mappedEntity.Scheme.Should().Be("scheme"); - mappedEntity.Type.Should().Be("oidc"); - mappedEntity.Properties.Should().NotBeNullOrEmpty(); + mappedEntity.DisplayName.ShouldBe("name"); + mappedEntity.Scheme.ShouldBe("scheme"); + mappedEntity.Type.ShouldBe("oidc"); + mappedEntity.Properties.ShouldNotBeNullOrEmpty(); var mappedModel = new Models.OidcProvider(mappedEntity.ToModel()); - mappedModel.Authority.Should().Be("auth"); - mappedModel.ClientId.Should().Be("client"); - mappedModel.ClientSecret.Should().Be("secret"); - mappedModel.DisplayName.Should().Be("name"); - mappedModel.ResponseType.Should().Be("rt"); - mappedModel.Scheme.Should().Be("scheme"); - mappedModel.Scope.Should().Be("scope"); - mappedModel.Type.Should().Be("oidc"); + mappedModel.Authority.ShouldBe("auth"); + mappedModel.ClientId.ShouldBe("client"); + mappedModel.ClientSecret.ShouldBe("secret"); + mappedModel.DisplayName.ShouldBe("name"); + mappedModel.ResponseType.ShouldBe("rt"); + mappedModel.Scheme.ShouldBe("scheme"); + mappedModel.Scope.ShouldBe("scope"); + mappedModel.Type.ShouldBe("oidc"); } [Fact] @@ -75,8 +75,7 @@ public void mapping_model_to_entity_maps_all_properties() source => source.ToEntity(), excludedProperties, out var unmappedMembers) - .Should() - .BeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); + .ShouldBeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); } [Fact] @@ -95,7 +94,6 @@ public void mapping_entity_to_model_maps_all_properties() }, source => source.ToModel(), out var unmappedMembers) - .Should() - .BeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); + .ShouldBeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); } } diff --git a/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/IdentityResourcesMappersTests.cs b/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/IdentityResourcesMappersTests.cs index 91d2969b2..29863b9ae 100644 --- a/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/IdentityResourcesMappersTests.cs +++ b/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/IdentityResourcesMappersTests.cs @@ -6,7 +6,7 @@ using Xunit; using Models = Duende.IdentityServer.Models; using Entities = Duende.IdentityServer.EntityFramework.Entities; -using FluentAssertions; +using Shouldly; namespace EntityFramework.Storage.UnitTests.Mappers; @@ -38,8 +38,7 @@ public void mapping_model_to_entity_maps_all_properties() source => source.ToEntity(), excludedProperties, out var unmappedMembers) - .Should() - .BeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); + .ShouldBeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); } [Fact] @@ -49,7 +48,6 @@ public void mapping_entity_to_model_maps_all_properties() .AllPropertiesAreMapped( source => source.ToModel(), out var unmappedMembers) - .Should() - .BeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); + .ShouldBeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); } } diff --git a/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/PersistedGrantMappersTests.cs b/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/PersistedGrantMappersTests.cs index 9925de87b..50d55fccf 100644 --- a/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/PersistedGrantMappersTests.cs +++ b/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/PersistedGrantMappersTests.cs @@ -3,7 +3,7 @@ using Duende.IdentityServer.EntityFramework.Mappers; -using FluentAssertions; +using Shouldly; using Xunit; using Models = Duende.IdentityServer.Models; using Entities = Duende.IdentityServer.EntityFramework.Entities; @@ -21,10 +21,10 @@ public void CanMap() }; var mappedEntity = model.ToEntity(); - mappedEntity.ConsumedTime.Value.Should().Be(new System.DateTime(2020, 02, 03, 4, 5, 6)); + mappedEntity.ConsumedTime.Value.ShouldBe(new System.DateTime(2020, 02, 03, 4, 5, 6)); var mappedModel = mappedEntity.ToModel(); - mappedModel.ConsumedTime.Value.Should().Be(new System.DateTime(2020, 02, 03, 4, 5, 6)); + mappedModel.ConsumedTime.Value.ShouldBe(new System.DateTime(2020, 02, 03, 4, 5, 6)); Assert.NotNull(mappedModel); Assert.NotNull(mappedEntity); @@ -44,8 +44,7 @@ public void mapping_model_to_entity_maps_all_properties() MapperTestHelpers .AllPropertiesAreMapped(source => source.ToEntity(), excludedProperties, out var unmappedMembers) - .Should() - .BeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); + .ShouldBeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); } [Fact] @@ -53,7 +52,6 @@ public void mapping_entity_to_model_maps_all_properties() { MapperTestHelpers .AllPropertiesAreMapped(source => source.ToModel(), out var unmappedMembers) - .Should() - .BeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); + .ShouldBeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); } } diff --git a/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/PushedAuthorizationRequestMappersTests.cs b/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/PushedAuthorizationRequestMappersTests.cs index 42fe0253c..b0a5dce4f 100644 --- a/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/PushedAuthorizationRequestMappersTests.cs +++ b/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/PushedAuthorizationRequestMappersTests.cs @@ -7,7 +7,7 @@ using Duende.IdentityServer.EntityFramework.Mappers; using Models = Duende.IdentityServer.Models; using Entities = Duende.IdentityServer.EntityFramework.Entities; -using FluentAssertions; +using Shouldly; using Xunit; namespace EntityFramework.Storage.UnitTests.Mappers; @@ -35,8 +35,7 @@ public void mapping_model_to_entity_maps_all_properties() MapperTestHelpers .AllPropertiesAreMapped(source => source.ToEntity(), excludedProperties, out var unmappedMembers) - .Should() - .BeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); + .ShouldBeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); } [Fact] @@ -44,7 +43,6 @@ public void mapping_entity_to_model_maps_all_properties() { MapperTestHelpers .AllPropertiesAreMapped(source => source.ToModel(), out var unmappedMembers) - .Should() - .BeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); + .ShouldBeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); } } \ No newline at end of file diff --git a/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/ScopeMappersTests.cs b/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/ScopeMappersTests.cs index a62a7e5f2..09b24302e 100644 --- a/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/ScopeMappersTests.cs +++ b/identity-server/test/EntityFramework.Storage.UnitTests/Mappers/ScopeMappersTests.cs @@ -7,7 +7,7 @@ using Duende.IdentityServer.EntityFramework.Mappers; using Models = Duende.IdentityServer.Models; using Entities = Duende.IdentityServer.EntityFramework.Entities; -using FluentAssertions; +using Shouldly; using Xunit; namespace EntityFramework.Storage.UnitTests.Mappers; @@ -39,8 +39,7 @@ public void mapping_model_to_entity_maps_all_properties() MapperTestHelpers .AllPropertiesAreMapped(source => source.ToEntity(), excludedProperties, out var unmappedMembers) - .Should() - .BeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); + .ShouldBeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); } [Fact] @@ -48,8 +47,7 @@ public void mapping_entity_to_model_maps_all_properties() { MapperTestHelpers .AllPropertiesAreMapped(source => source.ToModel(), out var unmappedMembers) - .Should() - .BeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); + .ShouldBeTrue($"{string.Join(',', unmappedMembers)} should be mapped"); } [Fact] @@ -70,27 +68,27 @@ public void Properties_Map() var mappedEntity = model.ToEntity(); - mappedEntity.Description.Should().Be("description"); - mappedEntity.DisplayName.Should().Be("displayname"); - mappedEntity.Name.Should().Be("foo"); + mappedEntity.Description.ShouldBe("description"); + mappedEntity.DisplayName.ShouldBe("displayname"); + mappedEntity.Name.ShouldBe("foo"); - mappedEntity.UserClaims.Count.Should().Be(2); - mappedEntity.UserClaims.Select(x => x.Type).Should().BeEquivalentTo(new[] { "c1", "c2" }); - mappedEntity.Properties.Count.Should().Be(2); - mappedEntity.Properties.Should().Contain(x => x.Key == "x" && x.Value == "xx"); - mappedEntity.Properties.Should().Contain(x => x.Key == "y" && x.Value == "yy"); + mappedEntity.UserClaims.Count.ShouldBe(2); + mappedEntity.UserClaims.Select(x => x.Type).ShouldBeEquivalentTo(new[] { "c1", "c2" }); + mappedEntity.Properties.Count.ShouldBe(2); + mappedEntity.Properties.ShouldContain(x => x.Key == "x" && x.Value == "xx"); + mappedEntity.Properties.ShouldContain(x => x.Key == "y" && x.Value == "yy"); var mappedModel = mappedEntity.ToModel(); - mappedModel.Description.Should().Be("description"); - mappedModel.DisplayName.Should().Be("displayname"); - mappedModel.Enabled.Should().BeFalse(); - mappedModel.Name.Should().Be("foo"); - mappedModel.UserClaims.Count.Should().Be(2); - mappedModel.UserClaims.Should().BeEquivalentTo(new[] { "c1", "c2" }); - mappedModel.Properties.Count.Should().Be(2); - mappedModel.Properties["x"].Should().Be("xx"); - mappedModel.Properties["y"].Should().Be("yy"); + mappedModel.Description.ShouldBe("description"); + mappedModel.DisplayName.ShouldBe("displayname"); + mappedModel.Enabled.ShouldBeFalse(); + mappedModel.Name.ShouldBe("foo"); + mappedModel.UserClaims.Count.ShouldBe(2); + mappedModel.UserClaims.ShouldBeEquivalentTo(new[] { "c1", "c2" }); + mappedModel.Properties.Count.ShouldBe(2); + mappedModel.Properties["x"].ShouldBe("xx"); + mappedModel.Properties["y"].ShouldBe("yy"); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/ClientAssertionClient.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/ClientAssertionClient.cs index 8050e5450..262aa490c 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/ClientAssertionClient.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/ClientAssertionClient.cs @@ -11,7 +11,7 @@ using System.Text; using System.Text.Json; using System.Threading.Tasks; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using Duende.IdentityModel.Client; using IntegrationTests.Common; @@ -141,8 +141,8 @@ public async Task Valid_client_with_token_replay_should_fail() Scope = "api1" }); - response.IsError.Should().BeTrue(); - response.Error.Should().Be("invalid_client"); + response.IsError.ShouldBeTrue(); + response.Error.ShouldBe("invalid_client"); } [Fact] @@ -163,9 +163,9 @@ public async Task Client_with_invalid_secret_should_fail() Scope = "api1" }); - response.IsError.Should().Be(true); - response.Error.Should().Be(OidcConstants.TokenErrors.InvalidClient); - response.ErrorType.Should().Be(ResponseErrorType.Protocol); + response.IsError.ShouldBe(true); + response.Error.ShouldBe(OidcConstants.TokenErrors.InvalidClient); + response.ErrorType.ShouldBe(ResponseErrorType.Protocol); } [Fact] @@ -189,9 +189,9 @@ public async Task Invalid_client_should_fail() Scope = "api1" }); - response.IsError.Should().Be(true); - response.Error.Should().Be(OidcConstants.TokenErrors.InvalidClient); - response.ErrorType.Should().Be(ResponseErrorType.Protocol); + response.IsError.ShouldBe(true); + response.Error.ShouldBe(OidcConstants.TokenErrors.InvalidClient); + response.ErrorType.ShouldBe(ResponseErrorType.Protocol); } private async Task GetToken(FormUrlEncodedContent body) @@ -202,22 +202,22 @@ private async Task GetToken(FormUrlEncodedContent body) private void AssertValidToken(TokenResponse response) { - response.IsError.Should().Be(false); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBe(false); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); var payload = GetPayload(response); - payload.Count.Should().Be(8); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be(ClientId); - payload.Keys.Should().Contain("iat"); + payload.Count.ShouldBe(8); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe(ClientId); + payload.Keys.ShouldContain("iat"); var scopes = payload["scope"].EnumerateArray(); - scopes.First().ToString().Should().Be("api1"); + scopes.First().ToString().ShouldBe("api1"); } private Dictionary GetPayload(TokenResponse response) diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/ClientCredentialsAndResourceOwnerClient.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/ClientCredentialsAndResourceOwnerClient.cs index 99e9a2ff6..999e30939 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/ClientCredentialsAndResourceOwnerClient.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/ClientCredentialsAndResourceOwnerClient.cs @@ -4,7 +4,7 @@ using System.Net.Http; using System.Threading.Tasks; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel.Client; using IntegrationTests.Clients.Setup; using Microsoft.AspNetCore.Hosting; @@ -39,7 +39,7 @@ public async Task Resource_scope_should_be_requestable_via_client_credentials() Scope = "api1" }); - response.IsError.Should().Be(false); + response.IsError.ShouldBe(false); } [Fact] @@ -53,7 +53,7 @@ public async Task Openid_scope_should_not_be_requestable_via_client_credentials( Scope = "openid api1" }); - response.IsError.Should().Be(true); + response.IsError.ShouldBe(true); } [Fact] @@ -70,7 +70,7 @@ public async Task Openid_scope_should_be_requestable_via_password() Password = "bob" }); - response.IsError.Should().Be(false); + response.IsError.ShouldBe(false); } [Fact] @@ -87,6 +87,6 @@ public async Task Openid_and_resource_scope_should_be_requestable_via_password() Password = "bob" }); - response.IsError.Should().Be(false); + response.IsError.ShouldBe(false); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/ClientCredentialsClient.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/ClientCredentialsClient.cs index a8242b7ed..6ebfbe770 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/ClientCredentialsClient.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/ClientCredentialsClient.cs @@ -9,7 +9,7 @@ using System.Text; using System.Text.Json; using System.Threading.Tasks; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using Duende.IdentityModel.Client; using IntegrationTests.Clients.Setup; @@ -45,10 +45,10 @@ public async Task Invalid_endpoint_should_return_404() Scope = "api1" }); - response.IsError.Should().Be(true); - response.ErrorType.Should().Be(ResponseErrorType.Http); - response.Error.Should().Be("Not Found"); - response.HttpStatusCode.Should().Be(HttpStatusCode.NotFound); + response.IsError.ShouldBe(true); + response.ErrorType.ShouldBe(ResponseErrorType.Http); + response.Error.ShouldBe("Not Found"); + response.HttpStatusCode.ShouldBe(HttpStatusCode.NotFound); } [Fact] @@ -62,23 +62,23 @@ public async Task Valid_request_single_audience_should_return_expected_payload() Scope = "api1" }); - response.IsError.Should().Be(false); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBe(false); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); var payload = GetPayload(response); - payload.Count.Should().Be(8); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be("client"); - payload.Keys.Should().Contain("jti"); - payload.Keys.Should().Contain("iat"); + payload.Count.ShouldBe(8); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe("client"); + payload.Keys.ShouldContain("jti"); + payload.Keys.ShouldContain("iat"); var scopes = payload["scope"].EnumerateArray(); - scopes.First().ToString().Should().Be("api1"); + scopes.First().ToString().ShouldBe("api1"); } [Fact] @@ -92,27 +92,27 @@ public async Task Valid_request_multiple_audiences_should_return_expected_payloa Scope = "api1 other_api" }); - response.IsError.Should().Be(false); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBe(false); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); var payload = GetPayload(response); - payload.Count.Should().Be(8); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["client_id"].GetString().Should().Be("client"); - payload.Keys.Should().Contain("jti"); - payload.Keys.Should().Contain("iat"); + payload.Count.ShouldBe(8); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["client_id"].GetString().ShouldBe("client"); + payload.Keys.ShouldContain("jti"); + payload.Keys.ShouldContain("iat"); var audiences = payload["aud"].EnumerateArray().Select(x => x.ToString()).ToList(); - audiences.Count.Should().Be(2); - audiences.Should().Contain("api"); - audiences.Should().Contain("other_api"); + audiences.Count.ShouldBe(2); + audiences.ShouldContain("api"); + audiences.ShouldContain("other_api"); var scopes = payload["scope"].EnumerateArray(); - scopes.First().ToString().Should().Be("api1"); + scopes.First().ToString().ShouldBe("api1"); } [Fact] @@ -126,26 +126,26 @@ public async Task Valid_request_with_confirmation_should_return_expected_payload Scope = "api1" }); - response.IsError.Should().Be(false); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBe(false); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); var payload = GetPayload(response); - payload.Count.Should().Be(9); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be("client.cnf"); - payload.Keys.Should().Contain("jti"); - payload.Keys.Should().Contain("iat"); + payload.Count.ShouldBe(9); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe("client.cnf"); + payload.Keys.ShouldContain("jti"); + payload.Keys.ShouldContain("iat"); var scopes = payload["scope"].EnumerateArray(); - scopes.First().ToString().Should().Be("api1"); + scopes.First().ToString().ShouldBe("api1"); var cnf = payload["cnf"]; - cnf.TryGetString("x5t#S256").Should().Be("foo"); + cnf.TryGetString("x5t#S256").ShouldBe("foo"); } [Fact] @@ -159,25 +159,25 @@ public async Task Requesting_multiple_scopes_should_return_expected_payload() Scope = "api1 api2" }); - response.IsError.Should().Be(false); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBe(false); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); var payload = GetPayload(response); - payload.Count.Should().Be(8); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be("client"); - payload.Keys.Should().Contain("jti"); - payload.Keys.Should().Contain("iat"); + payload.Count.ShouldBe(8); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe("client"); + payload.Keys.ShouldContain("jti"); + payload.Keys.ShouldContain("iat"); var scopes = payload["scope"].EnumerateArray().ToList(); - scopes.Count.Should().Be(2); - scopes.First().ToString().Should().Be("api1"); - scopes.Skip(1).First().ToString().Should().Be("api2"); + scopes.Count.ShouldBe(2); + scopes.First().ToString().ShouldBe("api1"); + scopes.Skip(1).First().ToString().ShouldBe("api2"); } [Fact] @@ -190,30 +190,30 @@ public async Task Request_with_no_explicit_scopes_should_return_expected_payload ClientSecret = "secret" }); - response.IsError.Should().Be(false); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBe(false); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); var payload = GetPayload(response); - payload.Count.Should().Be(8); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["client_id"].GetString().Should().Be("client"); - payload.Keys.Should().Contain("jti"); - payload.Keys.Should().Contain("iat"); + payload.Count.ShouldBe(8); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["client_id"].GetString().ShouldBe("client"); + payload.Keys.ShouldContain("jti"); + payload.Keys.ShouldContain("iat"); var audiences = payload["aud"].EnumerateArray().Select(x => x.GetString()).ToList(); - audiences.Count.Should().Be(2); - audiences.Should().Contain("api"); - audiences.Should().Contain("other_api"); + audiences.Count.ShouldBe(2); + audiences.ShouldContain("api"); + audiences.ShouldContain("other_api"); var scopes = payload["scope"].EnumerateArray().Select(x => x.GetString()).ToList(); - scopes.Count.Should().Be(3); - scopes.Should().Contain("api1"); - scopes.Should().Contain("api2"); - scopes.Should().Contain("other_api"); + scopes.Count.ShouldBe(3); + scopes.ShouldContain("api1"); + scopes.ShouldContain("api2"); + scopes.ShouldContain("other_api"); } [Fact] @@ -226,12 +226,12 @@ public async Task Client_without_default_scopes_skipping_scope_parameter_should_ ClientSecret = "secret" }); - response.IsError.Should().Be(true); - response.ExpiresIn.Should().Be(0); - response.TokenType.Should().BeNull(); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); - response.Error.Should().Be(OidcConstants.TokenErrors.InvalidScope); + response.IsError.ShouldBe(true); + response.ExpiresIn.ShouldBe(0); + response.TokenType.ShouldBeNull(); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); + response.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); } [Fact] @@ -247,20 +247,20 @@ public async Task Request_posting_client_secret_in_body_should_succeed() ClientCredentialStyle = ClientCredentialStyle.PostBody }); - response.IsError.Should().Be(false); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBe(false); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); var payload = GetPayload(response); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be("client"); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe("client"); var scopes = payload["scope"].EnumerateArray(); - scopes.First().ToString().Should().Be("api1"); + scopes.First().ToString().ShouldBe("api1"); } @@ -274,20 +274,20 @@ public async Task Request_For_client_with_no_secret_and_basic_authentication_sho Scope = "api1" }); - response.IsError.Should().Be(false); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBe(false); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); var payload = GetPayload(response); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be("client.no_secret"); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe("client.no_secret"); var scopes = payload["scope"].EnumerateArray(); - scopes.First().ToString().Should().Be("api1"); + scopes.First().ToString().ShouldBe("api1"); } [Fact] @@ -301,8 +301,8 @@ public async Task Request_with_invalid_client_secret_should_fail() Scope = "api1" }); - response.IsError.Should().Be(true); - response.Error.Should().Be("invalid_client"); + response.IsError.ShouldBe(true); + response.Error.ShouldBe("invalid_client"); } [Fact] @@ -316,10 +316,10 @@ public async Task Unknown_client_should_fail() Scope = "api1" }); - response.IsError.Should().Be(true); - response.ErrorType.Should().Be(ResponseErrorType.Protocol); - response.HttpStatusCode.Should().Be(HttpStatusCode.BadRequest); - response.Error.Should().Be("invalid_client"); + response.IsError.ShouldBe(true); + response.ErrorType.ShouldBe(ResponseErrorType.Protocol); + response.HttpStatusCode.ShouldBe(HttpStatusCode.BadRequest); + response.Error.ShouldBe("invalid_client"); } [Fact] @@ -332,10 +332,10 @@ public async Task Implicit_client_should_not_use_client_credential_grant() Scope = "api1" }); - response.IsError.Should().Be(true); - response.ErrorType.Should().Be(ResponseErrorType.Protocol); - response.HttpStatusCode.Should().Be(HttpStatusCode.BadRequest); - response.Error.Should().Be("unauthorized_client"); + response.IsError.ShouldBe(true); + response.ErrorType.ShouldBe(ResponseErrorType.Protocol); + response.HttpStatusCode.ShouldBe(HttpStatusCode.BadRequest); + response.Error.ShouldBe("unauthorized_client"); } [Fact] @@ -349,10 +349,10 @@ public async Task Implicit_and_client_creds_client_should_not_use_client_credent Scope = "api1" }); - response.IsError.Should().Be(true); - response.ErrorType.Should().Be(ResponseErrorType.Protocol); - response.HttpStatusCode.Should().Be(HttpStatusCode.BadRequest); - response.Error.Should().Be("invalid_client"); + response.IsError.ShouldBe(true); + response.ErrorType.ShouldBe(ResponseErrorType.Protocol); + response.HttpStatusCode.ShouldBe(HttpStatusCode.BadRequest); + response.Error.ShouldBe("invalid_client"); } @@ -367,10 +367,10 @@ public async Task Requesting_unknown_scope_should_fail() Scope = "unknown" }); - response.IsError.Should().Be(true); - response.ErrorType.Should().Be(ResponseErrorType.Protocol); - response.HttpStatusCode.Should().Be(HttpStatusCode.BadRequest); - response.Error.Should().Be("invalid_scope"); + response.IsError.ShouldBe(true); + response.ErrorType.ShouldBe(ResponseErrorType.Protocol); + response.HttpStatusCode.ShouldBe(HttpStatusCode.BadRequest); + response.Error.ShouldBe("invalid_scope"); } [Fact] @@ -384,10 +384,10 @@ public async Task Client_explicitly_requesting_identity_scope_should_fail() Scope = "openid api1" }); - response.IsError.Should().Be(true); - response.ErrorType.Should().Be(ResponseErrorType.Protocol); - response.HttpStatusCode.Should().Be(HttpStatusCode.BadRequest); - response.Error.Should().Be("invalid_scope"); + response.IsError.ShouldBe(true); + response.ErrorType.ShouldBe(ResponseErrorType.Protocol); + response.HttpStatusCode.ShouldBe(HttpStatusCode.BadRequest); + response.Error.ShouldBe("invalid_scope"); } [Fact] @@ -401,10 +401,10 @@ public async Task Client_explicitly_requesting_offline_access_should_fail() Scope = "api1 offline_access" }); - response.IsError.Should().Be(true); - response.ErrorType.Should().Be(ResponseErrorType.Protocol); - response.HttpStatusCode.Should().Be(HttpStatusCode.BadRequest); - response.Error.Should().Be("invalid_scope"); + response.IsError.ShouldBe(true); + response.ErrorType.ShouldBe(ResponseErrorType.Protocol); + response.HttpStatusCode.ShouldBe(HttpStatusCode.BadRequest); + response.Error.ShouldBe("invalid_scope"); } [Fact] @@ -418,10 +418,10 @@ public async Task Requesting_unauthorized_scope_should_fail() Scope = "api3" }); - response.IsError.Should().Be(true); - response.ErrorType.Should().Be(ResponseErrorType.Protocol); - response.HttpStatusCode.Should().Be(HttpStatusCode.BadRequest); - response.Error.Should().Be("invalid_scope"); + response.IsError.ShouldBe(true); + response.ErrorType.ShouldBe(ResponseErrorType.Protocol); + response.HttpStatusCode.ShouldBe(HttpStatusCode.BadRequest); + response.Error.ShouldBe("invalid_scope"); } [Fact] @@ -435,10 +435,10 @@ public async Task Requesting_authorized_and_unauthorized_scopes_should_fail() Scope = "api1 api3" }); - response.IsError.Should().Be(true); - response.ErrorType.Should().Be(ResponseErrorType.Protocol); - response.HttpStatusCode.Should().Be(HttpStatusCode.BadRequest); - response.Error.Should().Be("invalid_scope"); + response.IsError.ShouldBe(true); + response.ErrorType.ShouldBe(ResponseErrorType.Protocol); + response.HttpStatusCode.ShouldBe(HttpStatusCode.BadRequest); + response.Error.ShouldBe("invalid_scope"); } private Dictionary GetPayload(TokenResponse response) diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/CustomTokenRequestValidatorClient.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/CustomTokenRequestValidatorClient.cs index 89b761040..43450d64b 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/CustomTokenRequestValidatorClient.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/CustomTokenRequestValidatorClient.cs @@ -6,7 +6,7 @@ using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel.Client; using IntegrationTests.Clients.Setup; using Microsoft.AspNetCore.Hosting; @@ -46,7 +46,7 @@ public async Task Client_credentials_request_should_contain_custom_response() }); var fields = GetFields(response); - fields["custom"].GetString().Should().Be("custom"); + fields["custom"].GetString().ShouldBe("custom"); } [Fact] @@ -65,7 +65,7 @@ public async Task Resource_owner_credentials_request_should_contain_custom_respo }); var fields = GetFields(response); - fields["custom"].GetString().Should().Be("custom"); + fields["custom"].GetString().ShouldBe("custom"); } [Fact] @@ -93,7 +93,7 @@ public async Task Refreshing_a_token_should_contain_custom_response() }); var fields = GetFields(response); - fields["custom"].GetString().Should().Be("custom"); + fields["custom"].GetString().ShouldBe("custom"); } [Fact] @@ -115,7 +115,7 @@ public async Task Extension_grant_request_should_contain_custom_response() }); var fields = GetFields(response); - fields["custom"].GetString().Should().Be("custom"); + fields["custom"].GetString().ShouldBe("custom"); } private Dictionary GetFields(TokenResponse response) => response.Raw.GetFields(); diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/CustomTokenResponseClients.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/CustomTokenResponseClients.cs index c124085e9..5a4d2e577 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/CustomTokenResponseClients.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/CustomTokenResponseClients.cs @@ -8,7 +8,7 @@ using System.Text; using System.Text.Json; using System.Threading.Tasks; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using Duende.IdentityModel.Client; using IntegrationTests.Clients.Setup; @@ -49,52 +49,51 @@ public async Task Resource_owner_success_should_return_custom_response() // raw fields var fields = GetFields(response); - fields["string_value"].GetString().Should().Be("some_string"); - fields["int_value"].GetInt32().Should().Be(42); + fields["string_value"].GetString().ShouldBe("some_string"); + fields["int_value"].GetInt32().ShouldBe(42); JsonElement temp; - fields.TryGetValue("identity_token", out temp).Should().BeFalse(); - fields.TryGetValue("refresh_token", out temp).Should().BeFalse(); - fields.TryGetValue("error", out temp).Should().BeFalse(); - fields.TryGetValue("error_description", out temp).Should().BeFalse(); - fields.TryGetValue("token_type", out temp).Should().BeTrue(); - fields.TryGetValue("expires_in", out temp).Should().BeTrue(); + fields.TryGetValue("identity_token", out temp).ShouldBeFalse(); + fields.TryGetValue("refresh_token", out temp).ShouldBeFalse(); + fields.TryGetValue("error", out temp).ShouldBeFalse(); + fields.TryGetValue("error_description", out temp).ShouldBeFalse(); + fields.TryGetValue("token_type", out temp).ShouldBeTrue(); + fields.TryGetValue("expires_in", out temp).ShouldBeTrue(); var responseObject = fields["dto"]; - responseObject.Should().NotBeNull(); var responseDto = GetDto(responseObject); var dto = CustomResponseDto.Create; - responseDto.string_value.Should().Be(dto.string_value); - responseDto.int_value.Should().Be(dto.int_value); - responseDto.nested.string_value.Should().Be(dto.nested.string_value); - responseDto.nested.int_value.Should().Be(dto.nested.int_value); + responseDto.string_value.ShouldBe(dto.string_value); + responseDto.int_value.ShouldBe(dto.int_value); + responseDto.nested.string_value.ShouldBe(dto.nested.string_value); + responseDto.nested.int_value.ShouldBe(dto.nested.int_value); // token client response - response.IsError.Should().Be(false); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBe(false); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); // token content var payload = GetPayload(response); - payload.Count.Should().Be(12); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["client_id"].GetString().Should().Be("roclient"); - payload["sub"].GetString().Should().Be("bob"); - payload["idp"].GetString().Should().Be("local"); - payload["aud"].GetString().Should().Be("api"); + payload.Count.ShouldBe(12); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["client_id"].GetString().ShouldBe("roclient"); + payload["sub"].GetString().ShouldBe("bob"); + payload["idp"].GetString().ShouldBe("local"); + payload["aud"].GetString().ShouldBe("api"); var scopes = payload["scope"].EnumerateArray(); - scopes.First().ToString().Should().Be("api1"); + scopes.First().ToString().ShouldBe("api1"); var amr = payload["amr"].EnumerateArray(); - amr.Count().Should().Be(1); - amr.First().ToString().Should().Be("password"); + amr.Count().ShouldBe(1); + amr.First().ToString().ShouldBe("password"); } [Fact] @@ -113,37 +112,36 @@ public async Task Resource_owner_failure_should_return_custom_error_response() // raw fields var fields = GetFields(response); - fields["string_value"].GetString().Should().Be("some_string"); - fields["int_value"].GetInt32().Should().Be(42); + fields["string_value"].GetString().ShouldBe("some_string"); + fields["int_value"].GetInt32().ShouldBe(42); JsonElement temp; - fields.TryGetValue("identity_token", out temp).Should().BeFalse(); - fields.TryGetValue("refresh_token", out temp).Should().BeFalse(); - fields.TryGetValue("error", out temp).Should().BeTrue(); - fields.TryGetValue("error_description", out temp).Should().BeTrue(); - fields.TryGetValue("token_type", out temp).Should().BeFalse(); - fields.TryGetValue("expires_in", out temp).Should().BeFalse(); + fields.TryGetValue("identity_token", out temp).ShouldBeFalse(); + fields.TryGetValue("refresh_token", out temp).ShouldBeFalse(); + fields.TryGetValue("error", out temp).ShouldBeTrue(); + fields.TryGetValue("error_description", out temp).ShouldBeTrue(); + fields.TryGetValue("token_type", out temp).ShouldBeFalse(); + fields.TryGetValue("expires_in", out temp).ShouldBeFalse(); var responseObject = fields["dto"]; - responseObject.Should().NotBeNull(); var responseDto = GetDto(responseObject); var dto = CustomResponseDto.Create; - responseDto.string_value.Should().Be(dto.string_value); - responseDto.int_value.Should().Be(dto.int_value); - responseDto.nested.string_value.Should().Be(dto.nested.string_value); - responseDto.nested.int_value.Should().Be(dto.nested.int_value); + responseDto.string_value.ShouldBe(dto.string_value); + responseDto.int_value.ShouldBe(dto.int_value); + responseDto.nested.string_value.ShouldBe(dto.nested.string_value); + responseDto.nested.int_value.ShouldBe(dto.nested.int_value); // token client response - response.IsError.Should().Be(true); - response.Error.Should().Be("invalid_grant"); - response.ErrorDescription.Should().Be("invalid_credential"); - response.ExpiresIn.Should().Be(0); - response.TokenType.Should().BeNull(); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBe(true); + response.Error.ShouldBe("invalid_grant"); + response.ErrorDescription.ShouldBe("invalid_credential"); + response.ExpiresIn.ShouldBe(0); + response.TokenType.ShouldBeNull(); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); } [Fact] @@ -167,52 +165,51 @@ public async Task Extension_grant_success_should_return_custom_response() // raw fields var fields = GetFields(response); - fields["string_value"].GetString().Should().Be("some_string"); - fields["int_value"].GetInt32().Should().Be(42); + fields["string_value"].GetString().ShouldBe("some_string"); + fields["int_value"].GetInt32().ShouldBe(42); JsonElement temp; - fields.TryGetValue("identity_token", out temp).Should().BeFalse(); - fields.TryGetValue("refresh_token", out temp).Should().BeFalse(); - fields.TryGetValue("error", out temp).Should().BeFalse(); - fields.TryGetValue("error_description", out temp).Should().BeFalse(); - fields.TryGetValue("token_type", out temp).Should().BeTrue(); - fields.TryGetValue("expires_in", out temp).Should().BeTrue(); + fields.TryGetValue("identity_token", out temp).ShouldBeFalse(); + fields.TryGetValue("refresh_token", out temp).ShouldBeFalse(); + fields.TryGetValue("error", out temp).ShouldBeFalse(); + fields.TryGetValue("error_description", out temp).ShouldBeFalse(); + fields.TryGetValue("token_type", out temp).ShouldBeTrue(); + fields.TryGetValue("expires_in", out temp).ShouldBeTrue(); var responseObject = fields["dto"]; - responseObject.Should().NotBeNull(); var responseDto = GetDto(responseObject); var dto = CustomResponseDto.Create; - responseDto.string_value.Should().Be(dto.string_value); - responseDto.int_value.Should().Be(dto.int_value); - responseDto.nested.string_value.Should().Be(dto.nested.string_value); - responseDto.nested.int_value.Should().Be(dto.nested.int_value); + responseDto.string_value.ShouldBe(dto.string_value); + responseDto.int_value.ShouldBe(dto.int_value); + responseDto.nested.string_value.ShouldBe(dto.nested.string_value); + responseDto.nested.int_value.ShouldBe(dto.nested.int_value); // token client response - response.IsError.Should().Be(false); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBe(false); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); // token content var payload = GetPayload(response); - payload.Count.Should().Be(12); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["client_id"].GetString().Should().Be("client.custom"); - payload["sub"].GetString().Should().Be("bob"); - payload["idp"].GetString().Should().Be("local"); - payload["aud"].GetString().Should().Be("api"); + payload.Count.ShouldBe(12); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["client_id"].GetString().ShouldBe("client.custom"); + payload["sub"].GetString().ShouldBe("bob"); + payload["idp"].GetString().ShouldBe("local"); + payload["aud"].GetString().ShouldBe("api"); var scopes = payload["scope"].EnumerateArray(); - scopes.First().ToString().Should().Be("api1"); + scopes.First().ToString().ShouldBe("api1"); var amr = payload["amr"].EnumerateArray(); - amr.Count().Should().Be(1); - amr.First().ToString().Should().Be("custom"); + amr.Count().ShouldBe(1); + amr.First().ToString().ShouldBe("custom"); } [Fact] @@ -236,37 +233,36 @@ public async Task Extension_grant_failure_should_return_custom_error_response() // raw fields var fields = GetFields(response); - fields["string_value"].GetString().Should().Be("some_string"); - fields["int_value"].GetInt32().Should().Be(42); + fields["string_value"].GetString().ShouldBe("some_string"); + fields["int_value"].GetInt32().ShouldBe(42); JsonElement temp; - fields.TryGetValue("identity_token", out temp).Should().BeFalse(); - fields.TryGetValue("refresh_token", out temp).Should().BeFalse(); - fields.TryGetValue("error", out temp).Should().BeTrue(); - fields.TryGetValue("error_description", out temp).Should().BeTrue(); - fields.TryGetValue("token_type", out temp).Should().BeFalse(); - fields.TryGetValue("expires_in", out temp).Should().BeFalse(); + fields.TryGetValue("identity_token", out temp).ShouldBeFalse(); + fields.TryGetValue("refresh_token", out temp).ShouldBeFalse(); + fields.TryGetValue("error", out temp).ShouldBeTrue(); + fields.TryGetValue("error_description", out temp).ShouldBeTrue(); + fields.TryGetValue("token_type", out temp).ShouldBeFalse(); + fields.TryGetValue("expires_in", out temp).ShouldBeFalse(); var responseObject = fields["dto"]; - responseObject.Should().NotBeNull(); var responseDto = GetDto(responseObject); var dto = CustomResponseDto.Create; - responseDto.string_value.Should().Be(dto.string_value); - responseDto.int_value.Should().Be(dto.int_value); - responseDto.nested.string_value.Should().Be(dto.nested.string_value); - responseDto.nested.int_value.Should().Be(dto.nested.int_value); + responseDto.string_value.ShouldBe(dto.string_value); + responseDto.int_value.ShouldBe(dto.int_value); + responseDto.nested.string_value.ShouldBe(dto.nested.string_value); + responseDto.nested.int_value.ShouldBe(dto.nested.int_value); // token client response - response.IsError.Should().Be(true); - response.Error.Should().Be("invalid_grant"); - response.ErrorDescription.Should().Be("invalid_credential"); - response.ExpiresIn.Should().Be(0); - response.TokenType.Should().BeNull(); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBe(true); + response.Error.ShouldBe("invalid_grant"); + response.ErrorDescription.ShouldBe("invalid_credential"); + response.ExpiresIn.ShouldBe(0); + response.TokenType.ShouldBeNull(); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); } private CustomResponseDto GetDto(JsonElement responseObject) diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/DiscoveryClient.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/DiscoveryClient.cs index 488c9d48b..7465e1f25 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/DiscoveryClient.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/DiscoveryClient.cs @@ -2,7 +2,7 @@ // See LICENSE in the project root for license information. -using FluentAssertions; +using Shouldly; using Duende.IdentityModel.Client; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; @@ -42,14 +42,14 @@ public async Task Discovery_document_should_have_expected_values() }); // endpoints - doc.TokenEndpoint.Should().Be("https://server/connect/token"); - doc.AuthorizeEndpoint.Should().Be("https://server/connect/authorize"); - doc.IntrospectionEndpoint.Should().Be("https://server/connect/introspect"); - doc.EndSessionEndpoint.Should().Be("https://server/connect/endsession"); + doc.TokenEndpoint.ShouldBe("https://server/connect/token"); + doc.AuthorizeEndpoint.ShouldBe("https://server/connect/authorize"); + doc.IntrospectionEndpoint.ShouldBe("https://server/connect/introspect"); + doc.EndSessionEndpoint.ShouldBe("https://server/connect/endsession"); // jwk - doc.KeySet.Keys.Count.Should().Be(1); - doc.KeySet.Keys.First().E.Should().NotBeNull(); - doc.KeySet.Keys.First().N.Should().NotBeNull(); + doc.KeySet.Keys.Count.ShouldBe(1); + doc.KeySet.Keys.First().E.ShouldNotBeNull(); + doc.KeySet.Keys.First().N.ShouldNotBeNull(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/ExtensionGrantClient.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/ExtensionGrantClient.cs index 8054c7743..f5144b041 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/ExtensionGrantClient.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/ExtensionGrantClient.cs @@ -11,7 +11,7 @@ using System.Text; using System.Text.Json; using System.Threading.Tasks; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using Duende.IdentityModel.Client; using IntegrationTests.Clients.Setup; @@ -54,30 +54,30 @@ public async Task Valid_client_should_succeed() } }); - response.IsError.Should().BeFalse(); - response.HttpStatusCode.Should().Be(HttpStatusCode.OK); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBeFalse(); + response.HttpStatusCode.ShouldBe(HttpStatusCode.OK); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); var payload = GetPayload(response); - payload.Count.Should().Be(12); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be("client.custom"); - payload["sub"].GetString().Should().Be("818727"); - payload["idp"].GetString().Should().Be("local"); - payload.Keys.Should().Contain("jti"); - payload.Keys.Should().Contain("iat"); + payload.Count.ShouldBe(12); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe("client.custom"); + payload["sub"].GetString().ShouldBe("818727"); + payload["idp"].GetString().ShouldBe("local"); + payload.Keys.ShouldContain("jti"); + payload.Keys.ShouldContain("iat"); var scopes = payload["scope"].EnumerateArray(); - scopes.First().ToString().Should().Be("api1"); + scopes.First().ToString().ShouldBe("api1"); var amr = payload["amr"].EnumerateArray(); - amr.Count().Should().Be(1); - amr.First().ToString().Should().Be("custom"); + amr.Count().ShouldBe(1); + amr.First().ToString().ShouldBe("custom"); } [Fact] @@ -99,36 +99,36 @@ public async Task Valid_client_with_extra_claim_should_succeed() } }); - response.IsError.Should().BeFalse(); - response.HttpStatusCode.Should().Be(HttpStatusCode.OK); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBeFalse(); + response.HttpStatusCode.ShouldBe(HttpStatusCode.OK); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); var payload = GetPayload(response); var unixNow = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var exp = payload["exp"].GetInt64(); - exp.Should().BeLessThan(unixNow + 3620); - exp.Should().BeGreaterThan(unixNow + 3580); - - payload.Count.Should().Be(13); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be("client.custom"); - payload["sub"].GetString().Should().Be("818727"); - payload["idp"].GetString().Should().Be("local"); - payload["extra_claim"].GetString().Should().Be("extra_value"); - payload.Keys.Should().Contain("jti"); - payload.Keys.Should().Contain("iat"); + exp.ShouldBeLessThan(unixNow + 3620); + exp.ShouldBeGreaterThan(unixNow + 3580); + + payload.Count.ShouldBe(13); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe("client.custom"); + payload["sub"].GetString().ShouldBe("818727"); + payload["idp"].GetString().ShouldBe("local"); + payload["extra_claim"].GetString().ShouldBe("extra_value"); + payload.Keys.ShouldContain("jti"); + payload.Keys.ShouldContain("iat"); var scopes = payload["scope"].EnumerateArray(); - scopes.First().ToString().Should().Be("api1"); + scopes.First().ToString().ShouldBe("api1"); var amr = payload["amr"].EnumerateArray(); - amr.Count().Should().Be(1); - amr.First().ToString().Should().Be("custom"); + amr.Count().ShouldBe(1); + amr.First().ToString().ShouldBe("custom"); } @@ -151,12 +151,12 @@ public async Task Valid_client_with_refreshed_extra_claim_should_succeed() } }); - response.IsError.Should().BeFalse(); - response.HttpStatusCode.Should().Be(HttpStatusCode.OK); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().NotBeNull(); + response.IsError.ShouldBeFalse(); + response.HttpStatusCode.ShouldBe(HttpStatusCode.OK); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldNotBeNull(); var refreshResponse = await _client.RequestRefreshTokenAsync(new RefreshTokenRequest { @@ -168,36 +168,36 @@ public async Task Valid_client_with_refreshed_extra_claim_should_succeed() RefreshToken = response.RefreshToken }); - refreshResponse.IsError.Should().BeFalse(); - refreshResponse.HttpStatusCode.Should().Be(HttpStatusCode.OK); - refreshResponse.ExpiresIn.Should().Be(3600); - refreshResponse.TokenType.Should().Be("Bearer"); - refreshResponse.IdentityToken.Should().BeNull(); - refreshResponse.RefreshToken.Should().NotBeNull(); + refreshResponse.IsError.ShouldBeFalse(); + refreshResponse.HttpStatusCode.ShouldBe(HttpStatusCode.OK); + refreshResponse.ExpiresIn.ShouldBe(3600); + refreshResponse.TokenType.ShouldBe("Bearer"); + refreshResponse.IdentityToken.ShouldBeNull(); + refreshResponse.RefreshToken.ShouldNotBeNull(); var payload = GetPayload(refreshResponse); var unixNow = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var exp = payload["exp"].GetInt64(); - exp.Should().BeLessThan(unixNow + 3620); - exp.Should().BeGreaterThan(unixNow + 3580); - - payload.Count.Should().Be(13); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be("client.custom"); - payload["sub"].GetString().Should().Be("818727"); - payload["idp"].GetString().Should().Be("local"); - payload["extra_claim"].GetString().Should().Be("extra_value"); - payload.Keys.Should().Contain("jti"); - payload.Keys.Should().Contain("iat"); + exp.ShouldBeLessThan(unixNow + 3620); + exp.ShouldBeGreaterThan(unixNow + 3580); + + payload.Count.ShouldBe(13); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe("client.custom"); + payload["sub"].GetString().ShouldBe("818727"); + payload["idp"].GetString().ShouldBe("local"); + payload["extra_claim"].GetString().ShouldBe("extra_value"); + payload.Keys.ShouldContain("jti"); + payload.Keys.ShouldContain("iat"); var scopes = payload["scope"].EnumerateArray(); - scopes.First().ToString().Should().Be("api1"); + scopes.First().ToString().ShouldBe("api1"); var amr = payload["amr"].EnumerateArray(); - amr.Count().Should().Be(1); - amr.First().ToString().Should().Be("custom"); + amr.Count().ShouldBe(1); + amr.First().ToString().ShouldBe("custom"); } [Fact] @@ -218,22 +218,22 @@ public async Task Valid_client_no_subject_should_succeed() } }); - response.IsError.Should().BeFalse(); - response.HttpStatusCode.Should().Be(HttpStatusCode.OK); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBeFalse(); + response.HttpStatusCode.ShouldBe(HttpStatusCode.OK); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); var payload = GetPayload(response); - payload.Count.Should().Be(8); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be("client.custom"); + payload.Count.ShouldBe(8); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe("client.custom"); var scopes = payload["scope"].EnumerateArray(); - scopes.First().ToString().Should().Be("api1"); + scopes.First().ToString().ShouldBe("api1"); } [Fact] @@ -253,33 +253,33 @@ public async Task Valid_client_with_default_scopes_should_succeed() } }); - response.IsError.Should().BeFalse(); - response.HttpStatusCode.Should().Be(HttpStatusCode.OK); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().NotBeNull(); + response.IsError.ShouldBeFalse(); + response.HttpStatusCode.ShouldBe(HttpStatusCode.OK); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldNotBeNull(); var payload = GetPayload(response); - payload.Count.Should().Be(12); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be("client.custom"); - payload["sub"].GetString().Should().Be("818727"); - payload["idp"].GetString().Should().Be("local"); - payload.Keys.Should().Contain("jti"); - payload.Keys.Should().Contain("iat"); + payload.Count.ShouldBe(12); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe("client.custom"); + payload["sub"].GetString().ShouldBe("818727"); + payload["idp"].GetString().ShouldBe("local"); + payload.Keys.ShouldContain("jti"); + payload.Keys.ShouldContain("iat"); var amr = payload["amr"].EnumerateArray(); - amr.Count().Should().Be(1); - amr.First().ToString().Should().Be("custom"); + amr.Count().ShouldBe(1); + amr.First().ToString().ShouldBe("custom"); var scopes = payload["scope"].EnumerateArray(); - scopes.Count().Should().Be(3); - scopes.First().ToString().Should().Be("api1"); - scopes.Skip(1).First().ToString().Should().Be("api2"); - scopes.Skip(2).First().ToString().Should().Be("offline_access"); + scopes.Count().ShouldBe(3); + scopes.First().ToString().ShouldBe("api1"); + scopes.Skip(1).First().ToString().ShouldBe("api2"); + scopes.Skip(2).First().ToString().ShouldBe("offline_access"); } [Fact] @@ -299,10 +299,10 @@ public async Task Valid_client_missing_grant_specific_data_should_fail() } }); - response.IsError.Should().Be(true); - response.ErrorType.Should().Be(ResponseErrorType.Protocol); - response.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); - response.ErrorDescription.Should().Be("invalid_custom_credential"); + response.IsError.ShouldBe(true); + response.ErrorType.ShouldBe(ResponseErrorType.Protocol); + response.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); + response.ErrorDescription.ShouldBe("invalid_custom_credential"); } [Fact] @@ -323,10 +323,10 @@ public async Task Valid_client_using_unsupported_grant_type_should_fail() } }); - response.IsError.Should().Be(true); - response.ErrorType.Should().Be(ResponseErrorType.Protocol); - response.HttpStatusCode.Should().Be(HttpStatusCode.BadRequest); - response.Error.Should().Be("unsupported_grant_type"); + response.IsError.ShouldBe(true); + response.ErrorType.ShouldBe(ResponseErrorType.Protocol); + response.HttpStatusCode.ShouldBe(HttpStatusCode.BadRequest); + response.Error.ShouldBe("unsupported_grant_type"); } [Fact] @@ -347,10 +347,10 @@ public async Task Valid_client_using_unauthorized_grant_type_should_fail() } }); - response.IsError.Should().Be(true); - response.ErrorType.Should().Be(ResponseErrorType.Protocol); - response.HttpStatusCode.Should().Be(HttpStatusCode.BadRequest); - response.Error.Should().Be("unsupported_grant_type"); + response.IsError.ShouldBe(true); + response.ErrorType.ShouldBe(ResponseErrorType.Protocol); + response.HttpStatusCode.ShouldBe(HttpStatusCode.BadRequest); + response.Error.ShouldBe("unsupported_grant_type"); } [Fact(Skip = "needs improvement")] @@ -373,35 +373,35 @@ public async Task Dynamic_lifetime_should_succeed() } }); - response.IsError.Should().BeFalse(); - response.HttpStatusCode.Should().Be(HttpStatusCode.OK); - response.ExpiresIn.Should().Be(5000); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBeFalse(); + response.HttpStatusCode.ShouldBe(HttpStatusCode.OK); + response.ExpiresIn.ShouldBe(5000); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); var payload = GetPayload(response); var unixNow = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var exp = payload["exp"].GetInt64(); - exp.Should().BeLessThan(unixNow + 5020); - exp.Should().BeGreaterThan(unixNow + 4980); - - payload.Count.Should().Be(10); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be("client.dynamic"); - payload["sub"].GetString().Should().Be("88421113"); - payload["idp"].GetString().Should().Be("local"); - payload.Keys.Should().Contain("jti"); - payload.Keys.Should().Contain("iat"); + exp.ShouldBeLessThan(unixNow + 5020); + exp.ShouldBeGreaterThan(unixNow + 4980); + + payload.Count.ShouldBe(10); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe("client.dynamic"); + payload["sub"].GetString().ShouldBe("88421113"); + payload["idp"].GetString().ShouldBe("local"); + payload.Keys.ShouldContain("jti"); + payload.Keys.ShouldContain("iat"); var scopes = payload["scope"].EnumerateArray(); - scopes.First().ToString().Should().Be("api1"); + scopes.First().ToString().ShouldBe("api1"); var amr = payload["amr"].EnumerateArray(); - amr.Count().Should().Be(1); - amr.First().ToString().Should().Be("delegation"); + amr.Count().ShouldBe(1); + amr.First().ToString().ShouldBe("delegation"); } [Fact] @@ -424,14 +424,14 @@ public async Task Dynamic_token_type_jwt_should_succeed() } }); - response.IsError.Should().BeFalse(); - response.HttpStatusCode.Should().Be(HttpStatusCode.OK); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBeFalse(); + response.HttpStatusCode.ShouldBe(HttpStatusCode.OK); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); - response.AccessToken.Should().Contain("."); + response.AccessToken.ShouldContain("."); } [Fact] @@ -455,17 +455,17 @@ public async Task Impersonate_client_should_succeed() } }); - response.IsError.Should().BeFalse(); - response.HttpStatusCode.Should().Be(HttpStatusCode.OK); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBeFalse(); + response.HttpStatusCode.ShouldBe(HttpStatusCode.OK); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); - response.AccessToken.Should().Contain("."); + response.AccessToken.ShouldContain("."); var jwt = new JwtSecurityToken(response.AccessToken); - jwt.Payload["client_id"].Should().Be("impersonated_client_id"); + jwt.Payload["client_id"].ShouldBe("impersonated_client_id"); } [Fact] @@ -488,14 +488,14 @@ public async Task Dynamic_token_type_reference_should_succeed() } }); - response.IsError.Should().BeFalse(); - response.HttpStatusCode.Should().Be(HttpStatusCode.OK); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBeFalse(); + response.HttpStatusCode.ShouldBe(HttpStatusCode.OK); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); - response.AccessToken.Should().NotContain("."); + response.AccessToken.ShouldNotContain("."); } [Fact] @@ -518,31 +518,31 @@ public async Task Dynamic_client_claims_should_succeed() } }); - response.IsError.Should().BeFalse(); - response.HttpStatusCode.Should().Be(HttpStatusCode.OK); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBeFalse(); + response.HttpStatusCode.ShouldBe(HttpStatusCode.OK); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); var payload = GetPayload(response); - payload.Count.Should().Be(13); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be("client.dynamic"); - payload["sub"].GetString().Should().Be("818727"); - payload["idp"].GetString().Should().Be("local"); - payload["client_extra"].GetString().Should().Be("extra_claim"); - payload.Keys.Should().Contain("jti"); - payload.Keys.Should().Contain("iat"); + payload.Count.ShouldBe(13); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe("client.dynamic"); + payload["sub"].GetString().ShouldBe("818727"); + payload["idp"].GetString().ShouldBe("local"); + payload["client_extra"].GetString().ShouldBe("extra_claim"); + payload.Keys.ShouldContain("jti"); + payload.Keys.ShouldContain("iat"); var scopes = payload["scope"].EnumerateArray(); - scopes.First().ToString().Should().Be("api1"); + scopes.First().ToString().ShouldBe("api1"); var amr = payload["amr"].EnumerateArray(); - amr.Count().Should().Be(1); - amr.First().ToString().Should().Be("delegation"); + amr.Count().ShouldBe(1); + amr.First().ToString().ShouldBe("delegation"); } [Fact] @@ -564,25 +564,25 @@ public async Task Dynamic_client_claims_no_sub_should_succeed() } }); - response.IsError.Should().BeFalse(); - response.HttpStatusCode.Should().Be(HttpStatusCode.OK); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBeFalse(); + response.HttpStatusCode.ShouldBe(HttpStatusCode.OK); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); var payload = GetPayload(response); - payload.Count.Should().Be(9); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be("client.dynamic"); - payload["client_extra"].GetString().Should().Be("extra_claim"); - payload.Keys.Should().Contain("jti"); - payload.Keys.Should().Contain("iat"); + payload.Count.ShouldBe(9); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe("client.dynamic"); + payload["client_extra"].GetString().ShouldBe("extra_claim"); + payload.Keys.ShouldContain("jti"); + payload.Keys.ShouldContain("iat"); var scopes = payload["scope"].EnumerateArray(); - scopes.First().ToString().Should().Be("api1"); + scopes.First().ToString().ShouldBe("api1"); } private Dictionary GetPayload(TokenResponse response) diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/RefreshTokenClient.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/RefreshTokenClient.cs index bf4c799bc..a358b63ee 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/RefreshTokenClient.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/RefreshTokenClient.cs @@ -4,7 +4,7 @@ using System.Net.Http; using System.Threading.Tasks; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel.Client; using IntegrationTests.Clients.Setup; using Microsoft.AspNetCore.Hosting; @@ -43,11 +43,11 @@ public async Task Requesting_a_refresh_token_without_identity_scopes_should_retu Password = "bob" }); - response.IsError.Should().BeFalse(); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().NotBeNull(); + response.IsError.ShouldBeFalse(); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldNotBeNull(); response = await _client.RequestRefreshTokenAsync(new RefreshTokenRequest { @@ -58,11 +58,11 @@ public async Task Requesting_a_refresh_token_without_identity_scopes_should_retu RefreshToken = response.RefreshToken }); - response.IsError.Should().BeFalse(); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().NotBeNull(); + response.IsError.ShouldBeFalse(); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldNotBeNull(); } [Fact] @@ -79,11 +79,11 @@ public async Task Requesting_a_refresh_token_with_identity_scopes_should_return_ Password = "bob" }); - response.IsError.Should().BeFalse(); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().NotBeNull(); + response.IsError.ShouldBeFalse(); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldNotBeNull(); response = await _client.RequestRefreshTokenAsync(new RefreshTokenRequest { @@ -94,11 +94,11 @@ public async Task Requesting_a_refresh_token_with_identity_scopes_should_return_ RefreshToken = response.RefreshToken }); - response.IsError.Should().BeFalse(); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().NotBeNull(); - response.RefreshToken.Should().NotBeNull(); + response.IsError.ShouldBeFalse(); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldNotBeNull(); + response.RefreshToken.ShouldNotBeNull(); } [Fact] @@ -115,11 +115,11 @@ public async Task Refreshing_a_refresh_token_with_reuse_should_return_same_refre Password = "bob" }); - response.IsError.Should().BeFalse(); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().NotBeNull(); + response.IsError.ShouldBeFalse(); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldNotBeNull(); var rt1 = response.RefreshToken; @@ -132,15 +132,15 @@ public async Task Refreshing_a_refresh_token_with_reuse_should_return_same_refre RefreshToken = response.RefreshToken }); - response.IsError.Should().BeFalse(); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().NotBeNull(); - response.RefreshToken.Should().NotBeNull(); + response.IsError.ShouldBeFalse(); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldNotBeNull(); + response.RefreshToken.ShouldNotBeNull(); var rt2 = response.RefreshToken; - rt1.Should().BeEquivalentTo(rt2); + rt1.ShouldBeEquivalentTo(rt2); } [Fact] @@ -157,11 +157,11 @@ public async Task Refreshing_a_refresh_token_with_one_time_only_should_return_di Password = "bob" }); - response.IsError.Should().BeFalse(); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().NotBeNull(); + response.IsError.ShouldBeFalse(); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldNotBeNull(); var rt1 = response.RefreshToken; @@ -174,15 +174,15 @@ public async Task Refreshing_a_refresh_token_with_one_time_only_should_return_di RefreshToken = response.RefreshToken }); - response.IsError.Should().BeFalse(); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().NotBeNull(); - response.RefreshToken.Should().NotBeNull(); + response.IsError.ShouldBeFalse(); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldNotBeNull(); + response.RefreshToken.ShouldNotBeNull(); var rt2 = response.RefreshToken; - rt1.Should().NotBeEquivalentTo(rt2); + rt1.ShouldBeEquivalentTo(rt2); } [Fact] @@ -200,11 +200,11 @@ public async Task Replaying_a_rotated_token_should_fail() Password = "bob" }); - response.IsError.Should().BeFalse(); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().NotBeNull(); + response.IsError.ShouldBeFalse(); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldNotBeNull(); var rt1 = response.RefreshToken; @@ -218,11 +218,11 @@ public async Task Replaying_a_rotated_token_should_fail() RefreshToken = response.RefreshToken }); - response.IsError.Should().BeFalse(); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().NotBeNull(); - response.RefreshToken.Should().NotBeNull(); + response.IsError.ShouldBeFalse(); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldNotBeNull(); + response.RefreshToken.ShouldNotBeNull(); // refresh token (again) response = await _client.RequestRefreshTokenAsync(new RefreshTokenRequest @@ -234,8 +234,8 @@ public async Task Replaying_a_rotated_token_should_fail() RefreshToken = rt1 }); - response.IsError.Should().BeTrue(); - response.Error.Should().Be("invalid_grant"); + response.IsError.ShouldBeTrue(); + response.Error.ShouldBe("invalid_grant"); } [Fact] @@ -253,11 +253,11 @@ public async Task Using_a_valid_refresh_token_should_succeed() Password = "bob" }); - response.IsError.Should().BeFalse(); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().NotBeNull(); + response.IsError.ShouldBeFalse(); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldNotBeNull(); var rt1 = response.RefreshToken; @@ -271,7 +271,7 @@ public async Task Using_a_valid_refresh_token_should_succeed() RefreshToken = rt1 }); - response.IsError.Should().BeFalse(); + response.IsError.ShouldBeFalse(); } [Fact] @@ -289,11 +289,11 @@ public async Task Using_a_revoked_refresh_token_should_fail() Password = "bob" }); - response.IsError.Should().BeFalse(); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().NotBeNull(); + response.IsError.ShouldBeFalse(); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldNotBeNull(); var rt1 = response.RefreshToken; @@ -309,7 +309,7 @@ public async Task Using_a_revoked_refresh_token_should_fail() TokenTypeHint = "refresh_token" }); - revocationResponse.IsError.Should().Be(false); + revocationResponse.IsError.ShouldBe(false); // refresh token response = await _client.RequestRefreshTokenAsync(new RefreshTokenRequest @@ -321,7 +321,7 @@ public async Task Using_a_revoked_refresh_token_should_fail() RefreshToken = rt1 }); - response.IsError.Should().BeTrue(); - response.Error.Should().Be("invalid_grant"); + response.IsError.ShouldBeTrue(); + response.Error.ShouldBe("invalid_grant"); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/ResourceOwnerClient.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/ResourceOwnerClient.cs index b304d2479..de8ee8fdc 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/ResourceOwnerClient.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/ResourceOwnerClient.cs @@ -9,7 +9,7 @@ using System.Text; using System.Text.Json; using System.Threading.Tasks; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using Duende.IdentityModel.Client; using IntegrationTests.Clients.Setup; @@ -48,30 +48,30 @@ public async Task Valid_user_should_succeed_with_expected_response_payload() Password = "bob" }); - response.IsError.Should().Be(false); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBe(false); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); var payload = GetPayload(response); - payload.Count.Should().Be(12); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be("roclient"); - payload["sub"].GetString().Should().Be("88421113"); - payload["idp"].GetString().Should().Be("local"); - payload.Keys.Should().Contain("jti"); - payload.Keys.Should().Contain("iat"); + payload.Count.ShouldBe(12); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe("roclient"); + payload["sub"].GetString().ShouldBe("88421113"); + payload["idp"].GetString().ShouldBe("local"); + payload.Keys.ShouldContain("jti"); + payload.Keys.ShouldContain("iat"); var scopes = payload["scope"].EnumerateArray().Select(x => x.ToString()).ToList(); - scopes.Count.Should().Be(1); - scopes.Should().Contain("api1"); + scopes.Count.ShouldBe(1); + scopes.ShouldContain("api1"); var amr = payload["amr"].EnumerateArray().ToList(); - amr.Count.Should().Be(1); - amr.First().GetString().Should().Be("pwd"); + amr.Count.ShouldBe(1); + amr.First().GetString().ShouldBe("pwd"); } [Fact] @@ -87,37 +87,37 @@ public async Task Request_with_no_explicit_scopes_should_return_allowed_scopes() Password = "bob" }); - response.IsError.Should().Be(false); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().NotBeNull(); + response.IsError.ShouldBe(false); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldNotBeNull(); var payload = GetPayload(response); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be("roclient"); - payload["sub"].GetString().Should().Be("88421113"); - payload["idp"].GetString().Should().Be("local"); - payload.Keys.Should().Contain("jti"); - payload.Keys.Should().Contain("iat"); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe("roclient"); + payload["sub"].GetString().ShouldBe("88421113"); + payload["idp"].GetString().ShouldBe("local"); + payload.Keys.ShouldContain("jti"); + payload.Keys.ShouldContain("iat"); var amr = payload["amr"].EnumerateArray().ToList(); - amr.Count.Should().Be(1); - amr.First().GetString().Should().Be("pwd"); + amr.Count.ShouldBe(1); + amr.First().GetString().ShouldBe("pwd"); var scopes = payload["scope"].EnumerateArray().Select(x => x.ToString()).ToList(); - scopes.Count.Should().Be(8); - - scopes.Should().Contain("address"); - scopes.Should().Contain("api1"); - scopes.Should().Contain("api2"); - scopes.Should().Contain("api4.with.roles"); - scopes.Should().Contain("email"); - scopes.Should().Contain("offline_access"); - scopes.Should().Contain("openid"); - scopes.Should().Contain("roles"); + scopes.Count.ShouldBe(8); + + scopes.ShouldContain("address"); + scopes.ShouldContain("api1"); + scopes.ShouldContain("api2"); + scopes.ShouldContain("api4.with.roles"); + scopes.ShouldContain("email"); + scopes.ShouldContain("offline_access"); + scopes.ShouldContain("openid"); + scopes.ShouldContain("roles"); } [Fact] @@ -134,32 +134,32 @@ public async Task Request_containing_identity_scopes_should_return_expected_payl Password = "bob" }); - response.IsError.Should().Be(false); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().BeNull(); + response.IsError.ShouldBe(false); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldBeNull(); var payload = GetPayload(response); - payload.Count.Should().Be(12); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be("roclient"); - payload["sub"].GetString().Should().Be("88421113"); - payload["idp"].GetString().Should().Be("local"); - payload.Keys.Should().Contain("jti"); - payload.Keys.Should().Contain("iat"); + payload.Count.ShouldBe(12); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe("roclient"); + payload["sub"].GetString().ShouldBe("88421113"); + payload["idp"].GetString().ShouldBe("local"); + payload.Keys.ShouldContain("jti"); + payload.Keys.ShouldContain("iat"); var amr = payload["amr"].EnumerateArray(); - amr.Count().Should().Be(1); - amr.First().ToString().Should().Be("pwd"); + amr.Count().ShouldBe(1); + amr.First().ToString().ShouldBe("pwd"); var scopes = payload["scope"].EnumerateArray().Select(x => x.ToString()).ToList(); - scopes.Count.Should().Be(3); - scopes.Should().Contain("api1"); - scopes.Should().Contain("email"); - scopes.Should().Contain("openid"); + scopes.Count.ShouldBe(3); + scopes.ShouldContain("api1"); + scopes.ShouldContain("email"); + scopes.ShouldContain("openid"); } [Fact] @@ -176,33 +176,33 @@ public async Task Request_for_refresh_token_should_return_expected_payload() Password = "bob" }); - response.IsError.Should().Be(false); - response.ExpiresIn.Should().Be(3600); - response.TokenType.Should().Be("Bearer"); - response.IdentityToken.Should().BeNull(); - response.RefreshToken.Should().NotBeNullOrWhiteSpace(); + response.IsError.ShouldBe(false); + response.ExpiresIn.ShouldBe(3600); + response.TokenType.ShouldBe("Bearer"); + response.IdentityToken.ShouldBeNull(); + response.RefreshToken.ShouldNotBeNullOrWhiteSpace(); var payload = GetPayload(response); - payload.Count.Should().Be(12); - payload["iss"].GetString().Should().Be("https://idsvr4"); - payload["aud"].GetString().Should().Be("api"); - payload["client_id"].GetString().Should().Be("roclient"); - payload["sub"].GetString().Should().Be("88421113"); - payload["idp"].GetString().Should().Be("local"); - payload.Keys.Should().Contain("jti"); - payload.Keys.Should().Contain("iat"); + payload.Count.ShouldBe(12); + payload["iss"].GetString().ShouldBe("https://idsvr4"); + payload["aud"].GetString().ShouldBe("api"); + payload["client_id"].GetString().ShouldBe("roclient"); + payload["sub"].GetString().ShouldBe("88421113"); + payload["idp"].GetString().ShouldBe("local"); + payload.Keys.ShouldContain("jti"); + payload.Keys.ShouldContain("iat"); var amr = payload["amr"].EnumerateArray().ToList(); - amr.Count.Should().Be(1); - amr.First().ToString().Should().Be("pwd"); + amr.Count.ShouldBe(1); + amr.First().ToString().ShouldBe("pwd"); var scopes = payload["scope"].EnumerateArray().Select(x => x.ToString()).ToList(); - scopes.Count.Should().Be(4); - scopes.Should().Contain("api1"); - scopes.Should().Contain("email"); - scopes.Should().Contain("offline_access"); - scopes.Should().Contain("openid"); + scopes.Count.ShouldBe(4); + scopes.ShouldContain("api1"); + scopes.ShouldContain("email"); + scopes.ShouldContain("offline_access"); + scopes.ShouldContain("openid"); } [Fact] @@ -219,10 +219,10 @@ public async Task Unknown_user_should_fail() Password = "bob" }); - response.IsError.Should().Be(true); - response.ErrorType.Should().Be(ResponseErrorType.Protocol); - response.HttpStatusCode.Should().Be(HttpStatusCode.BadRequest); - response.Error.Should().Be("invalid_grant"); + response.IsError.ShouldBe(true); + response.ErrorType.ShouldBe(ResponseErrorType.Protocol); + response.HttpStatusCode.ShouldBe(HttpStatusCode.BadRequest); + response.Error.ShouldBe("invalid_grant"); } [Fact] @@ -238,7 +238,7 @@ public async Task User_with_empty_password_should_succeed() UserName = "bob_no_password" }); - response.IsError.Should().Be(false); + response.IsError.ShouldBe(false); } [Theory] @@ -257,10 +257,10 @@ public async Task User_with_invalid_password_should_fail(string password) Password = password }); - response.IsError.Should().Be(true); - response.ErrorType.Should().Be(ResponseErrorType.Protocol); - response.HttpStatusCode.Should().Be(HttpStatusCode.BadRequest); - response.Error.Should().Be("invalid_grant"); + response.IsError.ShouldBe(true); + response.ErrorType.ShouldBe(ResponseErrorType.Protocol); + response.HttpStatusCode.ShouldBe(HttpStatusCode.BadRequest); + response.Error.ShouldBe("invalid_grant"); } diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/RevocationClient.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/RevocationClient.cs index 4905993ce..cd9cfb7bc 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/RevocationClient.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/RevocationClient.cs @@ -4,7 +4,7 @@ using System.Net.Http; using System.Threading.Tasks; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel.Client; using IntegrationTests.Clients.Setup; using Microsoft.AspNetCore.Hosting; @@ -45,7 +45,7 @@ public async Task Revoking_reference_token_should_invalidate_token() Password = "bob" }); - response.IsError.Should().BeFalse(); + response.IsError.ShouldBeFalse(); // introspect - should be active var introspectionResponse = await _client.IntrospectTokenAsync(new TokenIntrospectionRequest @@ -57,7 +57,7 @@ public async Task Revoking_reference_token_should_invalidate_token() Token = response.AccessToken }); - introspectionResponse.IsActive.Should().Be(true); + introspectionResponse.IsActive.ShouldBe(true); // revoke access token var revocationResponse = await _client.RevokeTokenAsync(new TokenRevocationRequest @@ -79,6 +79,6 @@ public async Task Revoking_reference_token_should_invalidate_token() Token = response.AccessToken }); - introspectionResponse.IsActive.Should().Be(false); + introspectionResponse.IsActive.ShouldBe(false); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Clients/UserInfoClient.cs b/identity-server/test/IdentityServer.IntegrationTests/Clients/UserInfoClient.cs index 61306bbe4..0324be56b 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Clients/UserInfoClient.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Clients/UserInfoClient.cs @@ -9,7 +9,7 @@ using System.Text; using System.Text.Json; using System.Threading.Tasks; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using Duende.IdentityModel.Client; using IntegrationTests.Clients.Setup; @@ -49,7 +49,7 @@ public async Task Valid_client_with_GET_should_succeed() Password = "bob" }); - response.IsError.Should().BeFalse(); + response.IsError.ShouldBeFalse(); var userInfo = await _client.GetUserInfoAsync(new UserInfoRequest { @@ -57,12 +57,12 @@ public async Task Valid_client_with_GET_should_succeed() Token = response.AccessToken }); - userInfo.IsError.Should().BeFalse(); - userInfo.Claims.Count().Should().Be(3); + userInfo.IsError.ShouldBeFalse(); + userInfo.Claims.Count().ShouldBe(3); - userInfo.Claims.Should().Contain(c => c.Type == "sub" && c.Value == "88421113"); - userInfo.Claims.Should().Contain(c => c.Type == "email" && c.Value == "BobSmith@example.com"); - userInfo.Claims.Should().Contain(c => c.Type == "email_verified" && c.Value == "true"); + userInfo.Claims.ShouldContain(c => c.Type == "sub" && c.Value == "88421113"); + userInfo.Claims.ShouldContain(c => c.Type == "email" && c.Value == "BobSmith@example.com"); + userInfo.Claims.ShouldContain(c => c.Type == "email_verified" && c.Value == "true"); } [Fact] @@ -79,7 +79,7 @@ public async Task Request_address_scope_should_return_expected_response() Password = "bob" }); - response.IsError.Should().BeFalse(); + response.IsError.ShouldBeFalse(); var userInfo = await _client.GetUserInfoAsync(new UserInfoRequest { @@ -87,8 +87,8 @@ public async Task Request_address_scope_should_return_expected_response() Token = response.AccessToken }); - userInfo.IsError.Should().BeFalse(); - userInfo.Claims.First().Value.Should().Be("{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }"); + userInfo.IsError.ShouldBeFalse(); + userInfo.Claims.First().Value.ShouldBe("{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }"); } [Fact] @@ -105,7 +105,7 @@ public async Task Using_a_token_with_no_identity_scope_should_fail() Password = "bob" }); - response.IsError.Should().BeFalse(); + response.IsError.ShouldBeFalse(); var userInfo = await _client.GetUserInfoAsync(new UserInfoRequest { @@ -113,8 +113,8 @@ public async Task Using_a_token_with_no_identity_scope_should_fail() Token = response.AccessToken }); - userInfo.IsError.Should().BeTrue(); - userInfo.HttpStatusCode.Should().Be(HttpStatusCode.Forbidden); + userInfo.IsError.ShouldBeTrue(); + userInfo.HttpStatusCode.ShouldBe(HttpStatusCode.Forbidden); } [Fact] @@ -131,7 +131,7 @@ public async Task Using_a_token_with_an_identity_scope_but_no_openid_should_fail Password = "bob" }); - response.IsError.Should().BeFalse(); + response.IsError.ShouldBeFalse(); var userInfo = await _client.GetUserInfoAsync(new UserInfoRequest { @@ -139,8 +139,8 @@ public async Task Using_a_token_with_an_identity_scope_but_no_openid_should_fail Token = response.AccessToken }); - userInfo.IsError.Should().BeTrue(); - userInfo.HttpStatusCode.Should().Be(HttpStatusCode.Forbidden); + userInfo.IsError.ShouldBeTrue(); + userInfo.HttpStatusCode.ShouldBe(HttpStatusCode.Forbidden); } [Fact] @@ -152,8 +152,8 @@ public async Task Invalid_token_should_fail() Token = "invalid" }); - userInfo.IsError.Should().BeTrue(); - userInfo.HttpStatusCode.Should().Be(HttpStatusCode.Unauthorized); + userInfo.IsError.ShouldBeTrue(); + userInfo.HttpStatusCode.ShouldBe(HttpStatusCode.Unauthorized); } [Fact] @@ -170,22 +170,22 @@ public async Task Complex_json_should_be_correct() Password = "bob" }); - response.IsError.Should().BeFalse(); + response.IsError.ShouldBeFalse(); var payload = GetPayload(response); var scopes = ((JsonElement) payload["scope"]).ToStringList(); - scopes.Count.Should().Be(5); - scopes.Should().Contain("openid"); - scopes.Should().Contain("email"); - scopes.Should().Contain("api1"); - scopes.Should().Contain("api4.with.roles"); - scopes.Should().Contain("roles"); + scopes.Count.ShouldBe(5); + scopes.ShouldContain("openid"); + scopes.ShouldContain("email"); + scopes.ShouldContain("api1"); + scopes.ShouldContain("api4.with.roles"); + scopes.ShouldContain("roles"); var roles = ((JsonElement) payload["role"]).ToStringList(); - roles.Count.Should().Be(2); - roles.Should().Contain("Geek"); - roles.Should().Contain("Developer"); + roles.Count.ShouldBe(2); + roles.ShouldContain("Geek"); + roles.ShouldContain("Developer"); var userInfo = await _client.GetUserInfoAsync(new UserInfoRequest { @@ -194,9 +194,9 @@ public async Task Complex_json_should_be_correct() }); roles = userInfo.Json?.TryGetStringArray("role").ToList(); - roles.Count.Should().Be(2); - roles.Should().Contain("Geek"); - roles.Should().Contain("Developer"); + roles.Count.ShouldBe(2); + roles.ShouldContain("Geek"); + roles.ShouldContain("Developer"); } private Dictionary GetPayload(TokenResponse response) diff --git a/identity-server/test/IdentityServer.IntegrationTests/Common/IdentityServerPipeline.cs b/identity-server/test/IdentityServer.IntegrationTests/Common/IdentityServerPipeline.cs index 2b66c5594..a060d2a6e 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Common/IdentityServerPipeline.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Common/IdentityServerPipeline.cs @@ -17,7 +17,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel.Client; using IdentityServer.IntegrationTests.Common; using Microsoft.AspNetCore.Authentication; @@ -461,7 +461,7 @@ public Duende.IdentityModel.Client.AuthorizeResponse ParseAuthorizationResponseU var url = CreateAuthorizeUrl(clientId, responseType, scope, redirectUri, state, nonce, loginHint, acrValues, responseMode, codeChallenge, codeChallengeMethod, requestUri, extra); var result = await BrowserClient.GetAsync(url); - result.StatusCode.Should().Be(HttpStatusCode.Found); + result.StatusCode.ShouldBe(HttpStatusCode.Found); BrowserClient.AllowAutoRedirect = old; diff --git a/identity-server/test/IdentityServer.IntegrationTests/Conformance/Basic/ClientAuthenticationTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Conformance/Basic/ClientAuthenticationTests.cs index 21d4e7962..43ff64ce9 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Conformance/Basic/ClientAuthenticationTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Conformance/Basic/ClientAuthenticationTests.cs @@ -9,7 +9,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Models; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel.Client; using IntegrationTests.Common; using Xunit; @@ -79,7 +79,7 @@ public async Task Token_endpoint_supports_client_authentication_with_basic_authe var response = await _pipeline.BrowserClient.GetAsync(url); var authorization = _pipeline.ParseAuthorizationResponseUrl(response.Headers.Location.ToString()); - authorization.Code.Should().NotBeNull(); + authorization.Code.ShouldNotBeNull(); var code = authorization.Code; @@ -96,15 +96,15 @@ public async Task Token_endpoint_supports_client_authentication_with_basic_authe RedirectUri = "https://code_pipeline.Client/callback?foo=bar&baz=quux" }); - tokenResult.IsError.Should().BeFalse(); - tokenResult.HttpErrorReason.Should().Be("OK"); - tokenResult.TokenType.Should().Be("Bearer"); - tokenResult.AccessToken.Should().NotBeNull(); - tokenResult.ExpiresIn.Should().BeGreaterThan(0); - tokenResult.IdentityToken.Should().NotBeNull(); + tokenResult.IsError.ShouldBeFalse(); + tokenResult.HttpErrorReason.ShouldBe("OK"); + tokenResult.TokenType.ShouldBe("Bearer"); + tokenResult.AccessToken.ShouldNotBeNull(); + tokenResult.ExpiresIn.ShouldBeGreaterThan(0); + tokenResult.IdentityToken.ShouldNotBeNull(); - wrapper.Response.Headers.CacheControl.NoCache.Should().BeTrue(); - wrapper.Response.Headers.CacheControl.NoStore.Should().BeTrue(); + wrapper.Response.Headers.CacheControl.NoCache.ShouldBeTrue(); + wrapper.Response.Headers.CacheControl.NoStore.ShouldBeTrue(); } [Fact] @@ -125,7 +125,7 @@ public async Task Token_endpoint_supports_client_authentication_with_form_encode var response = await _pipeline.BrowserClient.GetAsync(url); var authorization = _pipeline.ParseAuthorizationResponseUrl(response.Headers.Location.ToString()); - authorization.Code.Should().NotBeNull(); + authorization.Code.ShouldNotBeNull(); var code = authorization.Code; @@ -143,11 +143,11 @@ public async Task Token_endpoint_supports_client_authentication_with_form_encode RedirectUri = "https://code_pipeline.Client/callback?foo=bar&baz=quux" }); - tokenResult.IsError.Should().BeFalse(); - tokenResult.HttpErrorReason.Should().Be("OK"); - tokenResult.TokenType.Should().Be("Bearer"); - tokenResult.AccessToken.Should().NotBeNull(); - tokenResult.ExpiresIn.Should().BeGreaterThan(0); - tokenResult.IdentityToken.Should().NotBeNull(); + tokenResult.IsError.ShouldBeFalse(); + tokenResult.HttpErrorReason.ShouldBe("OK"); + tokenResult.TokenType.ShouldBe("Bearer"); + tokenResult.AccessToken.ShouldNotBeNull(); + tokenResult.ExpiresIn.ShouldBeGreaterThan(0); + tokenResult.IdentityToken.ShouldNotBeNull(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Conformance/Basic/CodeFlowTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Conformance/Basic/CodeFlowTests.cs index b1a578470..ee161e775 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Conformance/Basic/CodeFlowTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Conformance/Basic/CodeFlowTests.cs @@ -12,7 +12,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Models; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel.Client; using IntegrationTests.Common; using Xunit; @@ -82,7 +82,7 @@ public async Task No_state_should_not_result_in_shash() var response = await _pipeline.BrowserClient.GetAsync(url); var authorization = _pipeline.ParseAuthorizationResponseUrl(response.Headers.Location.ToString()); - authorization.Code.Should().NotBeNull(); + authorization.Code.ShouldNotBeNull(); var code = authorization.Code; @@ -99,17 +99,17 @@ public async Task No_state_should_not_result_in_shash() RedirectUri = "https://code_pipeline.Client/callback?foo=bar&baz=quux" }); - tokenResult.IsError.Should().BeFalse(); - tokenResult.HttpErrorReason.Should().Be("OK"); - tokenResult.TokenType.Should().Be("Bearer"); - tokenResult.AccessToken.Should().NotBeNull(); - tokenResult.ExpiresIn.Should().BeGreaterThan(0); - tokenResult.IdentityToken.Should().NotBeNull(); + tokenResult.IsError.ShouldBeFalse(); + tokenResult.HttpErrorReason.ShouldBe("OK"); + tokenResult.TokenType.ShouldBe("Bearer"); + tokenResult.AccessToken.ShouldNotBeNull(); + tokenResult.ExpiresIn.ShouldBeGreaterThan(0); + tokenResult.IdentityToken.ShouldNotBeNull(); var token = new JwtSecurityToken(tokenResult.IdentityToken); var s_hash = token.Claims.FirstOrDefault(c => c.Type == "s_hash"); - s_hash.Should().BeNull(); + s_hash.ShouldBeNull(); } [Theory] @@ -135,7 +135,7 @@ public async Task StateHash_should_be_emitted_based_on_options(bool emitStateHas var response = await _pipeline.BrowserClient.GetAsync(url); var authorization = _pipeline.ParseAuthorizationResponseUrl(response.Headers.Location.ToString()); - authorization.Code.Should().NotBeNull(); + authorization.Code.ShouldNotBeNull(); var code = authorization.Code; @@ -152,12 +152,12 @@ public async Task StateHash_should_be_emitted_based_on_options(bool emitStateHas RedirectUri = "https://code_pipeline.Client/callback?foo=bar&baz=quux" }); - tokenResult.IsError.Should().BeFalse(); - tokenResult.HttpErrorReason.Should().Be("OK"); - tokenResult.TokenType.Should().Be("Bearer"); - tokenResult.AccessToken.Should().NotBeNull(); - tokenResult.ExpiresIn.Should().BeGreaterThan(0); - tokenResult.IdentityToken.Should().NotBeNull(); + tokenResult.IsError.ShouldBeFalse(); + tokenResult.HttpErrorReason.ShouldBe("OK"); + tokenResult.TokenType.ShouldBe("Bearer"); + tokenResult.AccessToken.ShouldNotBeNull(); + tokenResult.ExpiresIn.ShouldBeGreaterThan(0); + tokenResult.IdentityToken.ShouldNotBeNull(); var token = new JwtSecurityToken(tokenResult.IdentityToken); @@ -165,12 +165,12 @@ public async Task StateHash_should_be_emitted_based_on_options(bool emitStateHas if (emitStateHash) { - s_hash.Should().NotBeNull(); - s_hash.Value.Should().Be(CryptoHelper.CreateHashClaimValue("state", "RS256")); + s_hash.ShouldNotBeNull(); + s_hash.Value.ShouldBe(CryptoHelper.CreateHashClaimValue("state", "RS256")); } else { - s_hash.Should().BeNull(); + s_hash.ShouldBeNull(); } } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Conformance/Basic/RedirectUriTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Conformance/Basic/RedirectUriTests.cs index 77b4d9e3b..5bd00bb8d 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Conformance/Basic/RedirectUriTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Conformance/Basic/RedirectUriTests.cs @@ -9,7 +9,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Models; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using IntegrationTests.Common; using Xunit; @@ -79,8 +79,8 @@ public async Task Reject_redirect_uri_not_matching_registered_redirect_uri() nonce: nonce); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe("invalid_request"); } [Fact] @@ -102,8 +102,8 @@ public async Task Reject_request_without_redirect_uri_when_multiple_registered() nonce: nonce); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe("invalid_request"); } [Fact] @@ -125,14 +125,14 @@ public async Task Preserves_query_parameters_in_redirect_uri() nonce: nonce); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://code_client/callback?"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://code_client/callback?"); var authorization = _mockPipeline.ParseAuthorizationResponseUrl(response.Headers.Location.ToString()); - authorization.Code.Should().NotBeNull(); - authorization.State.Should().Be(state); + authorization.Code.ShouldNotBeNull(); + authorization.State.ShouldBe(state); var query = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(response.Headers.Location.Query); - query["foo"].ToString().Should().Be("bar"); - query["baz"].ToString().Should().Be("quux"); + query["foo"].ToString().ShouldBe("bar"); + query["baz"].ToString().ShouldBe("quux"); } [Fact] @@ -153,7 +153,7 @@ public async Task Rejects_redirect_uri_when_query_parameter_does_not_match() nonce: nonce); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe("invalid_request"); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Conformance/Basic/ResponseTypeResponseModeTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Conformance/Basic/ResponseTypeResponseModeTests.cs index 08d73cf9a..b10199c64 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Conformance/Basic/ResponseTypeResponseModeTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Conformance/Basic/ResponseTypeResponseModeTests.cs @@ -9,7 +9,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Models; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using Duende.IdentityModel.Client; using IntegrationTests.Common; @@ -69,7 +69,7 @@ public async Task Request_with_response_type_code_supported() await _mockPipeline.LoginAsync("bob"); var metadata = await _mockPipeline.BackChannelClient.GetAsync(IdentityServerPipeline.DiscoveryEndpoint); - metadata.StatusCode.Should().Be(HttpStatusCode.OK); + metadata.StatusCode.ShouldBe(HttpStatusCode.OK); var state = Guid.NewGuid().ToString(); var nonce = Guid.NewGuid().ToString(); @@ -82,12 +82,12 @@ public async Task Request_with_response_type_code_supported() state: state, nonce: nonce); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Found); + response.StatusCode.ShouldBe(HttpStatusCode.Found); var authorization = new AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); - authorization.Code.Should().NotBeNull(); - authorization.State.Should().Be(state); + authorization.IsError.ShouldBeFalse(); + authorization.Code.ShouldNotBeNull(); + authorization.State.ShouldBe(state); } // this might not be in sync with the actual conformance tests @@ -116,6 +116,6 @@ public async Task Request_missing_response_type_rejected() _mockPipeline.BrowserClient.AllowAutoRedirect = true; var _ = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Conformance/Pkce/PkceTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Conformance/Pkce/PkceTests.cs index 362e1bb04..815be9778 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Conformance/Pkce/PkceTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Conformance/Pkce/PkceTests.cs @@ -10,7 +10,7 @@ using Duende.IdentityServer; using Duende.IdentityServer.Models; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using Duende.IdentityModel.Client; using IntegrationTests.Common; @@ -179,8 +179,8 @@ public async Task Client_cannot_use_plain_code_challenge_method(string clientId) codeChallenge: code_challenge, codeChallengeMethod: OidcConstants.CodeChallengeMethods.Plain); - _pipeline.ErrorWasCalled.Should().BeTrue(); - _pipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + _pipeline.ErrorWasCalled.ShouldBeTrue(); + _pipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Theory] @@ -201,7 +201,7 @@ public async Task Client_can_use_plain_code_challenge_method(string clientId) codeChallenge: code_challenge, codeChallengeMethod: OidcConstants.CodeChallengeMethods.Plain); - authorizeResponse.IsError.Should().BeFalse(); + authorizeResponse.IsError.ShouldBeFalse(); var code = authorizeResponse.Code; @@ -216,11 +216,11 @@ public async Task Client_can_use_plain_code_challenge_method(string clientId) CodeVerifier = code_verifier }); - tokenResponse.IsError.Should().BeFalse(); - tokenResponse.TokenType.Should().Be("Bearer"); - tokenResponse.AccessToken.Should().NotBeNull(); - tokenResponse.IdentityToken.Should().NotBeNull(); - tokenResponse.ExpiresIn.Should().BeGreaterThan(0); + tokenResponse.IsError.ShouldBeFalse(); + tokenResponse.TokenType.ShouldBe("Bearer"); + tokenResponse.AccessToken.ShouldNotBeNull(); + tokenResponse.IdentityToken.ShouldNotBeNull(); + tokenResponse.ExpiresIn.ShouldBeGreaterThan(0); } [Theory] @@ -241,7 +241,7 @@ public async Task Client_can_use_sha256_code_challenge_method(string clientId) codeChallenge: code_challenge, codeChallengeMethod: OidcConstants.CodeChallengeMethods.Sha256); - authorizeResponse.IsError.Should().BeFalse(); + authorizeResponse.IsError.ShouldBeFalse(); var code = authorizeResponse.Code; @@ -256,11 +256,11 @@ public async Task Client_can_use_sha256_code_challenge_method(string clientId) CodeVerifier = code_verifier }); - tokenResponse.IsError.Should().BeFalse(); - tokenResponse.TokenType.Should().Be("Bearer"); - tokenResponse.AccessToken.Should().NotBeNull(); - tokenResponse.IdentityToken.Should().NotBeNull(); - tokenResponse.ExpiresIn.Should().BeGreaterThan(0); + tokenResponse.IsError.ShouldBeFalse(); + tokenResponse.TokenType.ShouldBe("Bearer"); + tokenResponse.AccessToken.ShouldNotBeNull(); + tokenResponse.IdentityToken.ShouldNotBeNull(); + tokenResponse.ExpiresIn.ShouldBeGreaterThan(0); } [Theory] @@ -278,7 +278,7 @@ public async Task Authorize_request_needs_code_challenge(string clientId) redirect_uri, nonce: nonce); - authorizeResponse.Should().BeNull(); + authorizeResponse.ShouldBeNull(); } [Fact] @@ -294,7 +294,7 @@ public async Task Code_verifier_should_not_be_accepted_if_no_code_challenge_was_ redirect_uri, nonce: nonce); - authorizeResponse.IsError.Should().BeFalse(); + authorizeResponse.IsError.ShouldBeFalse(); var code = authorizeResponse.Code; @@ -309,7 +309,7 @@ public async Task Code_verifier_should_not_be_accepted_if_no_code_challenge_was_ CodeVerifier = code_verifier }); - tokenResponse.IsError.Should().BeTrue(); + tokenResponse.IsError.ShouldBeTrue(); } [Theory] @@ -331,8 +331,8 @@ public async Task Authorize_request_code_challenge_cannot_be_too_short(string cl nonce: nonce, codeChallenge:"a"); - _pipeline.ErrorWasCalled.Should().BeTrue(); - _pipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + _pipeline.ErrorWasCalled.ShouldBeTrue(); + _pipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Theory] @@ -355,8 +355,8 @@ public async Task Authorize_request_code_challenge_cannot_be_too_long(string cli codeChallenge: new string('a', _pipeline.Options.InputLengthRestrictions.CodeChallengeMaxLength + 1) ); - _pipeline.ErrorWasCalled.Should().BeTrue(); - _pipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + _pipeline.ErrorWasCalled.ShouldBeTrue(); + _pipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Theory] @@ -380,7 +380,7 @@ public async Task Authorize_request_needs_supported_code_challenge_method(string codeChallengeMethod: "unknown_code_challenge_method" ); - authorizeResponse.Should().BeNull(); + authorizeResponse.ShouldBeNull(); } [Theory] @@ -401,7 +401,7 @@ public async Task Token_request_needs_code_verifier(string clientId) codeChallenge: code_challenge, codeChallengeMethod: OidcConstants.CodeChallengeMethods.Plain); - authorizeResponse.IsError.Should().BeFalse(); + authorizeResponse.IsError.ShouldBeFalse(); var code = authorizeResponse.Code; @@ -415,8 +415,8 @@ public async Task Token_request_needs_code_verifier(string clientId) RedirectUri = redirect_uri, }); - tokenResponse.IsError.Should().BeTrue(); - tokenResponse.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + tokenResponse.IsError.ShouldBeTrue(); + tokenResponse.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Theory] @@ -437,7 +437,7 @@ public async Task Token_request_code_verifier_cannot_be_too_short(string clientI codeChallenge: code_challenge, codeChallengeMethod: OidcConstants.CodeChallengeMethods.Plain); - authorizeResponse.IsError.Should().BeFalse(); + authorizeResponse.IsError.ShouldBeFalse(); var code = authorizeResponse.Code; @@ -452,8 +452,8 @@ public async Task Token_request_code_verifier_cannot_be_too_short(string clientI CodeVerifier = "a" }); - tokenResponse.IsError.Should().BeTrue(); - tokenResponse.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + tokenResponse.IsError.ShouldBeTrue(); + tokenResponse.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Theory] @@ -474,7 +474,7 @@ public async Task Token_request_code_verifier_cannot_be_too_long(string clientId codeChallenge: code_challenge, codeChallengeMethod: OidcConstants.CodeChallengeMethods.Plain); - authorizeResponse.IsError.Should().BeFalse(); + authorizeResponse.IsError.ShouldBeFalse(); var code = authorizeResponse.Code; @@ -489,8 +489,8 @@ public async Task Token_request_code_verifier_cannot_be_too_long(string clientId CodeVerifier = new string('a', _pipeline.Options.InputLengthRestrictions.CodeVerifierMaxLength + 1) }); - tokenResponse.IsError.Should().BeTrue(); - tokenResponse.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + tokenResponse.IsError.ShouldBeTrue(); + tokenResponse.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Theory] @@ -511,7 +511,7 @@ public async Task Token_request_code_verifier_must_match_with_code_chalenge(stri codeChallenge: code_challenge, codeChallengeMethod: OidcConstants.CodeChallengeMethods.Plain); - authorizeResponse.IsError.Should().BeFalse(); + authorizeResponse.IsError.ShouldBeFalse(); var code = authorizeResponse.Code; @@ -526,8 +526,8 @@ public async Task Token_request_code_verifier_must_match_with_code_chalenge(stri CodeVerifier = "mismatched_code_verifier" }); - tokenResponse.IsError.Should().BeTrue(); - tokenResponse.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + tokenResponse.IsError.ShouldBeTrue(); + tokenResponse.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } private static string Sha256OfCodeVerifier(string codeVerifier) diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/AuthorizeTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/AuthorizeTests.cs index 53cf2f4a8..a855f74c9 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/AuthorizeTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/AuthorizeTests.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Net; using System.Net.Http; using System.Security.Claims; @@ -16,7 +17,7 @@ using Duende.IdentityServer.Stores.Default; using Duende.IdentityServer.Test; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using IntegrationTests.Common; using Microsoft.Extensions.DependencyInjection; @@ -124,7 +125,7 @@ public async Task get_request_should_not_return_404() { var response = await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.AuthorizeEndpoint); - response.StatusCode.Should().NotBe(HttpStatusCode.NotFound); + response.StatusCode.ShouldNotBe(HttpStatusCode.NotFound); } [Fact] @@ -133,7 +134,7 @@ public async Task post_request_without_form_should_return_415() { var response = await _mockPipeline.BrowserClient.PostAsync(IdentityServerPipeline.AuthorizeEndpoint, new StringContent("foo")); - response.StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType); + response.StatusCode.ShouldBe(HttpStatusCode.UnsupportedMediaType); } [Fact] @@ -144,7 +145,7 @@ public async Task post_request_should_return_200() new FormUrlEncodedContent( new Dictionary { })); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); } [Fact] @@ -153,7 +154,7 @@ public async Task get_request_should_not_return_500() { var response = await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.AuthorizeEndpoint); - ((int)response.StatusCode).Should().BeLessThan(500); + ((int)response.StatusCode).ShouldBeLessThan(500); } [Fact] @@ -169,7 +170,7 @@ public async Task anonymous_user_should_be_redirected_to_login_page() nonce: "123_nonce"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginWasCalled.Should().BeTrue(); + _mockPipeline.LoginWasCalled.ShouldBeTrue(); } [Theory] @@ -205,16 +206,16 @@ public async Task signin_request_should_have_authorization_params(Type storeType }); var response = await _mockPipeline.BrowserClient.GetAsync(url + "&foo=foo1&foo=foo2"); - _mockPipeline.LoginRequest.Should().NotBeNull(); - _mockPipeline.LoginRequest.Client.ClientId.Should().Be("client1"); - _mockPipeline.LoginRequest.DisplayMode.Should().Be("popup"); - _mockPipeline.LoginRequest.UiLocales.Should().Be("ui_locale_value"); - _mockPipeline.LoginRequest.IdP.Should().Be("idp_value"); - _mockPipeline.LoginRequest.Tenant.Should().Be("tenant_value"); - _mockPipeline.LoginRequest.LoginHint.Should().Be("login_hint_value"); - _mockPipeline.LoginRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); - _mockPipeline.LoginRequest.Parameters.AllKeys.Should().Contain("foo"); - _mockPipeline.LoginRequest.Parameters.GetValues("foo").Should().BeEquivalentTo(new[] { "foo1", "foo2" }); + _mockPipeline.LoginRequest.ShouldNotBeNull(); + _mockPipeline.LoginRequest.Client.ClientId.ShouldBe("client1"); + _mockPipeline.LoginRequest.DisplayMode.ShouldBe("popup"); + _mockPipeline.LoginRequest.UiLocales.ShouldBe("ui_locale_value"); + _mockPipeline.LoginRequest.IdP.ShouldBe("idp_value"); + _mockPipeline.LoginRequest.Tenant.ShouldBe("tenant_value"); + _mockPipeline.LoginRequest.LoginHint.ShouldBe("login_hint_value"); + _mockPipeline.LoginRequest.AcrValues.ShouldBeEquivalentTo(new string[] { "acr_2", "acr_1" }); + _mockPipeline.LoginRequest.Parameters.AllKeys.ShouldContain("foo"); + _mockPipeline.LoginRequest.Parameters.GetValues("foo").ShouldBeEquivalentTo(new[] { "foo1", "foo2" }); } [Fact] @@ -233,14 +234,14 @@ public async Task signin_response_should_allow_successful_authorization_response nonce: "123_nonce"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client1/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client1/callback"); var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); - authorization.IdentityToken.Should().NotBeNull(); - authorization.State.Should().Be("123_state"); - authorization.Values.Keys.Should().NotContain("iss"); + authorization.IsError.ShouldBeFalse(); + authorization.IdentityToken.ShouldNotBeNull(); + authorization.State.ShouldBe("123_state"); + authorization.Values.Keys.ShouldNotContain("iss"); } [Fact] @@ -259,18 +260,18 @@ public async Task code_success_response_should_have_all_expected_values() nonce: "123_nonce"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client4/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client4/callback"); var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); - authorization.IdentityToken.Should().BeNull(); - authorization.AccessToken.Should().BeNull(); - authorization.Code.Should().NotBeNullOrEmpty(); - authorization.Scope.Should().Be("openid"); - authorization.State.Should().Be("123_state"); - authorization.Values["session_state"].Should().NotBeNullOrEmpty(); - authorization.Values["iss"].Should().Be("https%3A%2F%2Fserver"); + authorization.IsError.ShouldBeFalse(); + authorization.IdentityToken.ShouldBeNull(); + authorization.AccessToken.ShouldBeNull(); + authorization.Code.ShouldNotBeNullOrEmpty(); + authorization.Scope.ShouldBe("openid"); + authorization.State.ShouldBe("123_state"); + authorization.Values["session_state"].ShouldNotBeNullOrEmpty(); + authorization.Values["iss"].ShouldBe("https%3A%2F%2Fserver"); } [Fact] @@ -290,13 +291,13 @@ public async Task authenticated_user_with_valid_request_should_receive_authoriza nonce: "123_nonce"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client1/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client1/callback"); var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); - authorization.IdentityToken.Should().NotBeNull(); - authorization.State.Should().Be("123_state"); + authorization.IsError.ShouldBeFalse(); + authorization.IdentityToken.ShouldNotBeNull(); + authorization.State.ShouldBe("123_state"); } [Theory] @@ -333,15 +334,15 @@ public async Task login_response_and_consent_response_should_receive_authorizati nonce: "123_nonce"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client2/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client2/callback"); var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); - authorization.IdentityToken.Should().NotBeNull(); - authorization.State.Should().Be("123_state"); + authorization.IsError.ShouldBeFalse(); + authorization.IdentityToken.ShouldNotBeNull(); + authorization.State.ShouldBe("123_state"); var scopes = authorization.Scope.Split(' '); - scopes.Should().BeEquivalentTo(new string[] { "profile", "api1", "openid" }); + scopes.ShouldBeEquivalentTo(new string[] { "profile", "api1", "openid" }); } [Fact] @@ -358,8 +359,8 @@ public async Task idp_should_be_passed_to_login_page() acrValues: "idp:google"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginWasCalled.Should().BeTrue(); - _mockPipeline.LoginRequest.IdP.Should().Be("google"); + _mockPipeline.LoginWasCalled.ShouldBeTrue(); + _mockPipeline.LoginRequest.IdP.ShouldBe("google"); } [Fact] @@ -376,8 +377,8 @@ public async Task idp_not_allowed_by_client_should_not_be_passed_to_login_page() acrValues: "idp:facebook"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginWasCalled.Should().BeTrue(); - _mockPipeline.LoginRequest.IdP.Should().BeNull(); + _mockPipeline.LoginWasCalled.ShouldBeTrue(); + _mockPipeline.LoginRequest.IdP.ShouldBeNull(); } [Fact] @@ -395,8 +396,8 @@ public async Task user_idp_not_allowed_by_client_should_cause_login_page() nonce: "123_nonce"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginWasCalled.Should().BeTrue(); - _mockPipeline.LoginRequest.IdP.Should().BeNull(); + _mockPipeline.LoginWasCalled.ShouldBeTrue(); + _mockPipeline.LoginRequest.IdP.ShouldBeNull(); } [Fact] @@ -416,8 +417,8 @@ public async Task user_idp_does_not_match_acr_idp_should_cause_login_page() acrValues: "idp:idp2"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginWasCalled.Should().BeTrue(); - _mockPipeline.LoginRequest.IdP.Should().Be("idp2"); + _mockPipeline.LoginWasCalled.ShouldBeTrue(); + _mockPipeline.LoginRequest.IdP.ShouldBe("idp2"); } [Fact] @@ -439,8 +440,8 @@ public async Task when_tenant_validation_enabled_user_tenant_does_not_match_acr_ acrValues: "tenant:t2"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginWasCalled.Should().BeTrue(); - _mockPipeline.LoginRequest.Tenant.Should().Be("t2"); + _mockPipeline.LoginWasCalled.ShouldBeTrue(); + _mockPipeline.LoginRequest.Tenant.ShouldBe("t2"); } [Fact] @@ -461,7 +462,7 @@ public async Task when_tenant_validation_disabled_user_tenant_does_not_match_acr acrValues: "tenant:t2"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginWasCalled.Should().BeFalse(); + _mockPipeline.LoginWasCalled.ShouldBeFalse(); } [Fact] @@ -479,8 +480,8 @@ public async Task for_invalid_client_error_page_should_not_receive_client_id() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.ClientId.Should().BeNull(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.ClientId.ShouldBeNull(); } [Fact] @@ -498,8 +499,8 @@ public async Task error_page_should_receive_client_id() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.ClientId.Should().Be("client1"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.ClientId.ShouldBe("client1"); } [Fact] @@ -517,9 +518,9 @@ public async Task invalid_redirect_uri_should_show_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("redirect_uri"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("redirect_uri"); } [Fact] @@ -537,9 +538,9 @@ public async Task invalid_redirect_uri_should_not_pass_return_url_to_error_page( nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.RedirectUri.Should().BeNull(); - _mockPipeline.ErrorMessage.ResponseMode.Should().BeNull(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.RedirectUri.ShouldBeNull(); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBeNull(); } [Fact] @@ -557,8 +558,8 @@ public async Task invalid_client_id_should_show_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.UnauthorizedClient); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnauthorizedClient); } [Fact] @@ -576,9 +577,9 @@ public async Task invalid_client_id_should_not_pass_return_url_to_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.RedirectUri.Should().BeNull(); - _mockPipeline.ErrorMessage.ResponseMode.Should().BeNull(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.RedirectUri.ShouldBeNull(); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBeNull(); } [Fact] @@ -596,9 +597,9 @@ public async Task missing_redirect_uri_should_show_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.UnauthorizedClient); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("client"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnauthorizedClient); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("client"); } [Fact] @@ -616,9 +617,9 @@ public async Task missing_redirect_uri_should_not_pass_return_url_to_error_page( nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.RedirectUri.Should().BeNull(); - _mockPipeline.ErrorMessage.ResponseMode.Should().BeNull(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.RedirectUri.ShouldBeNull(); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBeNull(); } [Fact] @@ -636,9 +637,9 @@ public async Task malformed_redirect_uri_should_show_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.UnauthorizedClient); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("client"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnauthorizedClient); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("client"); } [Fact] @@ -658,8 +659,8 @@ public async Task disabled_client_should_show_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.UnauthorizedClient); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnauthorizedClient); } [Fact] @@ -679,9 +680,9 @@ public async Task disabled_client_should_not_pass_return_url_to_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.RedirectUri.Should().BeNull(); - _mockPipeline.ErrorMessage.ResponseMode.Should().BeNull(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.RedirectUri.ShouldBeNull(); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBeNull(); } [Fact] @@ -701,9 +702,9 @@ public async Task invalid_protocol_for_client_should_show_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.UnauthorizedClient); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("protocol"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnauthorizedClient); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("protocol"); } [Fact] @@ -723,9 +724,9 @@ public async Task invalid_protocol_for_client_should_not_pass_return_url_to_erro nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.RedirectUri.Should().BeNull(); - _mockPipeline.ErrorMessage.ResponseMode.Should().BeNull(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.RedirectUri.ShouldBeNull(); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBeNull(); } [Fact] @@ -743,8 +744,8 @@ public async Task invalid_response_type_should_show_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.UnsupportedResponseType); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnsupportedResponseType); } [Fact] @@ -762,9 +763,9 @@ public async Task invalid_response_type_should_not_pass_return_url_to_error_page nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.RedirectUri.Should().BeNull(); - _mockPipeline.ErrorMessage.ResponseMode.Should().BeNull(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.RedirectUri.ShouldBeNull(); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBeNull(); } [Fact] @@ -783,9 +784,9 @@ public async Task invalid_response_mode_for_flow_should_show_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("response_mode"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("response_mode"); } [Fact] @@ -804,9 +805,9 @@ public async Task invalid_response_mode_for_flow_should_pass_return_url_to_error nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback"); - _mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.RedirectUri.ShouldStartWith("https://client1/callback"); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBe("fragment"); } [Fact] @@ -825,9 +826,9 @@ public async Task invalid_response_mode_should_show_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.UnsupportedResponseType); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("response_mode"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnsupportedResponseType); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("response_mode"); } [Fact] @@ -846,9 +847,9 @@ public async Task invalid_response_mode_should_pass_return_url_to_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback"); - _mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.RedirectUri.ShouldStartWith("https://client1/callback"); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBe("fragment"); } [Fact] @@ -866,9 +867,9 @@ public async Task missing_scope_should_show_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("scope"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("scope"); } [Fact] @@ -886,9 +887,9 @@ public async Task missing_scope_should_pass_return_url_to_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback"); - _mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.RedirectUri.ShouldStartWith("https://client1/callback"); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBe("fragment"); } [Fact] @@ -907,9 +908,9 @@ public async Task explicit_response_mode_should_be_passed_to_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback"); - _mockPipeline.ErrorMessage.ResponseMode.Should().Be("form_post"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.RedirectUri.ShouldStartWith("https://client1/callback"); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBe("form_post"); } [Fact] @@ -927,11 +928,11 @@ public async Task scope_too_long_should_show_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("scope"); - _mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback"); - _mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("scope"); + _mockPipeline.ErrorMessage.RedirectUri.ShouldStartWith("https://client1/callback"); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBe("fragment"); } [Fact] @@ -949,12 +950,12 @@ public async Task missing_openid_scope_should_show_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("scope"); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("openid"); - _mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback"); - _mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("scope"); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("openid"); + _mockPipeline.ErrorMessage.RedirectUri.ShouldStartWith("https://client1/callback"); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBe("fragment"); } [Fact] @@ -972,11 +973,11 @@ public async Task client_not_allowed_access_to_scope_should_show_error_page() nonce: "123_nonce"); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidScope); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("scope"); - _mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback"); - _mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("scope"); + _mockPipeline.ErrorMessage.RedirectUri.ShouldStartWith("https://client1/callback"); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBe("fragment"); } [Fact] @@ -995,11 +996,11 @@ public async Task missing_nonce_should_show_error_page() ); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("nonce"); - _mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback"); - _mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("nonce"); + _mockPipeline.ErrorMessage.RedirectUri.ShouldStartWith("https://client1/callback"); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBe("fragment"); } [Fact] @@ -1017,11 +1018,11 @@ public async Task nonce_too_long_should_show_error_page() nonce: new string('x', 500)); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("nonce"); - _mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback"); - _mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("nonce"); + _mockPipeline.ErrorMessage.RedirectUri.ShouldStartWith("https://client1/callback"); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBe("fragment"); } [Fact] @@ -1040,11 +1041,11 @@ public async Task locale_too_long_should_show_error_page() extra: new { ui_locales = new string('x', 500) }); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("ui_locales"); - _mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback"); - _mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("ui_locales"); + _mockPipeline.ErrorMessage.RedirectUri.ShouldStartWith("https://client1/callback"); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBe("fragment"); } [Fact] @@ -1063,11 +1064,11 @@ public async Task invalid_max_age_should_show_error_page() extra: new { max_age = "invalid" }); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("max_age"); - _mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback"); - _mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("max_age"); + _mockPipeline.ErrorMessage.RedirectUri.ShouldStartWith("https://client1/callback"); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBe("fragment"); } [Fact] @@ -1086,11 +1087,11 @@ public async Task negative_max_age_should_show_error_page() extra: new { max_age = "-10" }); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("max_age"); - _mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback"); - _mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("max_age"); + _mockPipeline.ErrorMessage.RedirectUri.ShouldStartWith("https://client1/callback"); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBe("fragment"); } [Fact] @@ -1109,11 +1110,11 @@ public async Task login_hint_too_long_should_show_error_page() loginHint: new string('x', 500)); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("login_hint"); - _mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback"); - _mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("login_hint"); + _mockPipeline.ErrorMessage.RedirectUri.ShouldStartWith("https://client1/callback"); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBe("fragment"); } [Fact] @@ -1132,11 +1133,11 @@ public async Task acr_values_too_long_should_show_error_page() acrValues: new string('x', 500)); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Contain("acr_values"); - _mockPipeline.ErrorMessage.RedirectUri.Should().StartWith("https://client1/callback"); - _mockPipeline.ErrorMessage.ResponseMode.Should().Be("fragment"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldContain("acr_values"); + _mockPipeline.ErrorMessage.RedirectUri.ShouldStartWith("https://client1/callback"); + _mockPipeline.ErrorMessage.ResponseMode.ShouldBe("fragment"); } [Fact] @@ -1159,7 +1160,7 @@ public async Task overlapping_identity_scopes_and_api_scopes_should_show_error_p nonce: "123_nonce"); Func a = () => _mockPipeline.BrowserClient.GetAsync(url); - await a.Should().ThrowAsync(); + await a.ShouldThrowAsync(); } [Fact] @@ -1179,8 +1180,8 @@ public async Task ui_locales_should_be_passed_to_error_page() extra: new { ui_locales = "fr-FR" }); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.UiLocales.Should().Be("fr-FR"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.UiLocales.ShouldBe("fr-FR"); } [Fact] @@ -1200,8 +1201,8 @@ public async Task display_mode_should_be_passed_to_error_page() extra: new { display = "popup" }); await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.DisplayMode.Should().Be("popup"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.DisplayMode.ShouldBe("popup"); } [Fact] @@ -1218,7 +1219,7 @@ public async Task unicode_values_in_url_should_be_processed_correctly() url = url.Replace(IdentityServerPipeline.BaseUrl, "https://грант.рф"); var result = await _mockPipeline.BackChannelClient.GetAsync(url); - result.Headers.Location.Authority.Should().Be("xn--80af5akm.xn--p1ai"); + result.Headers.Location.Authority.ShouldBe("xn--80af5akm.xn--p1ai"); } [Fact] @@ -1235,7 +1236,7 @@ public async Task code_flow_with_fragment_response_type_should_be_allowed() nonce: "123_nonce"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginWasCalled.Should().BeTrue(); + _mockPipeline.LoginWasCalled.ShouldBeTrue(); } [Fact] @@ -1255,8 +1256,8 @@ public async Task prompt_login_should_show_login_page_and_preserve_prompt_values ); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginWasCalled.Should().BeTrue(); - _mockPipeline.LoginRequest.PromptModes.Should().Contain("login"); + _mockPipeline.LoginWasCalled.ShouldBeTrue(); + _mockPipeline.LoginRequest.PromptModes.ShouldContain("login"); } [Fact] @@ -1276,7 +1277,7 @@ public async Task max_age_0_should_show_login_page() ); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginWasCalled.Should().BeTrue(); + _mockPipeline.LoginWasCalled.ShouldBeTrue(); } [Fact] @@ -1300,9 +1301,9 @@ public async Task prompt_login_should_allow_user_to_login_and_complete_authoriza // this simulates the login page returning to the returnUrl which is the authorize callback page _mockPipeline.BrowserClient.AllowAutoRedirect = false; response = await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.BaseUrl + _mockPipeline.LoginReturnUrl); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client1/callback"); - response.Headers.Location.ToString().Should().Contain("id_token="); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client1/callback"); + response.Headers.Location.ToString().ShouldContain("id_token="); } [Fact] @@ -1326,9 +1327,9 @@ public async Task max_age_0_should_allow_user_to_login_and_complete_authorizatio // this simulates the login page returning to the returnUrl which is the authorize callback page _mockPipeline.BrowserClient.AllowAutoRedirect = false; response = await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.BaseUrl + _mockPipeline.LoginReturnUrl); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client1/callback"); - response.Headers.Location.ToString().Should().Contain("id_token="); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client1/callback"); + response.Headers.Location.ToString().ShouldContain("id_token="); } [Fact] @@ -1346,7 +1347,7 @@ public async Task unknown_prompt_should_error() ); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); } [Fact] @@ -1364,7 +1365,7 @@ public async Task without_config_prompt_create_should_be_treated_as_unknown() ); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); } [Fact] @@ -1393,8 +1394,8 @@ public async Task with_config_prompt_create_should_show_create_account_page_and_ ); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.CreateAccountWasCalled.Should().BeTrue(); - _mockPipeline.CreateAccountRequest.PromptModes.Should().Contain("create"); + _mockPipeline.CreateAccountWasCalled.ShouldBeTrue(); + _mockPipeline.CreateAccountRequest.PromptModes.ShouldContain("create"); } [Fact] @@ -1423,7 +1424,7 @@ public async Task prompt_create_and_login_should_be_an_error() ); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); } @@ -1472,18 +1473,18 @@ public async Task custom_request_should_have_authorization_params(Type storeType }); var response = await _mockPipeline.BrowserClient.GetAsync(url + "&foo=bar"); - _mockPipeline.CustomWasCalled.Should().BeTrue(); + _mockPipeline.CustomWasCalled.ShouldBeTrue(); - _mockPipeline.CustomRequest.Should().NotBeNull(); - _mockPipeline.CustomRequest.Client.ClientId.Should().Be("client1"); - _mockPipeline.CustomRequest.DisplayMode.Should().Be("popup"); - _mockPipeline.CustomRequest.UiLocales.Should().Be("ui_locale_value"); - _mockPipeline.CustomRequest.IdP.Should().Be("idp_value"); - _mockPipeline.CustomRequest.Tenant.Should().Be("tenant_value"); - _mockPipeline.CustomRequest.LoginHint.Should().Be("login_hint_value"); - _mockPipeline.CustomRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); - _mockPipeline.CustomRequest.Parameters.AllKeys.Should().Contain("foo"); - _mockPipeline.CustomRequest.Parameters["foo"].Should().Be("bar"); + _mockPipeline.CustomRequest.ShouldNotBeNull(); + _mockPipeline.CustomRequest.Client.ClientId.ShouldBe("client1"); + _mockPipeline.CustomRequest.DisplayMode.ShouldBe("popup"); + _mockPipeline.CustomRequest.UiLocales.ShouldBe("ui_locale_value"); + _mockPipeline.CustomRequest.IdP.ShouldBe("idp_value"); + _mockPipeline.CustomRequest.Tenant.ShouldBe("tenant_value"); + _mockPipeline.CustomRequest.LoginHint.ShouldBe("login_hint_value"); + _mockPipeline.CustomRequest.AcrValues.ShouldBeEquivalentTo(new string[] { "acr_2", "acr_1" }); + _mockPipeline.CustomRequest.Parameters.AllKeys.ShouldContain("foo"); + _mockPipeline.CustomRequest.Parameters["foo"].ShouldBe("bar"); } [Fact] @@ -1505,7 +1506,7 @@ public async Task custom_prompt_values_should_raise_error_with_default_interacti _mockPipeline.BrowserClient.AllowAutoRedirect = false; Func a = () => _mockPipeline.BrowserClient.GetAsync(url); - await a.Should().ThrowAsync(); + await a.ShouldThrowAsync(); } [Fact] @@ -1536,10 +1537,9 @@ public async Task custom_prompt_value_should_be_passed_to_custom_interaction_ser _mockPipeline.BrowserClient.AllowAutoRedirect = false; var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.Headers.Location.GetLeftPart(UriPartial.Path).Should().Be("https://server/custom"); - mockAuthzInteractionService.Request.PromptModes.Should() - .Contain("custom-prompt").And - .HaveCount(1); + response.Headers.Location.GetLeftPart(UriPartial.Path).ShouldBe("https://server/custom"); + mockAuthzInteractionService.Request.PromptModes.ShouldContain("custom-prompt"); + mockAuthzInteractionService.Request.PromptModes.Count().ShouldBe(1); } } diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/ConsentTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/ConsentTests.cs index f34b5a46f..a0f2bff5f 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/ConsentTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/ConsentTests.cs @@ -16,7 +16,7 @@ using Duende.IdentityServer.Stores.Default; using Duende.IdentityServer.Stores.Serialization; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using IntegrationTests.Common; using Microsoft.Extensions.DependencyInjection; using Xunit; @@ -119,7 +119,7 @@ public async Task client_requires_consent_should_show_consent_page() ); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ConsentWasCalled.Should().BeTrue(); + _mockPipeline.ConsentWasCalled.ShouldBeTrue(); } [Theory] @@ -158,15 +158,15 @@ public async Task consent_page_should_have_authorization_params(Type storeType) ); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ConsentRequest.Should().NotBeNull(); - _mockPipeline.ConsentRequest.Client.ClientId.Should().Be("client2"); - _mockPipeline.ConsentRequest.DisplayMode.Should().Be("popup"); - _mockPipeline.ConsentRequest.UiLocales.Should().Be("ui_locale_value"); - _mockPipeline.ConsentRequest.Tenant.Should().Be("tenant_value"); - _mockPipeline.ConsentRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); - _mockPipeline.ConsentRequest.Parameters.AllKeys.Should().Contain("custom_foo"); - _mockPipeline.ConsentRequest.Parameters["custom_foo"].Should().Be("foo_value"); - _mockPipeline.ConsentRequest.ValidatedResources.RawScopeValues.Should().BeEquivalentTo(new string[] { "api2", "openid", "api1" }); + _mockPipeline.ConsentRequest.ShouldNotBeNull(); + _mockPipeline.ConsentRequest.Client.ClientId.ShouldBe("client2"); + _mockPipeline.ConsentRequest.DisplayMode.ShouldBe("popup"); + _mockPipeline.ConsentRequest.UiLocales.ShouldBe("ui_locale_value"); + _mockPipeline.ConsentRequest.Tenant.ShouldBe("tenant_value"); + _mockPipeline.ConsentRequest.AcrValues.ShouldBeEquivalentTo(new string[] { "acr_2", "acr_1" }); + _mockPipeline.ConsentRequest.Parameters.AllKeys.ShouldContain("custom_foo"); + _mockPipeline.ConsentRequest.Parameters["custom_foo"].ShouldBe("foo_value"); + _mockPipeline.ConsentRequest.ValidatedResources.RawScopeValues.ShouldBeEquivalentTo(new string[] { "api2", "openid", "api1" }); } [Theory] @@ -202,15 +202,15 @@ public async Task consent_response_should_allow_successful_authorization_respons nonce: "123_nonce"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client2/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client2/callback"); var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); - authorization.IdentityToken.Should().NotBeNull(); - authorization.State.Should().Be("123_state"); + authorization.IsError.ShouldBeFalse(); + authorization.IdentityToken.ShouldNotBeNull(); + authorization.State.ShouldBe("123_state"); var scopes = authorization.Scope.Split(' '); - scopes.Should().BeEquivalentTo(new string[] { "api2", "openid" }); + scopes.ShouldBeEquivalentTo(new string[] { "api2", "openid" }); } [Fact] @@ -234,20 +234,20 @@ public async Task consent_response_should_reject_modified_request_params() nonce: "123_nonce"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://server/consent"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://server/consent"); response = await _mockPipeline.BrowserClient.GetAsync(response.Headers.Location.ToString()); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("/connect/authorize/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("/connect/authorize/callback"); var modifiedAuthorizeCallback = "https://server" + response.Headers.Location; modifiedAuthorizeCallback = modifiedAuthorizeCallback.Replace("api2", "api1%20api2"); response = await _mockPipeline.BrowserClient.GetAsync(modifiedAuthorizeCallback); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://server/consent"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://server/consent"); } [Fact()] @@ -270,13 +270,13 @@ public async Task consent_response_missing_required_scopes_should_error() state: "123_state", nonce: "123_nonce"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client2/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client2/callback"); var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeTrue(); - authorization.Error.Should().Be("access_denied"); - authorization.State.Should().Be("123_state"); + authorization.IsError.ShouldBeTrue(); + authorization.Error.ShouldBe("access_denied"); + authorization.State.ShouldBe("123_state"); } [Theory] @@ -313,13 +313,13 @@ public async Task consent_response_of_temporarily_unavailable_should_return_erro nonce: "123_nonce"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client2/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client2/callback"); var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeTrue(); - authorization.Error.Should().Be("temporarily_unavailable"); - authorization.ErrorDescription.Should().Be("some description"); + authorization.IsError.ShouldBeTrue(); + authorization.Error.ShouldBe("temporarily_unavailable"); + authorization.ErrorDescription.ShouldBe("some description"); } [Theory] @@ -356,13 +356,13 @@ public async Task consent_response_of_unmet_authentication_requirements_should_r nonce: "123_nonce"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client2/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client2/callback"); var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeTrue(); - authorization.Error.Should().Be("unmet_authentication_requirements"); - authorization.ErrorDescription.Should().Be("some description"); + authorization.IsError.ShouldBeTrue(); + authorization.Error.ShouldBe("unmet_authentication_requirements"); + authorization.ErrorDescription.ShouldBe("some description"); } [Fact] @@ -417,15 +417,15 @@ public async Task legacy_consents_should_apply_and_be_migrated_to_hex_encoding() var response = await _mockPipeline.BrowserClient.GetAsync(url); // The existing legacy consent should apply - user isn't show consent screen - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client2/callback"); - _mockPipeline.ConsentWasCalled.Should().BeFalse(); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client2/callback"); + _mockPipeline.ConsentWasCalled.ShouldBeFalse(); // The legacy consent should be migrated to use a new key... // Old key shouldn't find anything var grant = await persistedGrantStore.GetAsync(legacyKey); - grant.Should().BeNull(); + grant.ShouldBeNull(); // New key should var hexEncodedKeyNoHash = $"{clientId}|{subjectId}-1:{IdentityServerConstants.PersistedGrantTypes.UserConsent}"; @@ -435,9 +435,9 @@ public async Task legacy_consents_should_apply_and_be_migrated_to_hex_encoding() var hash = sha.ComputeHash(bytes); var hexEncodedKey = BitConverter.ToString(hash).Replace("-", ""); grant = await persistedGrantStore.GetAsync(hexEncodedKey); - grant.Should().NotBeNull(); - grant.ClientId.Should().Be(clientId); - grant.SubjectId.Should().Be(subjectId); + grant.ShouldNotBeNull(); + grant.ClientId.ShouldBe(clientId); + grant.SubjectId.ShouldBe(subjectId); } } } diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/JwtRequestAuthorizeTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/JwtRequestAuthorizeTests.cs index 1cc8f55f9..285f7295e 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/JwtRequestAuthorizeTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/JwtRequestAuthorizeTests.cs @@ -20,13 +20,14 @@ using Duende.IdentityServer.Stores; using Duende.IdentityServer.Stores.Default; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using IntegrationTests.Common; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Logging; using Microsoft.IdentityModel.Tokens; using Xunit; +using Microsoft.AspNetCore.Http; namespace IntegrationTests.Endpoints.Authorize; @@ -220,9 +221,9 @@ public async Task missing_request_object_should_fail() var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request"); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Be("Client must use request object, but no request or request_uri parameter present"); - _mockPipeline.LoginRequest.Should().BeNull(); + _mockPipeline.ErrorMessage.Error.ShouldBe("invalid_request"); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldBe("Client must use request object, but no request or request_uri parameter present"); + _mockPipeline.LoginRequest.ShouldBeNull(); } [Fact] @@ -256,21 +257,20 @@ public async Task authorize_should_accept_valid_JWT_request_object_parameters_us }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginRequest.Should().NotBeNull(); - _mockPipeline.LoginRequest.Client.ClientId.Should().Be(_client.ClientId); - _mockPipeline.LoginRequest.DisplayMode.Should().Be("popup"); - _mockPipeline.LoginRequest.UiLocales.Should().Be("ui_locale_value"); - _mockPipeline.LoginRequest.IdP.Should().Be("idp_value"); - _mockPipeline.LoginRequest.Tenant.Should().Be("tenant_value"); - _mockPipeline.LoginRequest.LoginHint.Should().Be("login_hint_value"); - _mockPipeline.LoginRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); - - _mockPipeline.LoginRequest.Parameters.AllKeys.Should().Contain("foo"); - _mockPipeline.LoginRequest.Parameters["foo"].Should().Be("123foo"); - - _mockPipeline.LoginRequest.RequestObjectValues.Count().Should().Be(11); - _mockPipeline.LoginRequest.RequestObjectValues.Single(c => c.Type == "foo" && c.Value == "123foo").Should() - .NotBeNull(); + _mockPipeline.LoginRequest.ShouldNotBeNull(); + _mockPipeline.LoginRequest.Client.ClientId.ShouldBe(_client.ClientId); + _mockPipeline.LoginRequest.DisplayMode.ShouldBe("popup"); + _mockPipeline.LoginRequest.UiLocales.ShouldBe("ui_locale_value"); + _mockPipeline.LoginRequest.IdP.ShouldBe("idp_value"); + _mockPipeline.LoginRequest.Tenant.ShouldBe("tenant_value"); + _mockPipeline.LoginRequest.LoginHint.ShouldBe("login_hint_value"); + _mockPipeline.LoginRequest.AcrValues.ShouldBeEquivalentTo(new string[] { "acr_2", "acr_1" }); + + _mockPipeline.LoginRequest.Parameters.AllKeys.ShouldContain("foo"); + _mockPipeline.LoginRequest.Parameters["foo"].ShouldBe("123foo"); + + _mockPipeline.LoginRequest.RequestObjectValues.Count().ShouldBe(11); + _mockPipeline.LoginRequest.RequestObjectValues.Single(c => c.Type == "foo" && c.Value == "123foo").ShouldNotBeNull(); } [Fact] @@ -304,21 +304,20 @@ public async Task authorize_should_accept_valid_JWT_request_object_parameters_us }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginRequest.Should().NotBeNull(); - _mockPipeline.LoginRequest.Client.ClientId.Should().Be(_client.ClientId); - _mockPipeline.LoginRequest.DisplayMode.Should().Be("popup"); - _mockPipeline.LoginRequest.UiLocales.Should().Be("ui_locale_value"); - _mockPipeline.LoginRequest.IdP.Should().Be("idp_value"); - _mockPipeline.LoginRequest.Tenant.Should().Be("tenant_value"); - _mockPipeline.LoginRequest.LoginHint.Should().Be("login_hint_value"); - _mockPipeline.LoginRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); - - _mockPipeline.LoginRequest.Parameters.AllKeys.Should().Contain("foo"); - _mockPipeline.LoginRequest.Parameters["foo"].Should().Be("123foo"); - - _mockPipeline.LoginRequest.RequestObjectValues.Count().Should().Be(11); - _mockPipeline.LoginRequest.RequestObjectValues.Single(c => c.Type == "foo" && c.Value == "123foo").Should() - .NotBeNull(); + _mockPipeline.LoginRequest.ShouldNotBeNull(); + _mockPipeline.LoginRequest.Client.ClientId.ShouldBe(_client.ClientId); + _mockPipeline.LoginRequest.DisplayMode.ShouldBe("popup"); + _mockPipeline.LoginRequest.UiLocales.ShouldBe("ui_locale_value"); + _mockPipeline.LoginRequest.IdP.ShouldBe("idp_value"); + _mockPipeline.LoginRequest.Tenant.ShouldBe("tenant_value"); + _mockPipeline.LoginRequest.LoginHint.ShouldBe("login_hint_value"); + _mockPipeline.LoginRequest.AcrValues.ShouldBeEquivalentTo(new string[] { "acr_2", "acr_1" }); + + _mockPipeline.LoginRequest.Parameters.AllKeys.ShouldContain("foo"); + _mockPipeline.LoginRequest.Parameters["foo"].ShouldBe("123foo"); + + _mockPipeline.LoginRequest.RequestObjectValues.Count().ShouldBe(11); + _mockPipeline.LoginRequest.RequestObjectValues.Single(c => c.Type == "foo" && c.Value == "123foo").ShouldNotBeNull(); } [Fact] @@ -352,21 +351,20 @@ public async Task authorize_should_accept_valid_JWT_request_object_parameters_us }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginRequest.Should().NotBeNull(); - _mockPipeline.LoginRequest.Client.ClientId.Should().Be(_client.ClientId); - _mockPipeline.LoginRequest.DisplayMode.Should().Be("popup"); - _mockPipeline.LoginRequest.UiLocales.Should().Be("ui_locale_value"); - _mockPipeline.LoginRequest.IdP.Should().Be("idp_value"); - _mockPipeline.LoginRequest.Tenant.Should().Be("tenant_value"); - _mockPipeline.LoginRequest.LoginHint.Should().Be("login_hint_value"); - _mockPipeline.LoginRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); - - _mockPipeline.LoginRequest.Parameters.AllKeys.Should().Contain("foo"); - _mockPipeline.LoginRequest.Parameters["foo"].Should().Be("123foo"); - - _mockPipeline.LoginRequest.RequestObjectValues.Count().Should().Be(11); - _mockPipeline.LoginRequest.RequestObjectValues.Single(c => c.Type == "foo" && c.Value == "123foo").Should() - .NotBeNull(); + _mockPipeline.LoginRequest.ShouldNotBeNull(); + _mockPipeline.LoginRequest.Client.ClientId.ShouldBe(_client.ClientId); + _mockPipeline.LoginRequest.DisplayMode.ShouldBe("popup"); + _mockPipeline.LoginRequest.UiLocales.ShouldBe("ui_locale_value"); + _mockPipeline.LoginRequest.IdP.ShouldBe("idp_value"); + _mockPipeline.LoginRequest.Tenant.ShouldBe("tenant_value"); + _mockPipeline.LoginRequest.LoginHint.ShouldBe("login_hint_value"); + _mockPipeline.LoginRequest.AcrValues.ShouldBeEquivalentTo(new string[] { "acr_2", "acr_1" }); + + _mockPipeline.LoginRequest.Parameters.AllKeys.ShouldContain("foo"); + _mockPipeline.LoginRequest.Parameters["foo"].ShouldBe("123foo"); + + _mockPipeline.LoginRequest.RequestObjectValues.Count().ShouldBe(11); + _mockPipeline.LoginRequest.RequestObjectValues.Single(c => c.Type == "foo" && c.Value == "123foo").ShouldNotBeNull(); } [Fact] @@ -399,28 +397,27 @@ public async Task authorize_should_accept_valid_JWT_request_object_parameters_us { "client_id", _client.ClientId }, { "request", requestJwt } }); - statusCode.Should().Be(HttpStatusCode.Created); + statusCode.ShouldBe(HttpStatusCode.Created); var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, requestUri: parResponse.RootElement.GetProperty("request_uri").GetString()); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginRequest.Should().NotBeNull(); - _mockPipeline.LoginRequest.Client.ClientId.Should().Be(_client.ClientId); - _mockPipeline.LoginRequest.DisplayMode.Should().Be("popup"); - _mockPipeline.LoginRequest.UiLocales.Should().Be("ui_locale_value"); - _mockPipeline.LoginRequest.IdP.Should().Be("idp_value"); - _mockPipeline.LoginRequest.Tenant.Should().Be("tenant_value"); - _mockPipeline.LoginRequest.LoginHint.Should().Be("login_hint_value"); - _mockPipeline.LoginRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); - - _mockPipeline.LoginRequest.Parameters.AllKeys.Should().Contain("foo"); - _mockPipeline.LoginRequest.Parameters["foo"].Should().Be("123foo"); - - _mockPipeline.LoginRequest.RequestObjectValues.Count().Should().Be(11); - _mockPipeline.LoginRequest.RequestObjectValues.Single(c => c.Type == "foo" && c.Value == "123foo").Should() - .NotBeNull(); + _mockPipeline.LoginRequest.ShouldNotBeNull(); + _mockPipeline.LoginRequest.Client.ClientId.ShouldBe(_client.ClientId); + _mockPipeline.LoginRequest.DisplayMode.ShouldBe("popup"); + _mockPipeline.LoginRequest.UiLocales.ShouldBe("ui_locale_value"); + _mockPipeline.LoginRequest.IdP.ShouldBe("idp_value"); + _mockPipeline.LoginRequest.Tenant.ShouldBe("tenant_value"); + _mockPipeline.LoginRequest.LoginHint.ShouldBe("login_hint_value"); + _mockPipeline.LoginRequest.AcrValues.ShouldBeEquivalentTo(new string[] { "acr_2", "acr_1" }); + + _mockPipeline.LoginRequest.Parameters.AllKeys.ShouldContain("foo"); + _mockPipeline.LoginRequest.Parameters["foo"].ShouldBe("123foo"); + + _mockPipeline.LoginRequest.RequestObjectValues.Count().ShouldBe(11); + _mockPipeline.LoginRequest.RequestObjectValues.Single(c => c.Type == "foo" && c.Value == "123foo").ShouldNotBeNull(); } [Theory] @@ -466,25 +463,24 @@ public async Task authorize_should_accept_valid_JWT_request_object_and_allow_som }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginRequest.Should().NotBeNull(); - _mockPipeline.LoginRequest.Client.ClientId.Should().Be(_client.ClientId); - _mockPipeline.LoginRequest.DisplayMode.Should().Be("popup"); - _mockPipeline.LoginRequest.UiLocales.Should().Be("ui_locale_value"); - _mockPipeline.LoginRequest.IdP.Should().Be("idp_value"); - _mockPipeline.LoginRequest.Tenant.Should().Be("tenant_value"); - _mockPipeline.LoginRequest.LoginHint.Should().Be("login_hint_value"); - _mockPipeline.LoginRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); - - _mockPipeline.LoginRequest.Parameters.AllKeys.Should().Contain("foo"); - _mockPipeline.LoginRequest.Parameters["foo"].Should().Be("123foo"); - _mockPipeline.LoginRequest.Parameters["nonce"].Should().Be("nonce"); - _mockPipeline.LoginRequest.Parameters["state"].Should().Be("state"); - - _mockPipeline.LoginRequest.RequestObjectValues.Count().Should().Be(9); - _mockPipeline.LoginRequest.RequestObjectValues.Single(c => c.Type == "foo" && c.Value == "123foo").Should() - .NotBeNull(); - _mockPipeline.LoginRequest.RequestObjectValues.SingleOrDefault(c => c.Type == "state").Should().BeNull(); - _mockPipeline.LoginRequest.RequestObjectValues.SingleOrDefault(c => c.Type == "nonce").Should().BeNull(); + _mockPipeline.LoginRequest.ShouldNotBeNull(); + _mockPipeline.LoginRequest.Client.ClientId.ShouldBe(_client.ClientId); + _mockPipeline.LoginRequest.DisplayMode.ShouldBe("popup"); + _mockPipeline.LoginRequest.UiLocales.ShouldBe("ui_locale_value"); + _mockPipeline.LoginRequest.IdP.ShouldBe("idp_value"); + _mockPipeline.LoginRequest.Tenant.ShouldBe("tenant_value"); + _mockPipeline.LoginRequest.LoginHint.ShouldBe("login_hint_value"); + _mockPipeline.LoginRequest.AcrValues.ShouldBeEquivalentTo(new string[] { "acr_2", "acr_1" }); + + _mockPipeline.LoginRequest.Parameters.AllKeys.ShouldContain("foo"); + _mockPipeline.LoginRequest.Parameters["foo"].ShouldBe("123foo"); + _mockPipeline.LoginRequest.Parameters["nonce"].ShouldBe("nonce"); + _mockPipeline.LoginRequest.Parameters["state"].ShouldBe("state"); + + _mockPipeline.LoginRequest.RequestObjectValues.Count().ShouldBe(9); + _mockPipeline.LoginRequest.RequestObjectValues.Single(c => c.Type == "foo" && c.Value == "123foo").ShouldNotBeNull(); + _mockPipeline.LoginRequest.RequestObjectValues.SingleOrDefault(c => c.Type == "state").ShouldBeNull(); + _mockPipeline.LoginRequest.RequestObjectValues.SingleOrDefault(c => c.Type == "nonce").ShouldBeNull(); } [Fact] @@ -520,21 +516,20 @@ public async Task correct_jwt_typ_should_pass_strict_validation() }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginRequest.Should().NotBeNull(); - _mockPipeline.LoginRequest.Client.ClientId.Should().Be(_client.ClientId); - _mockPipeline.LoginRequest.DisplayMode.Should().Be("popup"); - _mockPipeline.LoginRequest.UiLocales.Should().Be("ui_locale_value"); - _mockPipeline.LoginRequest.IdP.Should().Be("idp_value"); - _mockPipeline.LoginRequest.Tenant.Should().Be("tenant_value"); - _mockPipeline.LoginRequest.LoginHint.Should().Be("login_hint_value"); - _mockPipeline.LoginRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); - - _mockPipeline.LoginRequest.Parameters.AllKeys.Should().Contain("foo"); - _mockPipeline.LoginRequest.Parameters["foo"].Should().Be("123foo"); - - _mockPipeline.LoginRequest.RequestObjectValues.Count().Should().Be(11); - _mockPipeline.LoginRequest.RequestObjectValues.Single(c => c.Type == "foo" && c.Value == "123foo").Should() - .NotBeNull(); + _mockPipeline.LoginRequest.ShouldNotBeNull(); + _mockPipeline.LoginRequest.Client.ClientId.ShouldBe(_client.ClientId); + _mockPipeline.LoginRequest.DisplayMode.ShouldBe("popup"); + _mockPipeline.LoginRequest.UiLocales.ShouldBe("ui_locale_value"); + _mockPipeline.LoginRequest.IdP.ShouldBe("idp_value"); + _mockPipeline.LoginRequest.Tenant.ShouldBe("tenant_value"); + _mockPipeline.LoginRequest.LoginHint.ShouldBe("login_hint_value"); + _mockPipeline.LoginRequest.AcrValues.ShouldBeEquivalentTo(new string[] { "acr_2", "acr_1" }); + + _mockPipeline.LoginRequest.Parameters.AllKeys.ShouldContain("foo"); + _mockPipeline.LoginRequest.Parameters["foo"].ShouldBe("123foo"); + + _mockPipeline.LoginRequest.RequestObjectValues.Count().ShouldBe(11); + _mockPipeline.LoginRequest.RequestObjectValues.Single(c => c.Type == "foo" && c.Value == "123foo").ShouldNotBeNull(); } [Fact] @@ -570,8 +565,8 @@ public async Task missing_jwt_typ_should_error() }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request_object"); - _mockPipeline.LoginRequest.Should().BeNull(); + _mockPipeline.ErrorMessage.Error.ShouldBe("invalid_request_object"); + _mockPipeline.LoginRequest.ShouldBeNull(); } [Fact] @@ -613,24 +608,24 @@ public async Task authorize_should_accept_complex_objects_in_request_object() }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginRequest.Should().NotBeNull(); + _mockPipeline.LoginRequest.ShouldNotBeNull(); - _mockPipeline.LoginRequest.Parameters["someObj"].Should().NotBeNull(); + _mockPipeline.LoginRequest.Parameters["someObj"].ShouldNotBeNull(); var value = _mockPipeline.LoginRequest.Parameters["someObj"]; var someObj2 = JsonSerializer.Deserialize(value, someObj.GetType()); - someObj.Should().BeEquivalentTo(someObj2); + someObj.ShouldBeEquivalentTo(someObj2); - _mockPipeline.LoginRequest.Parameters["someArr"].Should().NotBeNull(); + _mockPipeline.LoginRequest.Parameters["someArr"].ShouldNotBeNull(); var arrValue = _mockPipeline.LoginRequest.Parameters.GetValues("someArr"); - arrValue.Length.Should().Be(3); + arrValue.Length.ShouldBe(3); - _mockPipeline.LoginRequest.RequestObjectValues.Count().Should().Be(15); + _mockPipeline.LoginRequest.RequestObjectValues.Count().ShouldBe(15); value = _mockPipeline.LoginRequest.RequestObjectValues.Single(c => c.Type == "someObj").Value; someObj2 = JsonSerializer.Deserialize(value, someObj.GetType()); - someObj.Should().BeEquivalentTo(someObj2); + someObj.ShouldBeEquivalentTo(someObj2); var arrValue2 = _mockPipeline.LoginRequest.RequestObjectValues.Where(c => c.Type == "someArr").ToList(); - arrValue2.Count.Should().Be(3); + arrValue2.Count.ShouldBe(3); } [Fact] @@ -662,9 +657,9 @@ public async Task authorize_should_reject_jwt_request_without_client_id() }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request"); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Be("Invalid client_id"); - _mockPipeline.LoginRequest.Should().BeNull(); + _mockPipeline.ErrorMessage.Error.ShouldBe("invalid_request"); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldBe("Invalid client_id"); + _mockPipeline.LoginRequest.ShouldBeNull(); } [Fact] @@ -697,9 +692,9 @@ public async Task authorize_should_reject_jwt_request_without_client_id_in_jwt() }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request_object"); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Be("Invalid JWT request"); - _mockPipeline.LoginRequest.Should().BeNull(); + _mockPipeline.ErrorMessage.Error.ShouldBe("invalid_request_object"); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldBe("Invalid JWT request"); + _mockPipeline.LoginRequest.ShouldBeNull(); } [Fact] @@ -734,9 +729,9 @@ public async Task authorize_should_reject_jwt_request_if_audience_is_incorrect() var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request_object"); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Be("Invalid JWT request"); - _mockPipeline.LoginRequest.Should().BeNull(); + _mockPipeline.ErrorMessage.Error.ShouldBe("invalid_request_object"); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldBe("Invalid JWT request"); + _mockPipeline.LoginRequest.ShouldBeNull(); } [Fact] @@ -771,9 +766,9 @@ public async Task authorize_should_reject_jwt_request_if_issuer_does_not_match_c var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request_object"); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Be("Invalid JWT request"); - _mockPipeline.LoginRequest.Should().BeNull(); + _mockPipeline.ErrorMessage.Error.ShouldBe("invalid_request_object"); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldBe("Invalid JWT request"); + _mockPipeline.LoginRequest.ShouldBeNull(); } [Fact] @@ -808,9 +803,9 @@ public async Task authorize_should_reject_jwt_request_that_includes_request_para var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request_object"); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Be("Invalid JWT request"); - _mockPipeline.LoginRequest.Should().BeNull(); + _mockPipeline.ErrorMessage.Error.ShouldBe("invalid_request_object"); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldBe("Invalid JWT request"); + _mockPipeline.LoginRequest.ShouldBeNull(); } [Fact] @@ -845,9 +840,9 @@ public async Task authorize_should_reject_jwt_request_that_includes_request_uri_ var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request_object"); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Be("Invalid JWT request"); - _mockPipeline.LoginRequest.Should().BeNull(); + _mockPipeline.ErrorMessage.Error.ShouldBe("invalid_request_object"); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldBe("Invalid JWT request"); + _mockPipeline.LoginRequest.ShouldBeNull(); } [Fact] @@ -881,9 +876,9 @@ public async Task authorize_should_reject_jwt_request_if_response_type_does_not_ var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request"); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Be("Invalid JWT request"); - _mockPipeline.LoginRequest.Should().BeNull(); + _mockPipeline.ErrorMessage.Error.ShouldBe("invalid_request"); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldBe("Invalid JWT request"); + _mockPipeline.LoginRequest.ShouldBeNull(); } [Fact] @@ -918,9 +913,9 @@ public async Task authorize_should_reject_jwt_request_if_client_id_does_not_matc var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request"); - _mockPipeline.ErrorMessage.ErrorDescription.Should().Be("Invalid JWT request"); - _mockPipeline.LoginRequest.Should().BeNull(); + _mockPipeline.ErrorMessage.Error.ShouldBe("invalid_request"); + _mockPipeline.ErrorMessage.ErrorDescription.ShouldBe("Invalid JWT request"); + _mockPipeline.LoginRequest.ShouldBeNull(); } [Fact] @@ -948,7 +943,7 @@ public async Task authorize_should_ignore_request_uri_when_feature_is_disabled() }); _mockPipeline.JwtRequestMessageHandler.OnInvoke = req => { - req.RequestUri.Should().Be(new Uri("http://client_jwt")); + req.RequestUri.ShouldBe(new Uri("http://client_jwt")); return Task.CompletedTask; }; _mockPipeline.JwtRequestMessageHandler.Response.Content = new StringContent(requestJwt); @@ -962,9 +957,9 @@ public async Task authorize_should_ignore_request_uri_when_feature_is_disabled() request_uri = "http://client_jwt" }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); - _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.Should().BeFalse(); + _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.ShouldBeFalse(); } [Fact] @@ -994,7 +989,7 @@ public async Task authorize_should_accept_request_uri_with_valid_jwt() }); _mockPipeline.JwtRequestMessageHandler.OnInvoke = req => { - req.RequestUri.Should().Be(new Uri("http://client_jwt")); + req.RequestUri.ShouldBe(new Uri("http://client_jwt")); return Task.CompletedTask; }; _mockPipeline.JwtRequestMessageHandler.Response.Content = new StringContent(requestJwt); @@ -1009,19 +1004,19 @@ public async Task authorize_should_accept_request_uri_with_valid_jwt() }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginRequest.Should().NotBeNull(); - _mockPipeline.LoginRequest.Client.ClientId.Should().Be(_client.ClientId); - _mockPipeline.LoginRequest.DisplayMode.Should().Be("popup"); - _mockPipeline.LoginRequest.UiLocales.Should().Be("ui_locale_value"); - _mockPipeline.LoginRequest.IdP.Should().Be("idp_value"); - _mockPipeline.LoginRequest.Tenant.Should().Be("tenant_value"); - _mockPipeline.LoginRequest.LoginHint.Should().Be("login_hint_value"); - _mockPipeline.LoginRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); - _mockPipeline.LoginRequest.Parameters.AllKeys.Should().Contain("foo"); - _mockPipeline.LoginRequest.Parameters["foo"].Should().Be("123foo"); - _mockPipeline.LoginRequest.RequestObjectValues.Count().Should().Be(13); - - _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.Should().BeTrue(); + _mockPipeline.LoginRequest.ShouldNotBeNull(); + _mockPipeline.LoginRequest.Client.ClientId.ShouldBe(_client.ClientId); + _mockPipeline.LoginRequest.DisplayMode.ShouldBe("popup"); + _mockPipeline.LoginRequest.UiLocales.ShouldBe("ui_locale_value"); + _mockPipeline.LoginRequest.IdP.ShouldBe("idp_value"); + _mockPipeline.LoginRequest.Tenant.ShouldBe("tenant_value"); + _mockPipeline.LoginRequest.LoginHint.ShouldBe("login_hint_value"); + _mockPipeline.LoginRequest.AcrValues.ShouldBeEquivalentTo(new string[] { "acr_2", "acr_1" }); + _mockPipeline.LoginRequest.Parameters.AllKeys.ShouldContain("foo"); + _mockPipeline.LoginRequest.Parameters["foo"].ShouldBe("123foo"); + _mockPipeline.LoginRequest.RequestObjectValues.Count().ShouldBe(13); + + _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.ShouldBeTrue(); } [Theory] @@ -1061,7 +1056,7 @@ public async Task authorize_should_accept_request_uri_and_allow_some_parameters_ }); _mockPipeline.JwtRequestMessageHandler.OnInvoke = req => { - req.RequestUri.Should().Be(new Uri("http://client_jwt")); + req.RequestUri.ShouldBe(new Uri("http://client_jwt")); return Task.CompletedTask; }; _mockPipeline.JwtRequestMessageHandler.Response.Content = new StringContent(requestJwt); @@ -1078,23 +1073,23 @@ public async Task authorize_should_accept_request_uri_and_allow_some_parameters_ }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginRequest.Should().NotBeNull(); - _mockPipeline.LoginRequest.Client.ClientId.Should().Be(_client.ClientId); - _mockPipeline.LoginRequest.DisplayMode.Should().Be("popup"); - _mockPipeline.LoginRequest.UiLocales.Should().Be("ui_locale_value"); - _mockPipeline.LoginRequest.IdP.Should().Be("idp_value"); - _mockPipeline.LoginRequest.Tenant.Should().Be("tenant_value"); - _mockPipeline.LoginRequest.LoginHint.Should().Be("login_hint_value"); - _mockPipeline.LoginRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); - _mockPipeline.LoginRequest.Parameters.AllKeys.Should().Contain("foo"); - _mockPipeline.LoginRequest.Parameters["foo"].Should().Be("123foo"); - _mockPipeline.LoginRequest.Parameters["nonce"].Should().Be("nonce"); - _mockPipeline.LoginRequest.Parameters["state"].Should().Be("state"); - _mockPipeline.LoginRequest.RequestObjectValues.Count().Should().Be(11); - _mockPipeline.LoginRequest.RequestObjectValues.Any(x => x.Type == "state").Should().BeFalse(); - _mockPipeline.LoginRequest.RequestObjectValues.Any(x => x.Type == "nonce").Should().BeFalse(); - - _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.Should().BeTrue(); + _mockPipeline.LoginRequest.ShouldNotBeNull(); + _mockPipeline.LoginRequest.Client.ClientId.ShouldBe(_client.ClientId); + _mockPipeline.LoginRequest.DisplayMode.ShouldBe("popup"); + _mockPipeline.LoginRequest.UiLocales.ShouldBe("ui_locale_value"); + _mockPipeline.LoginRequest.IdP.ShouldBe("idp_value"); + _mockPipeline.LoginRequest.Tenant.ShouldBe("tenant_value"); + _mockPipeline.LoginRequest.LoginHint.ShouldBe("login_hint_value"); + _mockPipeline.LoginRequest.AcrValues.ShouldBeEquivalentTo(new string[] { "acr_2", "acr_1" }); + _mockPipeline.LoginRequest.Parameters.AllKeys.ShouldContain("foo"); + _mockPipeline.LoginRequest.Parameters["foo"].ShouldBe("123foo"); + _mockPipeline.LoginRequest.Parameters["nonce"].ShouldBe("nonce"); + _mockPipeline.LoginRequest.Parameters["state"].ShouldBe("state"); + _mockPipeline.LoginRequest.RequestObjectValues.Count().ShouldBe(11); + _mockPipeline.LoginRequest.RequestObjectValues.Any(x => x.Type == "state").ShouldBeFalse(); + _mockPipeline.LoginRequest.RequestObjectValues.Any(x => x.Type == "nonce").ShouldBeFalse(); + + _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.ShouldBeTrue(); } [Fact] @@ -1123,7 +1118,7 @@ public async Task authorize_should_accept_request_uri_with_valid_jwt_and_strict_ }, setJwtTyp: true); _mockPipeline.JwtRequestMessageHandler.OnInvoke = req => { - req.RequestUri.Should().Be(new Uri("http://client_jwt")); + req.RequestUri.ShouldBe(new Uri("http://client_jwt")); return Task.CompletedTask; }; _mockPipeline.JwtRequestMessageHandler.Response.Content = new StringContent(requestJwt); @@ -1139,18 +1134,18 @@ public async Task authorize_should_accept_request_uri_with_valid_jwt_and_strict_ }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginRequest.Should().NotBeNull(); - _mockPipeline.LoginRequest.Client.ClientId.Should().Be(_client.ClientId); - _mockPipeline.LoginRequest.DisplayMode.Should().Be("popup"); - _mockPipeline.LoginRequest.UiLocales.Should().Be("ui_locale_value"); - _mockPipeline.LoginRequest.IdP.Should().Be("idp_value"); - _mockPipeline.LoginRequest.Tenant.Should().Be("tenant_value"); - _mockPipeline.LoginRequest.LoginHint.Should().Be("login_hint_value"); - _mockPipeline.LoginRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); - _mockPipeline.LoginRequest.Parameters.AllKeys.Should().Contain("foo"); - _mockPipeline.LoginRequest.Parameters["foo"].Should().Be("123foo"); - - _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.Should().BeTrue(); + _mockPipeline.LoginRequest.ShouldNotBeNull(); + _mockPipeline.LoginRequest.Client.ClientId.ShouldBe(_client.ClientId); + _mockPipeline.LoginRequest.DisplayMode.ShouldBe("popup"); + _mockPipeline.LoginRequest.UiLocales.ShouldBe("ui_locale_value"); + _mockPipeline.LoginRequest.IdP.ShouldBe("idp_value"); + _mockPipeline.LoginRequest.Tenant.ShouldBe("tenant_value"); + _mockPipeline.LoginRequest.LoginHint.ShouldBe("login_hint_value"); + _mockPipeline.LoginRequest.AcrValues.ShouldBeEquivalentTo(new string[] { "acr_2", "acr_1" }); + _mockPipeline.LoginRequest.Parameters.AllKeys.ShouldContain("foo"); + _mockPipeline.LoginRequest.Parameters["foo"].ShouldBe("123foo"); + + _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.ShouldBeTrue(); } [Fact] @@ -1179,7 +1174,7 @@ public async Task authorize_should_reject_request_uri_with_valid_jwt_and_strict_ }, setJwtTyp: true); _mockPipeline.JwtRequestMessageHandler.OnInvoke = req => { - req.RequestUri.Should().Be(new Uri("http://client_jwt")); + req.RequestUri.ShouldBe(new Uri("http://client_jwt")); return Task.CompletedTask; }; _mockPipeline.JwtRequestMessageHandler.Response.Content = new StringContent(requestJwt); @@ -1194,9 +1189,9 @@ public async Task authorize_should_reject_request_uri_with_valid_jwt_and_strict_ }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request_uri"); - _mockPipeline.LoginRequest.Should().BeNull(); - _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.Should().BeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe("invalid_request_uri"); + _mockPipeline.LoginRequest.ShouldBeNull(); + _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.ShouldBeTrue(); } [Fact] @@ -1216,10 +1211,10 @@ public async Task request_uri_response_returns_500_should_fail() }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.LoginRequest.Should().BeNull(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.LoginRequest.ShouldBeNull(); - _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.Should().BeTrue(); + _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.ShouldBeTrue(); } [Fact] @@ -1239,10 +1234,10 @@ public async Task request_uri_response_returns_404_should_fail() }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.LoginRequest.Should().BeNull(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.LoginRequest.ShouldBeNull(); - _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.Should().BeTrue(); + _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.ShouldBeTrue(); } [Fact] @@ -1259,10 +1254,10 @@ public async Task request_uri_length_too_long_should_fail() request_uri = "http://" + new string('x', 512) }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.LoginRequest.Should().BeNull(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.LoginRequest.ShouldBeNull(); - _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.Should().BeFalse(); + _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.ShouldBeFalse(); } [Fact] @@ -1300,10 +1295,10 @@ public async Task both_request_and_request_uri_params_should_fail() request_uri = "http://client_jwt" }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.LoginRequest.Should().BeNull(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.LoginRequest.ShouldBeNull(); - _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.Should().BeFalse(); + _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.ShouldBeFalse(); } [Theory] @@ -1350,12 +1345,12 @@ public async Task prompt_login_should_allow_user_to_login_and_complete_authoriza // this simulates the login page returning to the returnUrl which is the authorize callback page _mockPipeline.BrowserClient.AllowAutoRedirect = false; response = await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.BaseUrl + _mockPipeline.LoginReturnUrl); - response.Should().Be302Found(); - response.Headers.Location.ToString() - .Should().StartWith("https://client/callback") - .And.Contain("id_token=") - .And.Contain("state=state123"); + response.StatusCode.ShouldBe(HttpStatusCode.Found); + response.Headers.Location!.ToString().ShouldSatisfyAllConditions( + l => l.ShouldStartWith("https://client/callback"), + l => l.ShouldContain("id_token="), + l => l.ShouldContain("state=state123")); } [Theory] @@ -1408,9 +1403,9 @@ public async Task prompt_login_should_allow_user_to_consent_and_complete_authori var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client/callback"); - response.Headers.Location.ToString().Should().Contain("id_token="); - response.Headers.Location.ToString().Should().Contain("state=state123"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client/callback"); + response.Headers.Location.ToString().ShouldContain("id_token="); + response.Headers.Location.ToString().ShouldContain("state=state123"); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/PushedAuthorizationTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/PushedAuthorizationTests.cs index c4bc4bc04..98d5f6020 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/PushedAuthorizationTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/PushedAuthorizationTests.cs @@ -4,7 +4,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using IntegrationTests.Common; using System; @@ -48,7 +48,7 @@ public async Task happy_path() redirectUri: expectedCallback, state: expectedState ); - statusCode.Should().Be(HttpStatusCode.Created); + statusCode.ShouldBe(HttpStatusCode.Created); // Authorize using pushed request var authorizeUrl = _mockPipeline.CreateAuthorizeUrl( @@ -56,13 +56,13 @@ public async Task happy_path() requestUri: parJson.RootElement.GetProperty("request_uri").GetString()); var response = await _mockPipeline.BrowserClient.GetAsync(authorizeUrl); - response.Should().Be302Found(); - response.Should().HaveHeader("Location").And.Match($"{expectedCallback}*"); + response.StatusCode.ShouldBe(HttpStatusCode.Found); + response.Headers.Location!.AbsoluteUri.ShouldBe($"{expectedCallback}*"); var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); - authorization.IdentityToken.Should().NotBeNull(); - authorization.State.Should().Be(expectedState); + authorization.IsError.ShouldBeFalse(); + authorization.IdentityToken.ShouldNotBeNull(); + authorization.State.ShouldBe(expectedState); } [Fact] @@ -71,7 +71,7 @@ public async Task using_pushed_authorization_when_it_is_globally_disabled_fails( _mockPipeline.Options.Endpoints.EnablePushedAuthorizationEndpoint = false; var (_, statusCode) = await _mockPipeline.PushAuthorizationRequestAsync(); - statusCode.Should().Be(HttpStatusCode.NotFound); + statusCode.ShouldBe(HttpStatusCode.NotFound); } [Fact] @@ -90,15 +90,15 @@ public async Task not_using_pushed_authorization_when_it_is_globally_required_fa // We expect to be redirected to the error page, as this is an interactive // call to authorize - response.Should().Be302Found(); - response.Should().HaveHeader("Location").And.Match("*/error*"); + response.StatusCode.ShouldBe(HttpStatusCode.Found); + response.Headers.Location!.ToString().ShouldMatch("*/error*"); } [Fact] public async Task not_using_pushed_authorization_when_it_is_required_for_client_fails() { - _mockPipeline.Options.Endpoints.EnablePushedAuthorizationEndpoint.Should().BeTrue(); - _mockPipeline.Options.PushedAuthorization.Required.Should().BeFalse(); + _mockPipeline.Options.Endpoints.EnablePushedAuthorizationEndpoint.ShouldBeTrue(); + _mockPipeline.Options.PushedAuthorization.Required.ShouldBeFalse(); _client.RequirePushedAuthorization = true; var url = _mockPipeline.CreateAuthorizeUrl( @@ -112,8 +112,8 @@ public async Task not_using_pushed_authorization_when_it_is_required_for_client_ // We expect to be redirected to the error page, as this is an interactive // call to authorize - response.Should().Be302Found(); - response.Should().HaveHeader("Location").And.Match("*/error*"); + response.StatusCode.ShouldBe(HttpStatusCode.Found); + response.Headers.Location!.ToString().ShouldMatch("*/error*"); } [Fact] @@ -121,8 +121,8 @@ public async Task existing_pushed_authorization_request_uris_become_invalid_when { // PAR is enabled when we push authorization... var (parJson, statusCode) = await _mockPipeline.PushAuthorizationRequestAsync(); - statusCode.Should().Be(HttpStatusCode.Created); - parJson.Should().NotBeNull(); + statusCode.ShouldBe(HttpStatusCode.Created); + parJson.ShouldNotBeNull(); // ... But then is later disabled, and then we try to use the pushed request _mockPipeline.Options.Endpoints.EnablePushedAuthorizationEndpoint = false; @@ -138,8 +138,8 @@ public async Task existing_pushed_authorization_request_uris_become_invalid_when _mockPipeline.BrowserClient.AllowAutoRedirect = false; var authorizeResponse = await _mockPipeline.BrowserClient.GetAsync(authorizeUrl); - authorizeResponse.Should().Be302Found(); - authorizeResponse.Should().HaveHeader("Location").And.Match("*/error*"); + authorizeResponse.StatusCode.ShouldBe(HttpStatusCode.Found); + authorizeResponse.Headers.Location!.ToString().ShouldMatch("*/error*"); } [Fact] @@ -149,8 +149,8 @@ public async Task reusing_pushed_authorization_request_uris_fails() await _mockPipeline.LoginAsync("bob"); var (parJson, statusCode) = await _mockPipeline.PushAuthorizationRequestAsync(); - statusCode.Should().Be(HttpStatusCode.Created); - parJson.Should().NotBeNull(); + statusCode.ShouldBe(HttpStatusCode.Created); + parJson.ShouldNotBeNull(); // Authorize using pushed request var authorizeUrl = _mockPipeline.CreateAuthorizeUrl( @@ -161,8 +161,8 @@ public async Task reusing_pushed_authorization_request_uris_fails() var firstAuthorizeResponse = await _mockPipeline.BrowserClient.GetAsync(authorizeUrl); var secondAuthorizeResponse = await _mockPipeline.BrowserClient.GetAsync(authorizeUrl); - secondAuthorizeResponse.Should().Be302Found(); - secondAuthorizeResponse.Should().HaveHeader("Location").And.Match("*/error*"); + secondAuthorizeResponse.StatusCode.ShouldBe(HttpStatusCode.Found); + secondAuthorizeResponse.Headers.Location!.ToString().ShouldMatch("*/error*"); } [Theory] @@ -176,10 +176,10 @@ public async Task pushed_authorization_with_a_request_uri_fails(string requestUr { { "request_uri", requestUri } }); - statusCode.Should().Be(HttpStatusCode.BadRequest); - parJson.Should().NotBeNull(); + statusCode.ShouldBe(HttpStatusCode.BadRequest); + parJson.ShouldNotBeNull(); parJson.RootElement.GetProperty("error").GetString() - .Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + .ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } @@ -207,7 +207,7 @@ public async Task prompt_login_can_be_used_with_pushed_authorization(string para { parameterName, parameterValue } } ); - statusCode.Should().Be(HttpStatusCode.Created); + statusCode.ShouldBe(HttpStatusCode.Created); // Authorize using pushed request var authorizeUrl = _mockPipeline.CreateAuthorizeUrl( @@ -216,14 +216,14 @@ public async Task prompt_login_can_be_used_with_pushed_authorization(string para var authorizeResponse = await _mockPipeline.BrowserClient.GetAsync(authorizeUrl); // Verify that authorize redirects to login - authorizeResponse.Should().Be302Found(); + authorizeResponse.StatusCode.ShouldBe(HttpStatusCode.Found); var isPromptCreate = parameterName == "prompt" && parameterValue == "create"; var expectedLocation = isPromptCreate ? IdentityServerPipeline.CreateAccountPage : IdentityServerPipeline.LoginPage; - authorizeResponse.Headers.Location.ToString().ToLower().Should().Match($"{expectedLocation.ToLower()}*"); + authorizeResponse.Headers.Location.ToString().ToLower().ShouldMatch($"{expectedLocation.ToLower()}*"); // Verify that the UI prompts the user at this point var uiResponse = await _mockPipeline.BrowserClient.GetAsync(authorizeResponse.Headers.Location); - uiResponse.Should().Be200Ok(); + uiResponse.StatusCode.ShouldBe(HttpStatusCode.OK); // Now login and return to the return url we were given var returnPath = isPromptCreate ? _mockPipeline.CreateAccountReturnUrl : _mockPipeline.LoginReturnUrl; @@ -232,8 +232,8 @@ public async Task prompt_login_can_be_used_with_pushed_authorization(string para var authorizeCallbackResponse = await _mockPipeline.BrowserClient.GetAsync(returnUrl); // The authorize callback should continue back to the application (the prompt parameter is processed so we don't go back to the UI) - authorizeCallbackResponse.Should().Be302Found(); - authorizeCallbackResponse.Headers.Location.Should().Be(expectedCallback); + authorizeCallbackResponse.StatusCode.ShouldBe(HttpStatusCode.Found); + authorizeCallbackResponse.Headers.Location!.ToString().ShouldBe(expectedCallback); } private void ConfigureScopesAndResources() diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/ResourceTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/ResourceTests.cs index f2cba0612..21e7702c1 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/ResourceTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/ResourceTests.cs @@ -12,7 +12,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Models; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel.Client; using IntegrationTests.Common; using Xunit; @@ -118,7 +118,7 @@ public ResourceTests() ////////////////////////////////////////////////////////////////// private IEnumerable ParseAccessTokenClaims(TokenResponse tokenResponse) { - tokenResponse.IsError.Should().BeFalse(); + tokenResponse.IsError.ShouldBeFalse(); var handler = new JwtSecurityTokenHandler(); var token = handler.ReadJwtToken(tokenResponse.AccessToken); @@ -126,7 +126,7 @@ private IEnumerable ParseAccessTokenClaims(TokenResponse tokenResponse) } private string GetCode(HttpResponseMessage response) { - response.StatusCode.Should().Be(HttpStatusCode.Redirect); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); var url = response.Headers.Location.ToString(); var idx = url.IndexOf("code=", StringComparison.Ordinal); idx.Should().BeGreaterThan(-1); @@ -172,8 +172,8 @@ public async Task no_resource_indicator_on_code_exchange_should_succeed() { var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:resource1", "urn:resource2" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "openid", "profile", "scope1", "scope2", "scope3", "scope4", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:resource1", "urn:resource2" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "openid", "profile", "scope1", "scope2", "scope3", "scope4", "offline_access" }); } } @@ -211,8 +211,8 @@ public async Task empty_resource_indicator_on_authz_endpoint_should_succeed() { var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:resource1", "urn:resource2" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "openid", "profile", "scope1", "scope2", "scope3", "scope4", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:resource1", "urn:resource2" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "openid", "profile", "scope1", "scope2", "scope3", "scope4", "offline_access" }); } } @@ -251,8 +251,8 @@ public async Task empty_resource_indicator_on_code_exchange_should_succeed() { var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:resource1", "urn:resource2" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "openid", "profile", "scope1", "scope2", "scope3", "scope4", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:resource1", "urn:resource2" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "openid", "profile", "scope1", "scope2", "scope3", "scope4", "offline_access" }); } } @@ -291,8 +291,8 @@ public async Task resource_indicator_on_code_exchange_should_succeed() { var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:resource1" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "scope2", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:resource1" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "scope2", "offline_access" }); } } @@ -339,8 +339,8 @@ public async Task resource_indicator_on_refresh_token_exchange_should_succeed() { var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:resource1" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "scope2", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:resource1" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "scope2", "offline_access" }); } } @@ -383,8 +383,8 @@ public async Task no_resource_indicator_on_refresh_token_exchange_should_succeed { var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:resource1", "urn:resource2" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "openid", "profile", "scope1", "scope2", "scope3", "scope4", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:resource1", "urn:resource2" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "openid", "profile", "scope1", "scope2", "scope3", "scope4", "offline_access" }); } } @@ -422,8 +422,8 @@ public async Task resource_indicator_without_offline_access_should_succeed() { var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:resource1" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "scope2" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:resource1" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "scope2" }); } } @@ -461,8 +461,8 @@ public async Task resource_indicator_without_offline_access_no_resource_on_code_ { var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:resource1", "urn:resource2" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "scope2", "scope3" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:resource1", "urn:resource2" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "scope2", "scope3" }); } } @@ -500,8 +500,8 @@ public async Task resource_indicator_for_isolated_resource_with_offline_access_s { var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:resource1" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "scope3", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:resource1" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "scope3", "offline_access" }); } tokenResponse = await _mockPipeline.BackChannelClient.RequestRefreshTokenAsync(new RefreshTokenRequest @@ -518,8 +518,8 @@ public async Task resource_indicator_for_isolated_resource_with_offline_access_s { var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:resource3" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope3", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:resource3" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope3", "offline_access" }); } } @@ -557,8 +557,8 @@ public async Task resource_indicator_for_isolated_resource_without_offline_acces { var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:resource3" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope3" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:resource3" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope3" }); } } @@ -579,7 +579,7 @@ public async Task implicit_flow_with_resource_indicator_should_fail() url += "&resource=urn:resource3"; await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); - _mockPipeline.ErrorMessage.Error.Should().Be("invalid_target"); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); + _mockPipeline.ErrorMessage.Error.ShouldBe("invalid_target"); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/RestrictAccessTokenViaBrowserTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/RestrictAccessTokenViaBrowserTests.cs index a05fa33e8..648033e0c 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/RestrictAccessTokenViaBrowserTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/RestrictAccessTokenViaBrowserTests.cs @@ -9,7 +9,7 @@ using Duende.IdentityServer; using Duende.IdentityServer.Models; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using IntegrationTests.Common; using Xunit; @@ -99,11 +99,11 @@ public async Task Unrestricted_implicit_client_can_request_IdToken() _mockPipeline.BrowserClient.AllowAutoRedirect = false; var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Found); - response.Headers.Location.AbsoluteUri.Should().StartWith("https://client1/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Found); + response.Headers.Location.AbsoluteUri.ShouldStartWith("https://client1/callback"); var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IdentityToken.Should().NotBeNull(); - authorization.AccessToken.Should().BeNull(); + authorization.IdentityToken.ShouldNotBeNull(); + authorization.AccessToken.ShouldBeNull(); } [Fact] @@ -118,11 +118,11 @@ public async Task Unrestricted_implicit_client_can_request_IdTokenToken() _mockPipeline.BrowserClient.AllowAutoRedirect = false; var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Found); - response.Headers.Location.AbsoluteUri.Should().StartWith("https://client1/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Found); + response.Headers.Location.AbsoluteUri.ShouldStartWith("https://client1/callback"); var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IdentityToken.Should().NotBeNull(); - authorization.AccessToken.Should().NotBeNull(); + authorization.IdentityToken.ShouldNotBeNull(); + authorization.AccessToken.ShouldNotBeNull(); } [Fact] @@ -137,11 +137,11 @@ public async Task Restricted_implicit_client_can_request_IdToken() _mockPipeline.BrowserClient.AllowAutoRedirect = false; var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Found); - response.Headers.Location.AbsoluteUri.Should().StartWith("https://client2/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Found); + response.Headers.Location.AbsoluteUri.ShouldStartWith("https://client2/callback"); var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IdentityToken.Should().NotBeNull(); - authorization.AccessToken.Should().BeNull(); + authorization.IdentityToken.ShouldNotBeNull(); + authorization.AccessToken.ShouldBeNull(); } [Fact] @@ -155,7 +155,7 @@ public async Task Restricted_implicit_client_cannot_request_IdTokenToken() _mockPipeline.BrowserClient.AllowAutoRedirect = true; var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); } [Fact] @@ -170,12 +170,12 @@ public async Task Unrestricted_hybrid_client_can_request_CodeIdToken() _mockPipeline.BrowserClient.AllowAutoRedirect = false; var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Found); - response.Headers.Location.AbsoluteUri.Should().StartWith("https://client3/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Found); + response.Headers.Location.AbsoluteUri.ShouldStartWith("https://client3/callback"); var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IdentityToken.Should().NotBeNull(); - authorization.AccessToken.Should().BeNull(); - authorization.Code.Should().NotBeNull(); + authorization.IdentityToken.ShouldNotBeNull(); + authorization.AccessToken.ShouldBeNull(); + authorization.Code.ShouldNotBeNull(); } [Fact] @@ -190,12 +190,12 @@ public async Task Unrestricted_hybrid_client_can_request_CodeIdTokenToken() _mockPipeline.BrowserClient.AllowAutoRedirect = false; var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Found); - response.Headers.Location.AbsoluteUri.Should().StartWith("https://client3/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Found); + response.Headers.Location.AbsoluteUri.ShouldStartWith("https://client3/callback"); var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IdentityToken.Should().NotBeNull(); - authorization.AccessToken.Should().NotBeNull(); - authorization.Code.Should().NotBeNull(); + authorization.IdentityToken.ShouldNotBeNull(); + authorization.AccessToken.ShouldNotBeNull(); + authorization.Code.ShouldNotBeNull(); } @@ -211,12 +211,12 @@ public async Task Restricted_hybrid_client_can_request_CodeIdToken() _mockPipeline.BrowserClient.AllowAutoRedirect = false; var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Found); - response.Headers.Location.AbsoluteUri.Should().StartWith("https://client4/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Found); + response.Headers.Location.AbsoluteUri.ShouldStartWith("https://client4/callback"); var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IdentityToken.Should().NotBeNull(); - authorization.AccessToken.Should().BeNull(); - authorization.Code.Should().NotBeNull(); + authorization.IdentityToken.ShouldNotBeNull(); + authorization.AccessToken.ShouldBeNull(); + authorization.Code.ShouldNotBeNull(); } [Fact] @@ -230,6 +230,6 @@ public async Task Restricted_hybrid_client_cannot_request_CodeIdTokenToken() _mockPipeline.BrowserClient.AllowAutoRedirect = true; var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/SessionIdTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/SessionIdTests.cs index 208976616..81afa9cf0 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/SessionIdTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/SessionIdTests.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Models; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using IntegrationTests.Common; using Xunit; @@ -84,13 +84,13 @@ public async Task session_id_should_be_reissued_if_session_cookie_absent() { await _mockPipeline.LoginAsync("bob"); var sid1 = _mockPipeline.GetSessionCookie().Value; - sid1.Should().NotBeNull(); + sid1.ShouldNotBeNull(); _mockPipeline.RemoveSessionCookie(); await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.DiscoveryEndpoint); var sid2 = _mockPipeline.GetSessionCookie().Value; - sid2.Should().Be(sid1); + sid2.ShouldBe(sid1); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/CheckSession/CheckSessionTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/CheckSession/CheckSessionTests.cs index 821ff08d8..0da21081e 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/CheckSession/CheckSessionTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/CheckSession/CheckSessionTests.cs @@ -4,7 +4,7 @@ using System.Net; using System.Threading.Tasks; -using FluentAssertions; +using Shouldly; using IntegrationTests.Common; using Xunit; @@ -27,6 +27,6 @@ public async Task get_request_should_not_return_404() { var response = await _mockPipeline.BackChannelClient.GetAsync(IdentityServerPipeline.CheckSessionEndpoint); - response.StatusCode.Should().NotBe(HttpStatusCode.NotFound); + response.StatusCode.ShouldNotBe(HttpStatusCode.NotFound); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Ciba/CibaTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Ciba/CibaTests.cs index fab9b88e0..04be48cfb 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Ciba/CibaTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Ciba/CibaTests.cs @@ -5,7 +5,7 @@ using Duende.IdentityServer; using Duende.IdentityServer.Models; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using IntegrationTests.Common; using System; using System.Collections.Generic; @@ -167,7 +167,7 @@ public async Task get_request_should_return_error() { var response = await _mockPipeline.BackChannelClient.GetAsync(IdentityServerPipeline.BackchannelAuthenticationEndpoint); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); } [Fact] @@ -178,7 +178,7 @@ public async Task post_request_without_form_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new StringContent("invalid")); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); } [Fact] @@ -202,12 +202,12 @@ public async Task request_values_should_be_passed_to_user_validator() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); - _mockCibaUserValidator.UserValidatorContext.LoginHint.Should().Be("this means bob"); - _mockCibaUserValidator.UserValidatorContext.UserCode.Should().Be("xoxo"); - _mockCibaUserValidator.UserValidatorContext.BindingMessage.Should().Be(bindingMessage); - _mockCibaUserValidator.UserValidatorContext.Client.ClientId.Should().Be(_cibaClient.ClientId); + _mockCibaUserValidator.UserValidatorContext.LoginHint.ShouldBe("this means bob"); + _mockCibaUserValidator.UserValidatorContext.UserCode.ShouldBe("xoxo"); + _mockCibaUserValidator.UserValidatorContext.BindingMessage.ShouldBe(bindingMessage); + _mockCibaUserValidator.UserValidatorContext.Client.ClientId.ShouldBe(_cibaClient.ClientId); } @@ -244,10 +244,10 @@ public async Task custom_validators_are_invoked_and_can_process_custom_input() // The custom validator was invoked with the request parameters and mapped the custom input var validatedRequest = _mockCustomBackchannelAuthenticationValidator.Context.ValidationResult.ValidatedRequest; - validatedRequest.Should().NotBeNull(); - validatedRequest.ClientId.Should().Be("client1"); - validatedRequest.BindingMessage.Should().Be(bindingMessage); - validatedRequest.Properties["custom"].Should().Be("input"); + validatedRequest.ShouldNotBeNull(); + validatedRequest.ClientId.ShouldBe("client1"); + validatedRequest.BindingMessage.ShouldBe(bindingMessage); + validatedRequest.Properties["custom"].ShouldBe("input"); } [Fact] @@ -282,17 +282,17 @@ public async Task custom_validator_can_add_complex_properties_that_are_passed_to new FormUrlEncodedContent(body)); // Custom request properties are not included automatically in the response to the client - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); var responseContent = await response.Content.ReadAsStringAsync(); var json = JsonSerializer.Deserialize>(responseContent); - json.Should().NotBeNull(); - json.Should().NotContainKey("complex"); + json.ShouldNotBeNull(); + json.ShouldNotContainKey("complex"); // Custom properties are passed to the notification service var notificationProperties = _mockCibaUserNotificationService.LoginRequest.Properties; var complexObjectInNotification = notificationProperties["complex"] as Dictionary; - complexObjectInNotification.Should().NotBeNull(); - complexObjectInNotification["nested"].Should().Be("value"); + complexObjectInNotification.ShouldNotBeNull(); + complexObjectInNotification["nested"].ShouldBe("value"); } [Fact] @@ -315,14 +315,14 @@ public async Task valid_request_should_return_valid_result() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("auth_req_id").Should().BeTrue(); - values.ContainsKey("expires_in").Should().BeTrue(); - values.ContainsKey("interval").Should().BeTrue(); + values.ContainsKey("auth_req_id").ShouldBeTrue(); + values.ContainsKey("expires_in").ShouldBeTrue(); + values.ContainsKey("interval").ShouldBeTrue(); } [Fact] @@ -350,14 +350,14 @@ public async Task valid_request_object_should_return_valid_result() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("auth_req_id").Should().BeTrue(); - values.ContainsKey("expires_in").Should().BeTrue(); - values.ContainsKey("interval").Should().BeTrue(); + values.ContainsKey("auth_req_id").ShouldBeTrue(); + values.ContainsKey("expires_in").ShouldBeTrue(); + values.ContainsKey("interval").ShouldBeTrue(); } [Fact] @@ -382,13 +382,13 @@ public async Task no_request_object_when_required_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request"); } [Fact] @@ -416,13 +416,13 @@ public async Task request_object_too_long_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request_object"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request_object"); } [Fact] @@ -450,13 +450,13 @@ public async Task request_object_invalid_signature_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request_object"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request_object"); } [Fact] @@ -483,13 +483,13 @@ public async Task request_object_missing_jti_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request_object"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request_object"); } [Fact] @@ -518,13 +518,13 @@ public async Task request_object_with_request_object_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request_object"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request_object"); } [Fact] @@ -553,13 +553,13 @@ public async Task request_object_with_request_uri_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request_object"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request_object"); } [Fact] @@ -590,13 +590,13 @@ public async Task request_object_client_with_no_keys_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request_object"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request_object"); } [Fact] @@ -628,13 +628,13 @@ public async Task request_object_client_with_invalid_key_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request_object"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request_object"); } [Fact] @@ -663,13 +663,13 @@ public async Task request_object_client_with_mismatched_client_id_should_return_ IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request_object"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request_object"); } [Fact] @@ -698,13 +698,13 @@ public async Task request_object_with_param_also_outside_jwt_should_return_error IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request_object"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request_object"); } [Fact] @@ -733,7 +733,7 @@ public async Task request_object_client_with_correct_client_id_should_return_suc IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); } [Fact] @@ -758,15 +758,15 @@ public async Task valid_request_should_notify_user() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); - _mockCibaUserNotificationService.LoginRequest.Subject.FindFirst("sub").Value.Should().Be(_user.SubjectId); - _mockCibaUserNotificationService.LoginRequest.BindingMessage.Should().Be(bindingMessage); - _mockCibaUserNotificationService.LoginRequest.Client.ClientId.Should().Be(_cibaClient.ClientId); - _mockCibaUserNotificationService.LoginRequest.RequestedResourceIndicators.Should().BeEquivalentTo(new[] { "urn:api1" }); - _mockCibaUserNotificationService.LoginRequest.AuthenticationContextReferenceClasses.Should().BeEquivalentTo(new[] { "bar", "foo" }); - _mockCibaUserNotificationService.LoginRequest.IdP.Should().Be("x"); - _mockCibaUserNotificationService.LoginRequest.Tenant.Should().Be("y"); + _mockCibaUserNotificationService.LoginRequest.Subject.FindFirst("sub").Value.ShouldBe(_user.SubjectId); + _mockCibaUserNotificationService.LoginRequest.BindingMessage.ShouldBe(bindingMessage); + _mockCibaUserNotificationService.LoginRequest.Client.ClientId.ShouldBe(_cibaClient.ClientId); + _mockCibaUserNotificationService.LoginRequest.RequestedResourceIndicators.ShouldBeEquivalentTo(new[] { "urn:api1" }); + _mockCibaUserNotificationService.LoginRequest.AuthenticationContextReferenceClasses.ShouldBeEquivalentTo(new[] { "bar", "foo" }); + _mockCibaUserNotificationService.LoginRequest.IdP.ShouldBe("x"); + _mockCibaUserNotificationService.LoginRequest.Tenant.ShouldBe("y"); } [Fact] @@ -789,13 +789,13 @@ public async Task invalid_client_credentials_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); + response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_client"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_client"); } [Fact] @@ -820,13 +820,13 @@ public async Task invalid_client_grant_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("unauthorized_client"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("unauthorized_client"); } [Theory] @@ -855,13 +855,13 @@ public async Task invalid_user_errors_should_return_error(string error, HttpStat IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(code); + response.StatusCode.ShouldBe(code); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be(error); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe(error); } [Fact] @@ -884,13 +884,13 @@ public async Task unknown_user_validator_error_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("unknown_user_id"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("unknown_user_id"); } [Fact] @@ -915,13 +915,13 @@ public async Task validated_user_missing_sub_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("unknown_user_id"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("unknown_user_id"); } [Fact] @@ -943,13 +943,13 @@ public async Task missing_scope_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request"); } [Fact] @@ -973,13 +973,13 @@ public async Task scope_too_long_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request"); } [Fact] @@ -1002,13 +1002,13 @@ public async Task scope_missing_openid_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request"); } [Fact] @@ -1032,13 +1032,13 @@ public async Task resource_too_long_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_target"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_target"); } [Fact] @@ -1062,13 +1062,13 @@ public async Task resource_invalid_format_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_target"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_target"); } [Fact] @@ -1092,13 +1092,13 @@ public async Task invalid_resource_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_target"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_target"); } [Fact] @@ -1127,13 +1127,13 @@ public async Task invalid_scope_for_resource_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_scope"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_scope"); } [Fact] @@ -1157,13 +1157,13 @@ public async Task expiry_too_long_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request"); } [Fact] @@ -1189,13 +1189,13 @@ public async Task expiry_larger_than_client_allows_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request"); } [Fact] @@ -1221,7 +1221,7 @@ public async Task expiry_than_than_client_allows_should_return_success() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); } [Fact] @@ -1245,13 +1245,13 @@ public async Task acr_values_too_long_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request"); } [Fact] @@ -1277,9 +1277,9 @@ public async Task client_with_idp_restriction_should_ignore_invalid_idp_acr_valu IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); - _mockCibaUserNotificationService.LoginRequest.IdP.Should().BeNullOrEmpty(); + _mockCibaUserNotificationService.LoginRequest.IdP.ShouldBeNullOrEmpty(); } [Fact] @@ -1304,13 +1304,13 @@ public async Task too_many_login_hints_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request"); } { var bindingMessage = Guid.NewGuid().ToString("n"); @@ -1330,13 +1330,13 @@ public async Task too_many_login_hints_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request"); } { var bindingMessage = Guid.NewGuid().ToString("n"); @@ -1356,13 +1356,13 @@ public async Task too_many_login_hints_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request"); } } @@ -1385,13 +1385,13 @@ public async Task too_few_login_hints_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request"); } [Fact] @@ -1414,13 +1414,13 @@ public async Task login_hint_too_long_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request"); } [Fact] @@ -1443,13 +1443,13 @@ public async Task login_hint_token_too_long_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request"); } [Fact] @@ -1472,13 +1472,13 @@ public async Task id_token_hint_too_long_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request"); } [Fact] @@ -1501,13 +1501,13 @@ public async Task invalid_id_token_hint_too_long_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request"); } [Fact] @@ -1538,11 +1538,11 @@ public async Task valid_id_token_hint_should_return_success() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); - _mockCibaUserNotificationService.LoginRequest.Subject.HasClaim("sub", _user.SubjectId).Should().BeTrue(); - _mockCibaUserValidator.UserValidatorContext.IdTokenHint.Should().Be(id_token); - _mockCibaUserValidator.UserValidatorContext.IdTokenHintClaims.Should().Contain(x => x.Type == "sub" && x.Value == _user.SubjectId); + _mockCibaUserNotificationService.LoginRequest.Subject.HasClaim("sub", _user.SubjectId).ShouldBeTrue(); + _mockCibaUserValidator.UserValidatorContext.IdTokenHint.ShouldBe(id_token); + _mockCibaUserValidator.UserValidatorContext.IdTokenHintClaims.ShouldContain(x => x.Type == "sub" && x.Value == _user.SubjectId); } [Fact] @@ -1565,10 +1565,10 @@ public async Task valid_login_hint_token_hint_should_return_success() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); - _mockCibaUserNotificationService.LoginRequest.Subject.HasClaim("sub", _user.SubjectId).Should().BeTrue(); - _mockCibaUserValidator.UserValidatorContext.LoginHintToken.Should().Be("xoxo"); + _mockCibaUserNotificationService.LoginRequest.Subject.HasClaim("sub", _user.SubjectId).ShouldBeTrue(); + _mockCibaUserValidator.UserValidatorContext.LoginHintToken.ShouldBe("xoxo"); } [Fact] @@ -1592,13 +1592,13 @@ public async Task user_code_too_long_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_request"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_request"); } [Fact] @@ -1621,13 +1621,13 @@ public async Task binding_message_too_long_should_return_error() IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(body)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_binding_message"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_binding_message"); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/DeviceAuthorization/DeviceAuthorizationTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/DeviceAuthorization/DeviceAuthorizationTests.cs index fb4b5cf65..4a09a628a 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/DeviceAuthorization/DeviceAuthorizationTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/DeviceAuthorization/DeviceAuthorizationTests.cs @@ -11,7 +11,7 @@ using System.Text.Json; using System.Threading.Tasks; using Duende.IdentityServer.Models; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using IntegrationTests.Common; using Xunit; @@ -46,12 +46,12 @@ public DeviceAuthorizationTests() public async Task get_should_return_InvalidRequest() { var response = await _mockPipeline.BackChannelClient.GetAsync(IdentityServerPipeline.DeviceAuthorization); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var resultDto = ParseJsonBody(await response.Content.ReadAsStreamAsync()); - resultDto.Should().NotBeNull(); - resultDto.error.Should().Be(OidcConstants.TokenErrors.InvalidRequest); + resultDto.ShouldNotBeNull(); + resultDto.error.ShouldBe(OidcConstants.TokenErrors.InvalidRequest); } [Fact] @@ -65,12 +65,12 @@ public async Task wrong_content_type_return_InvalidRequest() var response = await _mockPipeline.BackChannelClient.PostAsync(IdentityServerPipeline.DeviceAuthorization, new StringContent(@"{""client_id"": ""client1""}", Encoding.UTF8, "application/json")); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var resultDto = ParseJsonBody(await response.Content.ReadAsStreamAsync()); - resultDto.Should().NotBeNull(); - resultDto.error.Should().Be(OidcConstants.TokenErrors.InvalidRequest); + resultDto.ShouldNotBeNull(); + resultDto.error.ShouldBe(OidcConstants.TokenErrors.InvalidRequest); } [Fact] @@ -80,12 +80,12 @@ public async Task empty_request_should_return_InvalidRequest() var response = await _mockPipeline.BackChannelClient.PostAsync(IdentityServerPipeline.DeviceAuthorization, new FormUrlEncodedContent(new Dictionary())); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var resultDto = ParseJsonBody(await response.Content.ReadAsStreamAsync()); - resultDto.Should().NotBeNull(); - resultDto.error.Should().Be(OidcConstants.TokenErrors.InvalidRequest); + resultDto.ShouldNotBeNull(); + resultDto.error.ShouldBe(OidcConstants.TokenErrors.InvalidRequest); } [Fact] @@ -98,12 +98,12 @@ public async Task unknown_client_should_return_InvalidClient() }; var response = await _mockPipeline.BackChannelClient.PostAsync(IdentityServerPipeline.DeviceAuthorization, new FormUrlEncodedContent(form)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var resultDto = ParseJsonBody(await response.Content.ReadAsStreamAsync()); - resultDto.Should().NotBeNull(); - resultDto.error.Should().Be(OidcConstants.TokenErrors.InvalidClient); + resultDto.ShouldNotBeNull(); + resultDto.error.ShouldBe(OidcConstants.TokenErrors.InvalidClient); } [Fact] @@ -117,20 +117,20 @@ public async Task valid_should_return_json() }; var response = await _mockPipeline.BackChannelClient.PostAsync(IdentityServerPipeline.DeviceAuthorization, new FormUrlEncodedContent(form)); - response.StatusCode.Should().Be(HttpStatusCode.OK); - response.Content.Headers.ContentType.MediaType.Should().Be("application/json"); + response.StatusCode.ShouldBe(HttpStatusCode.OK); + response.Content.Headers.ContentType.MediaType.ShouldBe("application/json"); var resultDto = ParseJsonBody(await response.Content.ReadAsStreamAsync()); - resultDto.Should().NotBeNull(); + resultDto.ShouldNotBeNull(); - resultDto.Should().NotBeNull(); - resultDto.device_code.Should().NotBeNull(); - resultDto.user_code.Should().NotBeNull(); - resultDto.verification_uri.Should().NotBeNull(); - resultDto.verification_uri_complete.Should().NotBeNull(); - resultDto.expires_in.Should().BeGreaterThan(0); - resultDto.interval.Should().BeGreaterThan(0); + resultDto.ShouldNotBeNull(); + resultDto.device_code.ShouldNotBeNull(); + resultDto.user_code.ShouldNotBeNull(); + resultDto.verification_uri.ShouldNotBeNull(); + resultDto.verification_uri_complete.ShouldNotBeNull(); + resultDto.expires_in.ShouldBeGreaterThan(0); + resultDto.interval.ShouldBeGreaterThan(0); } private T ParseJsonBody(Stream streamBody) diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Discovery/DiscoveryEndpointTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Discovery/DiscoveryEndpointTests.cs index 3f9ce0790..0272da6d4 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Discovery/DiscoveryEndpointTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Discovery/DiscoveryEndpointTests.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel.Client; using IntegrationTests.Common; using Microsoft.Extensions.DependencyInjection; @@ -34,7 +34,7 @@ public async Task Issuer_uri_should_be_lowercase() var json = await result.Content.ReadAsStringAsync(); var data = JsonSerializer.Deserialize>(json); - data["issuer"].GetString().Should().Be("https://server/root"); + data["issuer"].GetString().ShouldBe("https://server/root"); } [Fact] @@ -50,7 +50,7 @@ public async Task when_lower_case_issuer_option_disabled_issuer_uri_should_be_pr var json = await result.Content.ReadAsStringAsync(); var data = JsonSerializer.Deserialize>(json); - data["issuer"].GetString().Should().Be("https://server/ROOT"); + data["issuer"].GetString().ShouldBe("https://server/ROOT"); } private void Pipeline_OnPostConfigureServices(IServiceCollection obj) @@ -81,9 +81,9 @@ public async Task Algorithms_supported_should_match_signing_key() var algorithmsSupported = data["id_token_signing_alg_values_supported"].EnumerateArray() .Select(x => x.GetString()).ToList(); - algorithmsSupported.Count.Should().Be(2); - algorithmsSupported.Should().Contain(SecurityAlgorithms.RsaSha256); - algorithmsSupported.Should().Contain(SecurityAlgorithms.EcdsaSha256); + algorithmsSupported.Count.ShouldBe(2); + algorithmsSupported.ShouldContain(SecurityAlgorithms.RsaSha256); + algorithmsSupported.ShouldContain(SecurityAlgorithms.EcdsaSha256); } [Fact] @@ -122,15 +122,11 @@ public async Task Jwks_entries_should_countain_crv() var data = JsonSerializer.Deserialize>(json); var keys = data["keys"].EnumerateArray().ToList(); - keys.Should().NotBeNull(); - keys.Count.Should().Be(2); + keys.Count.ShouldBe(2); var key = keys[1]; - key.Should().NotBeNull(); - var crv = key.TryGetValue("crv"); - crv.GetString().Should().Be(JsonWebKeyECTypes.P256); - + crv.GetString().ShouldBe(JsonWebKeyECTypes.P256); } [Fact] @@ -146,13 +142,10 @@ public async Task Jwks_entries_should_contain_alg() var data = JsonSerializer.Deserialize>(json); var keys = data["keys"]; - keys.Should().NotBeNull(); - var key = keys[0]; - key.Should().NotBeNull(); var alg = key.TryGetValue("alg"); - alg.GetString().Should().Be(Constants.SigningAlgorithms.RSA_SHA_256); + alg.GetString().ShouldBe(Constants.SigningAlgorithms.RSA_SHA_256); } [Theory] @@ -179,8 +172,8 @@ public async Task Jwks_with_ecdsa_should_have_parsable_key(string crv, string al var parsedKeys = jwks.GetSigningKeys(); var matchingKey = parsedKeys.FirstOrDefault(x => x.KeyId == key.KeyId); - matchingKey.Should().NotBeNull(); - matchingKey.Should().BeOfType(); + matchingKey.ShouldNotBeNull(); + matchingKey.ShouldBeOfType(); } [Fact] @@ -203,8 +196,8 @@ public async Task Jwks_with_two_key_using_different_algs_expect_different_alg_va var json = await result.Content.ReadAsStringAsync(); var jwks = new JsonWebKeySet(json); - jwks.Keys.Should().Contain(x => x.KeyId == ecdsaKey.KeyId && x.Alg == "ES256"); - jwks.Keys.Should().Contain(x => x.KeyId == rsaKey.KeyId && x.Alg == "RS256"); + jwks.Keys.ShouldContain(x => x.KeyId == ecdsaKey.KeyId && x.Alg == "ES256"); + jwks.Keys.ShouldContain(x => x.KeyId == rsaKey.KeyId && x.Alg == "RS256"); } [Fact] @@ -226,7 +219,7 @@ public async Task Unicode_values_in_url_should_be_processed_correctly() } }); - result.Issuer.Should().Be("https://грант.рф"); + result.Issuer.ShouldBe("https://грант.рф"); } @@ -243,7 +236,7 @@ public async Task prompt_values_supported_should_contain_defaults() var data = JsonSerializer.Deserialize>(json); var prompts = data["prompt_values_supported"].EnumerateArray() .Select(x => x.GetString()).ToList(); - prompts.Should().BeEquivalentTo(new[] { "none", "login", "consent", "select_account" }); + prompts.ShouldBeEquivalentTo(new[] { "none", "login", "consent", "select_account" }); } [Fact] @@ -266,7 +259,7 @@ public async Task createaccount_options_should_include_create_in_prompt_values_s var data = JsonSerializer.Deserialize>(json); var prompts = data["prompt_values_supported"].EnumerateArray() .Select(x => x.GetString()).ToList(); - prompts.Should().Contain("create"); + prompts.ShouldContain("create"); } [Fact] @@ -281,6 +274,6 @@ public async Task prompt_values_supported_should_be_absent_if_no_authorize_endpo var json = await result.Content.ReadAsStringAsync(); var data = JsonSerializer.Deserialize>(json); - data.ContainsKey("prompt_values_supported").Should().BeFalse(); + data.ContainsKey("prompt_values_supported").ShouldBeFalse(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/EndSession/EndSessionTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/EndSession/EndSessionTests.cs index 20689802c..213d2134d 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/EndSession/EndSessionTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/EndSession/EndSessionTests.cs @@ -15,7 +15,7 @@ using Duende.IdentityServer; using Duende.IdentityServer.Models; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using IntegrationTests.Common; using Microsoft.AspNetCore.WebUtilities; @@ -106,7 +106,7 @@ public async Task get_request_should_not_return_404() { var response = await _mockPipeline.BackChannelClient.GetAsync(IdentityServerPipeline.EndSessionEndpoint); - response.StatusCode.Should().NotBe(HttpStatusCode.NotFound); + response.StatusCode.ShouldNotBe(HttpStatusCode.NotFound); } [Fact] @@ -115,7 +115,7 @@ public async Task signout_request_should_redirect_to_logout_page() { var response = await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.EndSessionEndpoint); - _mockPipeline.LogoutWasCalled.Should().BeTrue(); + _mockPipeline.LogoutWasCalled.ShouldBeTrue(); } [Fact] @@ -144,8 +144,8 @@ public async Task get_request_should_redirect_to_configured_logout_path() "?id_token_hint=" + id_token + "&post_logout_redirect_uri=https://client1/signout-callback"); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://server/logout?id="); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://server/logout?id="); } [Fact] @@ -169,16 +169,16 @@ public async Task logout_request_with_params_should_pass_values_in_logout_contex "&post_logout_redirect_uri=https://client2/signout-callback2" + "&ui_locales=fr-FR fr-CA"); - _mockPipeline.LogoutWasCalled.Should().BeTrue(); - _mockPipeline.LogoutRequest.Should().NotBeNull(); - _mockPipeline.LogoutRequest.ClientId.Should().Be("client2"); - _mockPipeline.LogoutRequest.PostLogoutRedirectUri.Should().Be("https://client2/signout-callback2"); - _mockPipeline.LogoutRequest.UiLocales.Should().Be("fr-FR fr-CA"); + _mockPipeline.LogoutWasCalled.ShouldBeTrue(); + _mockPipeline.LogoutRequest.ShouldNotBeNull(); + _mockPipeline.LogoutRequest.ClientId.ShouldBe("client2"); + _mockPipeline.LogoutRequest.PostLogoutRedirectUri.ShouldBe("https://client2/signout-callback2"); + _mockPipeline.LogoutRequest.UiLocales.ShouldBe("fr-FR fr-CA"); var parts = _mockPipeline.LogoutRequest.SignOutIFrameUrl.Split('?'); - parts[0].Should().Be(IdentityServerPipeline.EndSessionCallbackEndpoint); + parts[0].ShouldBe(IdentityServerPipeline.EndSessionCallbackEndpoint); var iframeUrl = QueryHelpers.ParseNullableQuery(parts[1]); - iframeUrl["endSessionId"].FirstOrDefault().Should().NotBeNull(); + iframeUrl["endSessionId"].FirstOrDefault().ShouldNotBeNull(); } [Fact] @@ -202,11 +202,11 @@ public async Task ui_locales_too_long_should_be_ignored() "&post_logout_redirect_uri=https://client2/signout-callback2" + "&ui_locales=" + new string('x', 101)); - _mockPipeline.LogoutWasCalled.Should().BeTrue(); - _mockPipeline.LogoutRequest.Should().NotBeNull(); - _mockPipeline.LogoutRequest.ClientId.Should().Be("client2"); - _mockPipeline.LogoutRequest.PostLogoutRedirectUri.Should().Be("https://client2/signout-callback2"); - _mockPipeline.LogoutRequest.UiLocales.Should().BeNull(); + _mockPipeline.LogoutWasCalled.ShouldBeTrue(); + _mockPipeline.LogoutRequest.ShouldNotBeNull(); + _mockPipeline.LogoutRequest.ClientId.ShouldBe("client2"); + _mockPipeline.LogoutRequest.PostLogoutRedirectUri.ShouldBe("https://client2/signout-callback2"); + _mockPipeline.LogoutRequest.UiLocales.ShouldBeNull(); } [Fact] @@ -231,11 +231,11 @@ public async Task logout_request_with_params_but_user_no_longer_authenticated_sh "?id_token_hint=" + id_token + "&post_logout_redirect_uri=https://client2/signout-callback2"); - _mockPipeline.LogoutWasCalled.Should().BeTrue(); - _mockPipeline.LogoutRequest.Should().NotBeNull(); - _mockPipeline.LogoutRequest.ClientId.Should().Be("client2"); - _mockPipeline.LogoutRequest.PostLogoutRedirectUri.Should().Be("https://client2/signout-callback2"); - _mockPipeline.LogoutRequest.SignOutIFrameUrl.Should().BeNull(); + _mockPipeline.LogoutWasCalled.ShouldBeTrue(); + _mockPipeline.LogoutRequest.ShouldNotBeNull(); + _mockPipeline.LogoutRequest.ClientId.ShouldBe("client2"); + _mockPipeline.LogoutRequest.PostLogoutRedirectUri.ShouldBe("https://client2/signout-callback2"); + _mockPipeline.LogoutRequest.SignOutIFrameUrl.ShouldBeNull(); } [Fact] @@ -265,15 +265,15 @@ public async Task signout_should_support_POST() var content = new FormUrlEncodedContent(values); response = await _mockPipeline.BrowserClient.PostAsync(IdentityServerPipeline.EndSessionEndpoint, content); - _mockPipeline.LogoutWasCalled.Should().BeTrue(); - _mockPipeline.LogoutRequest.Should().NotBeNull(); - _mockPipeline.LogoutRequest.ClientId.Should().Be("client1"); - _mockPipeline.LogoutRequest.PostLogoutRedirectUri.Should().Be("https://client1/signout-callback"); + _mockPipeline.LogoutWasCalled.ShouldBeTrue(); + _mockPipeline.LogoutRequest.ShouldNotBeNull(); + _mockPipeline.LogoutRequest.ClientId.ShouldBe("client1"); + _mockPipeline.LogoutRequest.PostLogoutRedirectUri.ShouldBe("https://client1/signout-callback"); var parts = _mockPipeline.LogoutRequest.SignOutIFrameUrl.Split('?'); - parts[0].Should().Be(IdentityServerPipeline.EndSessionCallbackEndpoint); + parts[0].ShouldBe(IdentityServerPipeline.EndSessionCallbackEndpoint); var iframeUrl = QueryHelpers.ParseNullableQuery(parts[1]); - iframeUrl["endSessionId"].FirstOrDefault().Should().NotBeNull(); + iframeUrl["endSessionId"].FirstOrDefault().ShouldNotBeNull(); } [Fact] @@ -282,7 +282,7 @@ public async Task signout_callback_without_params_should_return_400() { var response = await _mockPipeline.BackChannelClient.GetAsync(IdentityServerPipeline.EndSessionCallbackEndpoint); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); } [Fact] @@ -314,8 +314,8 @@ public async Task signout_callback_with_mismatched_post_logout_redirect_uri_shou response = await _mockPipeline.BrowserClient.GetAsync(signoutFrameUrl); - _mockPipeline.LogoutRequest.ClientId.Should().NotBeNull(); - _mockPipeline.LogoutRequest.PostLogoutRedirectUri.Should().BeNull(); + _mockPipeline.LogoutRequest.ClientId.ShouldNotBeNull(); + _mockPipeline.LogoutRequest.PostLogoutRedirectUri.ShouldBeNull(); } [Fact] @@ -345,8 +345,8 @@ public async Task signout_callback_with_mismatched_id_token_hint_should_not_pass "?id_token_hint=" + id_token + "&post_logout_redirect_uri=https://client1/signout-callback"); - _mockPipeline.LogoutRequest.ClientId.Should().BeNull(); - _mockPipeline.LogoutRequest.PostLogoutRedirectUri.Should().BeNull(); + _mockPipeline.LogoutRequest.ClientId.ShouldBeNull(); + _mockPipeline.LogoutRequest.PostLogoutRedirectUri.ShouldBeNull(); } [Fact] @@ -372,8 +372,8 @@ public async Task valid_signout_callback_should_return_200_html() var signoutFrameUrl = _mockPipeline.LogoutRequest.SignOutIFrameUrl; response = await _mockPipeline.BrowserClient.GetAsync(signoutFrameUrl); - response.StatusCode.Should().Be(HttpStatusCode.OK); - response.Content.Headers.ContentType.MediaType.Should().Be("text/html"); + response.StatusCode.ShouldBe(HttpStatusCode.OK); + response.Content.Headers.ContentType.MediaType.ShouldBe("text/html"); } [Fact] @@ -409,8 +409,8 @@ public async Task valid_signout_callback_should_render_iframes_for_all_clients() response = await _mockPipeline.BrowserClient.GetAsync(signoutFrameUrl); var html = await response.Content.ReadAsStringAsync(); - html.Should().Contain(HtmlEncoder.Default.Encode("https://client1/signout?sid=" + sid + "&iss=" + UrlEncoder.Default.Encode("https://server"))); - html.Should().Contain(HtmlEncoder.Default.Encode("https://client2/signout?sid=" + sid + "&iss=" + UrlEncoder.Default.Encode("https://server"))); + html.ShouldContain(HtmlEncoder.Default.Encode("https://client1/signout?sid=" + sid + "&iss=" + UrlEncoder.Default.Encode("https://server"))); + html.ShouldContain(HtmlEncoder.Default.Encode("https://client2/signout?sid=" + sid + "&iss=" + UrlEncoder.Default.Encode("https://server"))); } [Fact] @@ -441,7 +441,7 @@ public async Task signout_callback_should_use_signoutcleanup_for_wsfed_client() response = await _mockPipeline.BrowserClient.GetAsync(signoutFrameUrl); var html = await response.Content.ReadAsStringAsync(); - html.Should().Contain("https://client4/signout?wa=wsignoutcleanup1.0"); + html.ShouldContain("https://client4/signout?wa=wsignoutcleanup1.0"); } [Fact] @@ -466,7 +466,7 @@ public async Task valid_id_token_hint_but_no_post_logout_redirect_uri_should_not response = await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.EndSessionEndpoint + "?id_token_hint=" + id_token); - _mockPipeline.LogoutRequest.PostLogoutRedirectUri.Should().BeNull(); + _mockPipeline.LogoutRequest.PostLogoutRedirectUri.ShouldBeNull(); } [Fact] @@ -491,7 +491,7 @@ public async Task valid_id_token_hint_but_no_post_logout_redirect_uri_should_not response = await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.EndSessionEndpoint + "?id_token_hint=" + id_token); - _mockPipeline.LogoutRequest.PostLogoutRedirectUri.Should().BeNull(); + _mockPipeline.LogoutRequest.PostLogoutRedirectUri.ShouldBeNull(); } [Fact] @@ -507,12 +507,12 @@ public async Task logout_with_clients_should_render_signout_callback_iframe() redirectUri: "https://client2/callback", state: "123_state", nonce: "123_nonce"); - response.Should().NotBeNull(); + response.ShouldNotBeNull(); await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.EndSessionEndpoint); - _mockPipeline.LogoutWasCalled.Should().BeTrue(); - _mockPipeline.LogoutRequest.SignOutIFrameUrl.Should().NotBeNull(); + _mockPipeline.LogoutWasCalled.ShouldBeTrue(); + _mockPipeline.LogoutRequest.SignOutIFrameUrl.ShouldNotBeNull(); } [Fact] @@ -523,8 +523,8 @@ public async Task logout_without_clients_should_not_render_signout_callback_ifra await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.EndSessionEndpoint); - _mockPipeline.LogoutWasCalled.Should().BeTrue(); - _mockPipeline.LogoutRequest.SignOutIFrameUrl.Should().BeNull(); + _mockPipeline.LogoutWasCalled.ShouldBeTrue(); + _mockPipeline.LogoutRequest.SignOutIFrameUrl.ShouldBeNull(); } [Fact] @@ -533,30 +533,30 @@ public async Task logout_should_invoke_back_channel_logout() { _mockPipeline.BackChannelMessageHandler.OnInvoke = async req => { - req.RequestUri.ToString().Should().StartWith("https://client3/signout"); + req.RequestUri.ToString().ShouldStartWith("https://client3/signout"); var form = await req.Content.ReadAsStringAsync(); - form.Should().Contain(OidcConstants.BackChannelLogoutRequest.LogoutToken); + form.ShouldContain(OidcConstants.BackChannelLogoutRequest.LogoutToken); var token = form.Split('=')[1]; var parts = token.Split('.'); - parts.Length.Should().Be(3); + parts.Length.ShouldBe(3); var bytes = Base64Url.Decode(parts[1]); var json = Encoding.UTF8.GetString(bytes); var payload = JsonSerializer.Deserialize>(json); - payload["iss"].GetString().Should().Be("https://server"); - payload["sub"].GetString().Should().Be("bob"); - payload["aud"].GetString().Should().Be("client3"); - payload["iat"].Should().NotBeNull(); - payload["jti"].Should().NotBeNull(); - payload["sid"].Should().NotBeNull(); - payload["logout_reason"].Should().Be("user_logout"); - payload["events"].ValueKind.Should().Be(JsonValueKind.Object); - payload["events"].EnumerateObject().Single().Name.Should() - .Be("http://schemas.openid.net/event/backchannel-logout"); - payload["events"].EnumerateObject().Single().Value.EnumerateObject().Count().Should().Be(0); + payload["iss"].GetString().ShouldBe("https://server"); + payload["sub"].GetString().ShouldBe("bob"); + payload["aud"].GetString().ShouldBe("client3"); + payload.ShouldContainKey("iat"); + payload.ShouldContainKey("jti"); + payload.ShouldContainKey("sid"); + payload["logout_reason"].GetString().ShouldBe("user_logout"); + payload["events"].ValueKind.ShouldBe(JsonValueKind.Object); + payload["events"].EnumerateObject().Single().Name + .ShouldBe("http://schemas.openid.net/event/backchannel-logout"); + payload["events"].EnumerateObject().Single().Value.EnumerateObject().Count().ShouldBe(0); }; await _mockPipeline.LoginAsync("bob"); @@ -568,11 +568,11 @@ public async Task logout_should_invoke_back_channel_logout() redirectUri: "https://client3/callback", state: "123_state", nonce: "123_nonce"); - response.Should().NotBeNull(); + response.ShouldNotBeNull(); await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.EndSessionEndpoint); - _mockPipeline.BackChannelMessageHandler.InvokeWasCalled.Should().BeTrue(); + _mockPipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeTrue(); } [Fact] @@ -581,20 +581,20 @@ public async Task back_channel_logout_token_should_have_typ_header_set() { _mockPipeline.BackChannelMessageHandler.OnInvoke = async req => { - req.RequestUri.ToString().Should().StartWith("https://client3/signout"); + req.RequestUri.ToString().ShouldStartWith("https://client3/signout"); var form = await req.Content.ReadAsStringAsync(); - form.Should().Contain(OidcConstants.BackChannelLogoutRequest.LogoutToken); + form.ShouldContain(OidcConstants.BackChannelLogoutRequest.LogoutToken); var token = form.Split('=')[1]; var parts = token.Split('.'); - parts.Length.Should().Be(3); + parts.Length.ShouldBe(3); var bytes = Base64Url.Decode(parts[0]); var json = Encoding.UTF8.GetString(bytes); var header = JsonSerializer.Deserialize>(json); - header["typ"].GetString().Should().Be("logout+jwt"); + header["typ"].GetString().ShouldBe("logout+jwt"); }; await _mockPipeline.LoginAsync("bob"); @@ -606,11 +606,11 @@ public async Task back_channel_logout_token_should_have_typ_header_set() redirectUri: "https://client3/callback", state: "123_state", nonce: "123_nonce"); - response.Should().NotBeNull(); + response.ShouldNotBeNull(); await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.EndSessionEndpoint); - _mockPipeline.BackChannelMessageHandler.InvokeWasCalled.Should().BeTrue(); + _mockPipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeTrue(); } [Fact] @@ -621,20 +621,20 @@ public async Task back_channel_logout_token_should_use_configured_typ_header_val _mockPipeline.BackChannelMessageHandler.OnInvoke = async req => { - req.RequestUri.ToString().Should().StartWith("https://client3/signout"); + req.RequestUri.ToString().ShouldStartWith("https://client3/signout"); var form = await req.Content.ReadAsStringAsync(); - form.Should().Contain(OidcConstants.BackChannelLogoutRequest.LogoutToken); + form.ShouldContain(OidcConstants.BackChannelLogoutRequest.LogoutToken); var token = form.Split('=')[1]; var parts = token.Split('.'); - parts.Length.Should().Be(3); + parts.Length.ShouldBe(3); var bytes = Base64Url.Decode(parts[0]); var json = Encoding.UTF8.GetString(bytes); var header = JsonSerializer.Deserialize>(json); - header["typ"].GetString().Should().Be("jwt"); + header["typ"].GetString().ShouldBe("jwt"); }; await _mockPipeline.LoginAsync("bob"); @@ -646,11 +646,11 @@ public async Task back_channel_logout_token_should_use_configured_typ_header_val redirectUri: "https://client3/callback", state: "123_state", nonce: "123_nonce"); - response.Should().NotBeNull(); + response.ShouldNotBeNull(); await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.EndSessionEndpoint); - _mockPipeline.BackChannelMessageHandler.InvokeWasCalled.Should().BeTrue(); + _mockPipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeTrue(); } [Fact] @@ -668,11 +668,11 @@ public async Task back_channel_logout_should_not_affect_end_session_callback() redirectUri: "https://client3/callback", state: "123_state", nonce: "123_nonce"); - response.Should().NotBeNull(); + response.ShouldNotBeNull(); await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.EndSessionEndpoint); - _mockPipeline.BackChannelMessageHandler.InvokeWasCalled.Should().BeTrue(); + _mockPipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeTrue(); } [Fact] @@ -693,11 +693,11 @@ public async Task back_channel_json_errors_can_be_logged() redirectUri: "https://client3/callback", state: "123_state", nonce: "123_nonce"); - response.Should().NotBeNull(); + response.ShouldNotBeNull(); await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.EndSessionEndpoint); - _mockPipeline.BackChannelMessageHandler.InvokeWasCalled.Should().BeTrue(); + _mockPipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeTrue(); } [Fact] @@ -718,11 +718,11 @@ public async Task back_channel_bad_json_errors_can_be_logged() redirectUri: "https://client3/callback", state: "123_state", nonce: "123_nonce"); - response.Should().NotBeNull(); + response.ShouldNotBeNull(); await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.EndSessionEndpoint); - _mockPipeline.BackChannelMessageHandler.InvokeWasCalled.Should().BeTrue(); + _mockPipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeTrue(); } [Fact] @@ -741,10 +741,10 @@ public async Task back_channel_errors_no_content_can_be_logged() redirectUri: "https://client3/callback", state: "123_state", nonce: "123_nonce"); - response.Should().NotBeNull(); + response.ShouldNotBeNull(); await _mockPipeline.BrowserClient.GetAsync(IdentityServerPipeline.EndSessionEndpoint); - _mockPipeline.BackChannelMessageHandler.InvokeWasCalled.Should().BeTrue(); + _mockPipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeTrue(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Introspection/IntrospectionTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Introspection/IntrospectionTests.cs index 81e47f662..e53d005e8 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Introspection/IntrospectionTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Introspection/IntrospectionTests.cs @@ -11,7 +11,7 @@ using System.Text.Json; using System.Threading.Tasks; using Duende.IdentityServer; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel.Client; using IntegrationTests.Endpoints.Introspection.Setup; using Microsoft.AspNetCore.Hosting; @@ -48,7 +48,7 @@ public async Task Empty_request_should_fail() var response = await _client.PostAsync(IntrospectionEndpoint, new FormUrlEncodedContent(form)); - response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); + response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); } [Fact] @@ -60,7 +60,7 @@ public async Task Unknown_scope_should_fail() _client.SetBasicAuthentication("unknown", "invalid"); var response = await _client.PostAsync(IntrospectionEndpoint, new FormUrlEncodedContent(form)); - response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); + response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); } [Fact] @@ -72,7 +72,7 @@ public async Task Invalid_scope_secret_should_fail() _client.SetBasicAuthentication("api1", "invalid"); var response = await _client.PostAsync(IntrospectionEndpoint, new FormUrlEncodedContent(form)); - response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); + response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); } [Fact] @@ -84,7 +84,7 @@ public async Task Missing_token_should_fail() _client.SetBasicAuthentication("api1", "secret"); var response = await _client.PostAsync(IntrospectionEndpoint, new FormUrlEncodedContent(form)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); } [Fact] @@ -100,8 +100,8 @@ public async Task Invalid_token_should_fail() Token = "invalid" }); - introspectionResponse.IsActive.Should().Be(false); - introspectionResponse.IsError.Should().Be(false); + introspectionResponse.IsActive.ShouldBe(false); + introspectionResponse.IsError.ShouldBe(false); } [Fact] @@ -126,7 +126,7 @@ public async Task Invalid_Content_type_should_fail() var client = new HttpClient(_handler); var response = await client.PostAsync(IntrospectionEndpoint, new StringContent(json, Encoding.UTF8, "application/json")); - response.StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType); + response.StatusCode.ShouldBe(HttpStatusCode.UnsupportedMediaType); } [Fact] @@ -151,15 +151,15 @@ public async Task Invalid_token_type_hint_should_not_fail() TokenTypeHint = "invalid" }); - introspectionResponse.IsActive.Should().Be(true); - introspectionResponse.IsError.Should().Be(false); + introspectionResponse.IsActive.ShouldBe(true); + introspectionResponse.IsError.ShouldBe(false); var scopes = from c in introspectionResponse.Claims where c.Type == "scope" select c; - scopes.Count().Should().Be(1); - scopes.First().Value.Should().Be("api1"); + scopes.Count().ShouldBe(1); + scopes.First().Value.ShouldBe("api1"); } [Theory] @@ -194,13 +194,13 @@ public async Task Access_tokens_can_be_introspected_with_any_hint(string introsp TokenTypeHint = hint }); - introspectionResponse.IsActive.Should().Be(true); - introspectionResponse.IsError.Should().Be(false); + introspectionResponse.IsActive.ShouldBe(true); + introspectionResponse.IsError.ShouldBe(false); var scopes = from c in introspectionResponse.Claims where c.Type == "scope" select c.Value; - scopes.Should().Contain("api1"); + scopes.ShouldContain("api1"); } [Theory] @@ -242,20 +242,20 @@ public async Task Refresh_tokens_can_be_introspected_by_their_client_with_any_hi if (isActive) { - introspectionResponse.IsActive.Should().Be(true); - introspectionResponse.IsError.Should().Be(false); + introspectionResponse.IsActive.ShouldBe(true); + introspectionResponse.IsError.ShouldBe(false); var scopes = from c in introspectionResponse.Claims where c.Type == "scope" select c; - scopes.Count().Should().Be(2); - scopes.First().Value.Should().Be("api1"); + scopes.Count().ShouldBe(2); + scopes.First().Value.ShouldBe("api1"); } else { - introspectionResponse.IsActive.Should().Be(false); - introspectionResponse.IsError.Should().Be(false); + introspectionResponse.IsActive.ShouldBe(false); + introspectionResponse.IsError.ShouldBe(false); } } @@ -280,15 +280,15 @@ public async Task Valid_token_and_valid_scope_should_succeed() Token = tokenResponse.AccessToken }); - introspectionResponse.IsActive.Should().Be(true); - introspectionResponse.IsError.Should().Be(false); + introspectionResponse.IsActive.ShouldBe(true); + introspectionResponse.IsError.ShouldBe(false); var scopes = from c in introspectionResponse.Claims where c.Type == "scope" select c; - scopes.Count().Should().Be(1); - scopes.First().Value.Should().Be("api1"); + scopes.Count().ShouldBe(1); + scopes.First().Value.ShouldBe("api1"); } [Fact] @@ -314,16 +314,16 @@ public async Task Response_data_should_be_valid_using_single_scope() var values = GetFields(introspectionResponse); - values["iss"].ValueKind.Should().Be(JsonValueKind.String); - values["aud"].ValueKind.Should().Be(JsonValueKind.String); - values["nbf"].ValueKind.Should().Be(JsonValueKind.Number); - values["exp"].ValueKind.Should().Be(JsonValueKind.Number); - values["client_id"].ValueKind.Should().Be(JsonValueKind.String); - values["active"].ValueKind.Should().Be(JsonValueKind.True); - values["scope"].ValueKind.Should().Be(JsonValueKind.String); + values["iss"].ValueKind.ShouldBe(JsonValueKind.String); + values["aud"].ValueKind.ShouldBe(JsonValueKind.String); + values["nbf"].ValueKind.ShouldBe(JsonValueKind.Number); + values["exp"].ValueKind.ShouldBe(JsonValueKind.Number); + values["client_id"].ValueKind.ShouldBe(JsonValueKind.String); + values["active"].ValueKind.ShouldBe(JsonValueKind.True); + values["scope"].ValueKind.ShouldBe(JsonValueKind.String); var scopes = values["scope"]; - scopes.GetString().Should().Be("api1"); + scopes.GetString().ShouldBe("api1"); } [Fact] @@ -341,7 +341,7 @@ public async Task Response_data_with_user_authentication_should_be_valid_using_s Scope = "api1", }); - tokenResponse.IsError.Should().BeFalse(); + tokenResponse.IsError.ShouldBeFalse(); var introspectionResponse = await _client.IntrospectTokenAsync(new TokenIntrospectionRequest { @@ -354,16 +354,16 @@ public async Task Response_data_with_user_authentication_should_be_valid_using_s var values = GetFields(introspectionResponse); - values["iss"].ValueKind.Should().Be(JsonValueKind.String); - values["aud"].ValueKind.Should().Be(JsonValueKind.String); - values["nbf"].ValueKind.Should().Be(JsonValueKind.Number); - values["exp"].ValueKind.Should().Be(JsonValueKind.Number); - values["client_id"].ValueKind.Should().Be(JsonValueKind.String); - values["active"].ValueKind.Should().Be(JsonValueKind.True); - values["scope"].ValueKind.Should().Be(JsonValueKind.String); + values["iss"].ValueKind.ShouldBe(JsonValueKind.String); + values["aud"].ValueKind.ShouldBe(JsonValueKind.String); + values["nbf"].ValueKind.ShouldBe(JsonValueKind.Number); + values["exp"].ValueKind.ShouldBe(JsonValueKind.Number); + values["client_id"].ValueKind.ShouldBe(JsonValueKind.String); + values["active"].ValueKind.ShouldBe(JsonValueKind.True); + values["scope"].ValueKind.ShouldBe(JsonValueKind.String); var scopes = values["scope"]; - scopes.GetString().Should().Be("api1"); + scopes.GetString().ShouldBe("api1"); } [Fact] @@ -379,7 +379,7 @@ public async Task Response_data_should_be_valid_using_multiple_scopes_multiple_a Scope = "api2 api3-a api3-b", }); - tokenResponse.IsError.Should().BeFalse(); + tokenResponse.IsError.ShouldBeFalse(); var introspectionResponse = await _client.IntrospectTokenAsync(new TokenIntrospectionRequest { @@ -392,23 +392,23 @@ public async Task Response_data_should_be_valid_using_multiple_scopes_multiple_a var values = GetFields(introspectionResponse); - values["aud"].ValueKind.Should().Be(JsonValueKind.Array); + values["aud"].ValueKind.ShouldBe(JsonValueKind.Array); var audiences = values["aud"].EnumerateArray(); foreach (var aud in audiences) { - aud.ValueKind.Should().Be(JsonValueKind.String); + aud.ValueKind.ShouldBe(JsonValueKind.String); } - values["iss"].ValueKind.Should().Be(JsonValueKind.String); - values["nbf"].ValueKind.Should().Be(JsonValueKind.Number); - values["exp"].ValueKind.Should().Be(JsonValueKind.Number); - values["client_id"].ValueKind.Should().Be(JsonValueKind.String); - values["active"].ValueKind.Should().Be(JsonValueKind.True); - values["scope"].ValueKind.Should().Be(JsonValueKind.String); + values["iss"].ValueKind.ShouldBe(JsonValueKind.String); + values["nbf"].ValueKind.ShouldBe(JsonValueKind.Number); + values["exp"].ValueKind.ShouldBe(JsonValueKind.Number); + values["client_id"].ValueKind.ShouldBe(JsonValueKind.String); + values["active"].ValueKind.ShouldBe(JsonValueKind.True); + values["scope"].ValueKind.ShouldBe(JsonValueKind.String); var scopes = values["scope"]; - scopes.GetString().Should().Be("api3-a api3-b"); + scopes.GetString().ShouldBe("api3-a api3-b"); } [Fact] @@ -424,7 +424,7 @@ public async Task Response_data_should_be_valid_using_multiple_scopes_single_aud Scope = "api3-a api3-b", }); - tokenResponse.IsError.Should().BeFalse(); + tokenResponse.IsError.ShouldBeFalse(); var introspectionResponse = await _client.IntrospectTokenAsync(new TokenIntrospectionRequest { @@ -437,16 +437,16 @@ public async Task Response_data_should_be_valid_using_multiple_scopes_single_aud var values = GetFields(introspectionResponse); - values["iss"].ValueKind.Should().Be(JsonValueKind.String); - values["aud"].ValueKind.Should().Be(JsonValueKind.String); - values["nbf"].ValueKind.Should().Be(JsonValueKind.Number); - values["exp"].ValueKind.Should().Be(JsonValueKind.Number); - values["client_id"].ValueKind.Should().Be(JsonValueKind.String); - values["active"].ValueKind.Should().Be(JsonValueKind.True); - values["scope"].ValueKind.Should().Be(JsonValueKind.String); + values["iss"].ValueKind.ShouldBe(JsonValueKind.String); + values["aud"].ValueKind.ShouldBe(JsonValueKind.String); + values["nbf"].ValueKind.ShouldBe(JsonValueKind.Number); + values["exp"].ValueKind.ShouldBe(JsonValueKind.Number); + values["client_id"].ValueKind.ShouldBe(JsonValueKind.String); + values["active"].ValueKind.ShouldBe(JsonValueKind.True); + values["scope"].ValueKind.ShouldBe(JsonValueKind.String); var scopes = values["scope"]; - scopes.GetString().Should().Be("api3-a api3-b"); + scopes.GetString().ShouldBe("api3-a api3-b"); } [Fact] @@ -462,7 +462,7 @@ public async Task Token_with_many_scopes_but_api_should_only_see_its_own_scopes( Scope = "api1 api2 api3-a", }); - tokenResponse.IsError.Should().BeFalse(); + tokenResponse.IsError.ShouldBeFalse(); var introspectionResponse = await _client.IntrospectTokenAsync(new TokenIntrospectionRequest { @@ -473,15 +473,15 @@ public async Task Token_with_many_scopes_but_api_should_only_see_its_own_scopes( Token = tokenResponse.AccessToken }); - introspectionResponse.IsActive.Should().BeTrue(); - introspectionResponse.IsError.Should().BeFalse(); + introspectionResponse.IsActive.ShouldBeTrue(); + introspectionResponse.IsError.ShouldBeFalse(); var scopes = from c in introspectionResponse.Claims where c.Type == "scope" select c.Value; - scopes.Count().Should().Be(1); - scopes.First().Should().Be("api3-a"); + scopes.Count().ShouldBe(1); + scopes.First().ShouldBe("api3-a"); } [Fact] @@ -506,15 +506,15 @@ public async Task Valid_token_with_valid_multiple_scopes() Token = tokenResponse.AccessToken }); - introspectionResponse.IsActive.Should().Be(true); - introspectionResponse.IsError.Should().Be(false); + introspectionResponse.IsActive.ShouldBe(true); + introspectionResponse.IsError.ShouldBe(false); var scopes = from c in introspectionResponse.Claims where c.Type == "scope" select c; - scopes.Count().Should().Be(1); - scopes.First().Value.Should().Be("api1"); + scopes.Count().ShouldBe(1); + scopes.First().Value.ShouldBe("api1"); } [Fact] @@ -539,8 +539,8 @@ public async Task Valid_token_with_invalid_scopes_should_fail() Token = tokenResponse.AccessToken }); - introspectionResponse.IsActive.Should().Be(false); - introspectionResponse.IsError.Should().Be(false); + introspectionResponse.IsActive.ShouldBe(false); + introspectionResponse.IsError.ShouldBe(false); } [Fact] @@ -564,9 +564,9 @@ public async Task client_validation_with_access_token_should_succeed() Token = tokenResponse.AccessToken }); - introspectionResponse.IsActive.Should().BeTrue(); - introspectionResponse.IsError.Should().BeFalse(); - introspectionResponse.Claims.Single(x => x.Type == "client_id").Value.Should().Be("client1"); + introspectionResponse.IsActive.ShouldBeTrue(); + introspectionResponse.IsError.ShouldBeFalse(); + introspectionResponse.Claims.Single(x => x.Type == "client_id").Value.ShouldBe("client1"); } [Fact] @@ -592,11 +592,11 @@ public async Task client_validation_with_refresh_token_should_succeed() Token = tokenResponse.RefreshToken }); - introspectionResponse.IsActive.Should().BeTrue(); - introspectionResponse.IsError.Should().BeFalse(); - introspectionResponse.Claims.Single(x => x.Type == "client_id").Value.Should().Be("ro.client"); - introspectionResponse.Claims.Single(x => x.Type == "sub").Value.Should().Be("1"); - introspectionResponse.Claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "api1", "offline_access" }); + introspectionResponse.IsActive.ShouldBeTrue(); + introspectionResponse.IsError.ShouldBeFalse(); + introspectionResponse.Claims.Single(x => x.Type == "client_id").Value.ShouldBe("ro.client"); + introspectionResponse.Claims.Single(x => x.Type == "sub").Value.ShouldBe("1"); + introspectionResponse.Claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "api1", "offline_access" }); } [Fact] @@ -622,8 +622,8 @@ public async Task api_validation_with_refresh_token_should_fail() Token = tokenResponse.RefreshToken }); - introspectionResponse.IsActive.Should().BeFalse(); - introspectionResponse.IsError.Should().BeFalse(); + introspectionResponse.IsActive.ShouldBeFalse(); + introspectionResponse.IsError.ShouldBeFalse(); } [Fact] @@ -648,7 +648,7 @@ public async Task client_validation_with_revoked_refresh_token_should_fail() Token = tokenResponse.RefreshToken }); - revocationResponse.IsError.Should().BeFalse(); + revocationResponse.IsError.ShouldBeFalse(); var introspectionResponse = await _client.IntrospectTokenAsync(new TokenIntrospectionRequest { @@ -659,8 +659,8 @@ public async Task client_validation_with_revoked_refresh_token_should_fail() Token = tokenResponse.RefreshToken }); - introspectionResponse.IsActive.Should().BeFalse(); - introspectionResponse.IsError.Should().BeFalse(); + introspectionResponse.IsActive.ShouldBeFalse(); + introspectionResponse.IsError.ShouldBeFalse(); } [Fact] @@ -684,8 +684,8 @@ public async Task client_validation_with_access_token_for_different_client_shoul Token = tokenResponse.AccessToken }); - introspectionResponse.IsActive.Should().BeFalse(); - introspectionResponse.IsError.Should().BeFalse(); + introspectionResponse.IsActive.ShouldBeFalse(); + introspectionResponse.IsError.ShouldBeFalse(); } [Fact] @@ -711,8 +711,8 @@ public async Task client_validation_with_refresh_token_for_different_client_shou Token = tokenResponse.RefreshToken }); - introspectionResponse.IsActive.Should().BeFalse(); - introspectionResponse.IsError.Should().BeFalse(); + introspectionResponse.IsActive.ShouldBeFalse(); + introspectionResponse.IsError.ShouldBeFalse(); } private Dictionary GetFields(TokenIntrospectionResponse response) => response.Raw.GetFields(); diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Revocation/RevocationTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Revocation/RevocationTests.cs index 0fe8d8c6a..1e4343e89 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Revocation/RevocationTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Revocation/RevocationTests.cs @@ -9,7 +9,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Models; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel.Client; using IntegrationTests.Common; using Xunit; @@ -125,8 +125,8 @@ private async Task GetTokensAsync() "api offline_access", "https://client/callback"); - authorizationResponse.IsError.Should().BeFalse(); - authorizationResponse.Code.Should().NotBeNull(); + authorizationResponse.IsError.ShouldBeFalse(); + authorizationResponse.Code.ShouldNotBeNull(); var tokenResponse = await _mockPipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest { @@ -138,9 +138,9 @@ private async Task GetTokensAsync() RedirectUri = redirect_uri }); - tokenResponse.IsError.Should().BeFalse(); - tokenResponse.AccessToken.Should().NotBeNull(); - tokenResponse.RefreshToken.Should().NotBeNull(); + tokenResponse.IsError.ShouldBeFalse(); + tokenResponse.AccessToken.ShouldNotBeNull(); + tokenResponse.RefreshToken.ShouldNotBeNull(); return new Tokens(tokenResponse); } @@ -155,8 +155,8 @@ private async Task GetAccessTokenForImplicitClientAsync(string clientId) "api", "https://client/callback"); - authorizationResponse.IsError.Should().BeFalse(); - authorizationResponse.AccessToken.Should().NotBeNull(); + authorizationResponse.IsError.ShouldBeFalse(); + authorizationResponse.AccessToken.ShouldNotBeNull(); return authorizationResponse.AccessToken; } @@ -207,7 +207,7 @@ public async Task Get_request_should_return_405() { var response = await _mockPipeline.BackChannelClient.GetAsync(IdentityServerPipeline.RevocationEndpoint); - response.StatusCode.Should().Be(HttpStatusCode.MethodNotAllowed); + response.StatusCode.ShouldBe(HttpStatusCode.MethodNotAllowed); } [Fact] @@ -216,7 +216,7 @@ public async Task Post_without_form_urlencoded_should_return_415() { var response = await _mockPipeline.BackChannelClient.PostAsync(IdentityServerPipeline.RevocationEndpoint, null); - response.StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType); + response.StatusCode.ShouldBe(HttpStatusCode.UnsupportedMediaType); } [Fact] @@ -224,7 +224,7 @@ public async Task Post_without_form_urlencoded_should_return_415() public async Task Revoke_valid_access_token_should_return_success() { var tokens = await GetTokensAsync(); - (await IsAccessTokenValidAsync(tokens)).Should().BeTrue(); + (await IsAccessTokenValidAsync(tokens)).ShouldBeTrue(); var result = await _mockPipeline.BackChannelClient.RevokeTokenAsync(new TokenRevocationRequest { @@ -235,8 +235,8 @@ public async Task Revoke_valid_access_token_should_return_success() Token = tokens.AccessToken }); - result.IsError.Should().BeFalse(); - (await IsAccessTokenValidAsync(tokens)).Should().BeFalse(); + result.IsError.ShouldBeFalse(); + (await IsAccessTokenValidAsync(tokens)).ShouldBeFalse(); } [Fact] @@ -244,7 +244,7 @@ public async Task Revoke_valid_access_token_should_return_success() public async Task Revoke_valid_access_token_belonging_to_another_client_should_return_success_but_not_revoke_token() { var tokens = await GetTokensAsync(); - (await IsAccessTokenValidAsync(tokens)).Should().BeTrue(); + (await IsAccessTokenValidAsync(tokens)).ShouldBeTrue(); var result = await _mockPipeline.BackChannelClient.RevokeTokenAsync(new TokenRevocationRequest { @@ -255,8 +255,8 @@ public async Task Revoke_valid_access_token_belonging_to_another_client_should_r Token = tokens.AccessToken }); - result.IsError.Should().BeFalse(); - (await IsAccessTokenValidAsync(tokens)).Should().BeTrue(); + result.IsError.ShouldBeFalse(); + (await IsAccessTokenValidAsync(tokens)).ShouldBeTrue(); } [Fact] @@ -264,7 +264,7 @@ public async Task Revoke_valid_access_token_belonging_to_another_client_should_r public async Task Revoke_valid_refresh_token_should_return_success() { var tokens = await GetTokensAsync(); - (await UseRefreshTokenAsync(tokens)).Should().BeTrue(); + (await UseRefreshTokenAsync(tokens)).ShouldBeTrue(); var result = await _mockPipeline.BackChannelClient.RevokeTokenAsync(new TokenRevocationRequest { @@ -275,9 +275,9 @@ public async Task Revoke_valid_refresh_token_should_return_success() Token = tokens.RefreshToken }); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); - (await UseRefreshTokenAsync(tokens)).Should().BeFalse(); + (await UseRefreshTokenAsync(tokens)).ShouldBeFalse(); } [Fact] @@ -285,7 +285,7 @@ public async Task Revoke_valid_refresh_token_should_return_success() public async Task Revoke_valid_refresh_token_belonging_to_another_client_should_return_success_but_not_revoke_token() { var tokens = await GetTokensAsync(); - (await UseRefreshTokenAsync(tokens)).Should().BeTrue(); + (await UseRefreshTokenAsync(tokens)).ShouldBeTrue(); var result = await _mockPipeline.BackChannelClient.RevokeTokenAsync(new TokenRevocationRequest { @@ -296,9 +296,9 @@ public async Task Revoke_valid_refresh_token_belonging_to_another_client_should_ Token = tokens.RefreshToken }); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); - (await UseRefreshTokenAsync(tokens)).Should().BeTrue(); + (await UseRefreshTokenAsync(tokens)).ShouldBeTrue(); } [Fact] @@ -309,8 +309,8 @@ public async Task Revoke_valid_refresh_token_belonging_to_another_session_should await _mockPipeline.LogoutAsync(); var tokens2 = await GetTokensAsync(); - (await IsAccessTokenValidAsync(tokens1)).Should().BeTrue(); - (await IsAccessTokenValidAsync(tokens2)).Should().BeTrue(); + (await IsAccessTokenValidAsync(tokens1)).ShouldBeTrue(); + (await IsAccessTokenValidAsync(tokens2)).ShouldBeTrue(); var result = await _mockPipeline.BackChannelClient.RevokeTokenAsync(new TokenRevocationRequest { @@ -321,10 +321,10 @@ public async Task Revoke_valid_refresh_token_belonging_to_another_session_should Token = tokens1.RefreshToken }); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); - (await IsAccessTokenValidAsync(tokens1)).Should().BeFalse(); - (await IsAccessTokenValidAsync(tokens2)).Should().BeTrue(); + (await IsAccessTokenValidAsync(tokens1)).ShouldBeFalse(); + (await IsAccessTokenValidAsync(tokens2)).ShouldBeTrue(); } [Fact] @@ -332,7 +332,7 @@ public async Task Revoke_valid_refresh_token_belonging_to_another_session_should public async Task Revoke_invalid_access_token_should_return_success() { var tokens = await GetTokensAsync(); - (await IsAccessTokenValidAsync(tokens)).Should().BeTrue(); + (await IsAccessTokenValidAsync(tokens)).ShouldBeTrue(); var result = await _mockPipeline.BackChannelClient.RevokeTokenAsync(new TokenRevocationRequest { @@ -343,9 +343,9 @@ public async Task Revoke_invalid_access_token_should_return_success() Token = tokens.AccessToken }); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); - (await IsAccessTokenValidAsync(tokens)).Should().BeFalse(); + (await IsAccessTokenValidAsync(tokens)).ShouldBeFalse(); result = await _mockPipeline.BackChannelClient.RevokeTokenAsync(new TokenRevocationRequest { @@ -356,7 +356,7 @@ public async Task Revoke_invalid_access_token_should_return_success() Token = tokens.AccessToken }); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -364,7 +364,7 @@ public async Task Revoke_invalid_access_token_should_return_success() public async Task Revoke_invalid_refresh_token_should_return_success() { var tokens = await GetTokensAsync(); - (await UseRefreshTokenAsync(tokens)).Should().BeTrue(); + (await UseRefreshTokenAsync(tokens)).ShouldBeTrue(); var result = await _mockPipeline.BackChannelClient.RevokeTokenAsync(new TokenRevocationRequest { @@ -375,9 +375,9 @@ public async Task Revoke_invalid_refresh_token_should_return_success() Token = tokens.RefreshToken }); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); - (await UseRefreshTokenAsync(tokens)).Should().BeFalse(); + (await UseRefreshTokenAsync(tokens)).ShouldBeFalse(); result = await _mockPipeline.BackChannelClient.RevokeTokenAsync(new TokenRevocationRequest { @@ -388,7 +388,7 @@ public async Task Revoke_invalid_refresh_token_should_return_success() Token = tokens.RefreshToken }); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -396,7 +396,7 @@ public async Task Revoke_invalid_refresh_token_should_return_success() public async Task Invalid_client_id_should_return_error() { var tokens = await GetTokensAsync(); - (await IsAccessTokenValidAsync(tokens)).Should().BeTrue(); + (await IsAccessTokenValidAsync(tokens)).ShouldBeTrue(); var result = await _mockPipeline.BackChannelClient.RevokeTokenAsync(new TokenRevocationRequest { @@ -407,8 +407,8 @@ public async Task Invalid_client_id_should_return_error() Token = tokens.AccessToken }); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_client"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_client"); } [Fact] @@ -416,7 +416,7 @@ public async Task Invalid_client_id_should_return_error() public async Task Invalid_credentials_should_return_error() { var tokens = await GetTokensAsync(); - (await IsAccessTokenValidAsync(tokens)).Should().BeTrue(); + (await IsAccessTokenValidAsync(tokens)).ShouldBeTrue(); var result = await _mockPipeline.BackChannelClient.RevokeTokenAsync(new TokenRevocationRequest { @@ -427,8 +427,8 @@ public async Task Invalid_credentials_should_return_error() Token = tokens.AccessToken }); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_client"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_client"); } [Fact] @@ -442,11 +442,11 @@ public async Task Missing_token_should_return_error() }; var response = await _mockPipeline.BackChannelClient.PostAsync(IdentityServerPipeline.RevocationEndpoint, new FormUrlEncodedContent(data)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var result = await ProtocolResponse.FromHttpResponseAsync(response); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_request"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_request"); } [Fact] @@ -454,7 +454,7 @@ public async Task Missing_token_should_return_error() public async Task Invalid_token_type_hint_should_return_error() { var tokens = await GetTokensAsync(); - (await IsAccessTokenValidAsync(tokens)).Should().BeTrue(); + (await IsAccessTokenValidAsync(tokens)).ShouldBeTrue(); var data = new Dictionary { @@ -465,11 +465,11 @@ public async Task Invalid_token_type_hint_should_return_error() }; var response = await _mockPipeline.BackChannelClient.PostAsync(IdentityServerPipeline.RevocationEndpoint, new FormUrlEncodedContent(data)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var result = await ProtocolResponse.FromHttpResponseAsync(response); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("unsupported_token_type"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("unsupported_token_type"); } [Fact] @@ -477,7 +477,7 @@ public async Task Invalid_token_type_hint_should_return_error() public async Task Valid_access_token_but_missing_token_type_hint_should_succeed() { var tokens = await GetTokensAsync(); - (await IsAccessTokenValidAsync(tokens)).Should().BeTrue(); + (await IsAccessTokenValidAsync(tokens)).ShouldBeTrue(); var data = new Dictionary { @@ -487,9 +487,9 @@ public async Task Valid_access_token_but_missing_token_type_hint_should_succeed( }; var response = await _mockPipeline.BackChannelClient.PostAsync(IdentityServerPipeline.RevocationEndpoint, new FormUrlEncodedContent(data)); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); - (await IsAccessTokenValidAsync(tokens)).Should().BeFalse(); + (await IsAccessTokenValidAsync(tokens)).ShouldBeFalse(); } [Fact] @@ -497,7 +497,7 @@ public async Task Valid_access_token_but_missing_token_type_hint_should_succeed( public async Task Valid_refresh_token_but_missing_token_type_hint_should_succeed() { var tokens = await GetTokensAsync(); - (await UseRefreshTokenAsync(tokens)).Should().BeTrue(); + (await UseRefreshTokenAsync(tokens)).ShouldBeTrue(); var data = new Dictionary { @@ -507,9 +507,9 @@ public async Task Valid_refresh_token_but_missing_token_type_hint_should_succeed }; var response = await _mockPipeline.BackChannelClient.PostAsync(IdentityServerPipeline.RevocationEndpoint, new FormUrlEncodedContent(data)); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); - (await UseRefreshTokenAsync(tokens)).Should().BeFalse(); + (await UseRefreshTokenAsync(tokens)).ShouldBeFalse(); } [Fact] @@ -524,11 +524,11 @@ public async Task Implicit_client_without_secret_revoking_token_should_succeed() { "token", token } }; - (await IsAccessTokenValidAsync(token)).Should().BeTrue(); + (await IsAccessTokenValidAsync(token)).ShouldBeTrue(); var response = await _mockPipeline.BackChannelClient.PostAsync(IdentityServerPipeline.RevocationEndpoint, new FormUrlEncodedContent(data)); - response.StatusCode.Should().Be(HttpStatusCode.OK); - (await IsAccessTokenValidAsync(token)).Should().BeFalse(); + response.StatusCode.ShouldBe(HttpStatusCode.OK); + (await IsAccessTokenValidAsync(token)).ShouldBeFalse(); } [Fact] @@ -543,10 +543,10 @@ public async Task Implicit_and_client_creds_client_without_secret_revoking_token { "token", token } }; - (await IsAccessTokenValidAsync(token)).Should().BeTrue(); + (await IsAccessTokenValidAsync(token)).ShouldBeTrue(); var response = await _mockPipeline.BackChannelClient.PostAsync(IdentityServerPipeline.RevocationEndpoint, new FormUrlEncodedContent(data)); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); - (await IsAccessTokenValidAsync(token)).Should().BeTrue(); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); + (await IsAccessTokenValidAsync(token)).ShouldBeTrue(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/CibaTokenEndpointTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/CibaTokenEndpointTests.cs index a0229e3f7..ae066a141 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/CibaTokenEndpointTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/CibaTokenEndpointTests.cs @@ -2,7 +2,7 @@ // See LICENSE in the project root for license information. -using FluentAssertions; +using Shouldly; using System.Collections.Generic; using System.Net; using System.Net.Http; @@ -146,7 +146,7 @@ public async Task valid_request_should_return_valid_result() var cibaResponse = await _mockPipeline.BackChannelClient.PostAsync( IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(cibaBody)); - cibaResponse.StatusCode.Should().Be(HttpStatusCode.OK); + cibaResponse.StatusCode.ShouldBe(HttpStatusCode.OK); // user auth/consent @@ -180,7 +180,7 @@ await cibaService.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest( IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.OK); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.OK); } @@ -204,7 +204,7 @@ public async Task request_before_consent_should_return_error() var cibaResponse = await _mockPipeline.BackChannelClient.PostAsync( IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(cibaBody)); - cibaResponse.StatusCode.Should().Be(HttpStatusCode.OK); + cibaResponse.StatusCode.ShouldBe(HttpStatusCode.OK); @@ -224,13 +224,13 @@ public async Task request_before_consent_should_return_error() IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("authorization_pending"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("authorization_pending"); } [Fact] @@ -253,7 +253,7 @@ public async Task client_mismatch_should_return_error() var cibaResponse = await _mockPipeline.BackChannelClient.PostAsync( IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(cibaBody)); - cibaResponse.StatusCode.Should().Be(HttpStatusCode.OK); + cibaResponse.StatusCode.ShouldBe(HttpStatusCode.OK); // user auth/consent @@ -287,13 +287,13 @@ await cibaService.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest( IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_grant"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_grant"); } [Fact] @@ -316,7 +316,7 @@ public async Task client_not_allowed_for_ciba_should_return_error() var cibaResponse = await _mockPipeline.BackChannelClient.PostAsync( IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(cibaBody)); - cibaResponse.StatusCode.Should().Be(HttpStatusCode.OK); + cibaResponse.StatusCode.ShouldBe(HttpStatusCode.OK); // user auth/consent @@ -350,13 +350,13 @@ await cibaService.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest( IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("unauthorized_client"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("unauthorized_client"); } [Fact] @@ -379,7 +379,7 @@ public async Task user_denies_consent_should_return_error() var cibaResponse = await _mockPipeline.BackChannelClient.PostAsync( IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(cibaBody)); - cibaResponse.StatusCode.Should().Be(HttpStatusCode.OK); + cibaResponse.StatusCode.ShouldBe(HttpStatusCode.OK); // user auth/consent @@ -413,13 +413,13 @@ await cibaService.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest( IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("access_denied"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("access_denied"); } [Fact] @@ -442,7 +442,7 @@ public async Task user_inactive_should_return_error() var cibaResponse = await _mockPipeline.BackChannelClient.PostAsync( IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(cibaBody)); - cibaResponse.StatusCode.Should().Be(HttpStatusCode.OK); + cibaResponse.StatusCode.ShouldBe(HttpStatusCode.OK); // user auth/consent @@ -478,13 +478,13 @@ await cibaService.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest( IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("invalid_grant"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("invalid_grant"); } [Fact] @@ -511,7 +511,7 @@ public async Task expired_request_should_return_error() var cibaResponse = await _mockPipeline.BackChannelClient.PostAsync( IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(cibaBody)); - cibaResponse.StatusCode.Should().Be(HttpStatusCode.OK); + cibaResponse.StatusCode.ShouldBe(HttpStatusCode.OK); // user auth/consent @@ -547,13 +547,13 @@ await cibaService.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest( IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("expired_token"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("expired_token"); } [Fact] @@ -580,7 +580,7 @@ public async Task too_frequent_request_should_return_error() var cibaResponse = await _mockPipeline.BackChannelClient.PostAsync( IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(cibaBody)); - cibaResponse.StatusCode.Should().Be(HttpStatusCode.OK); + cibaResponse.StatusCode.ShouldBe(HttpStatusCode.OK); // token request @@ -600,13 +600,13 @@ public async Task too_frequent_request_should_return_error() IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("authorization_pending"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("authorization_pending"); } { var tokenBody = new Dictionary @@ -621,13 +621,13 @@ public async Task too_frequent_request_should_return_error() IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("slow_down"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("slow_down"); } } @@ -655,7 +655,7 @@ public async Task calls_past_interval_should_reset_throttling() var cibaResponse = await _mockPipeline.BackChannelClient.PostAsync( IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(cibaBody)); - cibaResponse.StatusCode.Should().Be(HttpStatusCode.OK); + cibaResponse.StatusCode.ShouldBe(HttpStatusCode.OK); // token request @@ -675,13 +675,13 @@ public async Task calls_past_interval_should_reset_throttling() IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("authorization_pending"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("authorization_pending"); } { var tokenBody = new Dictionary @@ -696,13 +696,13 @@ public async Task calls_past_interval_should_reset_throttling() IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("slow_down"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("slow_down"); } clock.UtcNow = clock.UtcNow.AddSeconds(_mockPipeline.Options.Ciba.DefaultPollingInterval); @@ -720,13 +720,13 @@ public async Task calls_past_interval_should_reset_throttling() IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("authorization_pending"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("authorization_pending"); } { var tokenBody = new Dictionary @@ -741,13 +741,13 @@ public async Task calls_past_interval_should_reset_throttling() IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("slow_down"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("slow_down"); } } @@ -777,7 +777,7 @@ public async Task client_polling_interval_should_be_honored() var cibaResponse = await _mockPipeline.BackChannelClient.PostAsync( IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(cibaBody)); - cibaResponse.StatusCode.Should().Be(HttpStatusCode.OK); + cibaResponse.StatusCode.ShouldBe(HttpStatusCode.OK); // token request @@ -797,13 +797,13 @@ public async Task client_polling_interval_should_be_honored() IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("authorization_pending"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("authorization_pending"); } { var tokenBody = new Dictionary @@ -818,13 +818,13 @@ public async Task client_polling_interval_should_be_honored() IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("slow_down"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("slow_down"); } clock.UtcNow = clock.UtcNow.AddSeconds(6); @@ -842,13 +842,13 @@ public async Task client_polling_interval_should_be_honored() IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("slow_down"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("slow_down"); } clock.UtcNow = clock.UtcNow.AddSeconds(10); @@ -866,13 +866,13 @@ public async Task client_polling_interval_should_be_honored() IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("authorization_pending"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("authorization_pending"); } { var tokenBody = new Dictionary @@ -887,13 +887,13 @@ public async Task client_polling_interval_should_be_honored() IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("slow_down"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("slow_down"); } } @@ -923,7 +923,7 @@ public async Task client_lifetime_should_be_honored() var cibaResponse = await _mockPipeline.BackChannelClient.PostAsync( IdentityServerPipeline.BackchannelAuthenticationEndpoint, new FormUrlEncodedContent(cibaBody)); - cibaResponse.StatusCode.Should().Be(HttpStatusCode.OK); + cibaResponse.StatusCode.ShouldBe(HttpStatusCode.OK); // token request @@ -943,13 +943,13 @@ public async Task client_lifetime_should_be_honored() IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("authorization_pending"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("authorization_pending"); } clock.UtcNow = clock.UtcNow.AddSeconds(_cibaClient.CibaLifetime.Value + 1); @@ -967,13 +967,13 @@ public async Task client_lifetime_should_be_honored() IdentityServerPipeline.TokenEndpoint, new FormUrlEncodedContent(tokenBody)); - tokenResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await tokenResponse.Content.ReadAsStringAsync(); values = JsonSerializer.Deserialize>(json); - values.ContainsKey("error").Should().BeTrue(); - values["error"].ToString().Should().Be("expired_token"); + values.ContainsKey("error").ShouldBeTrue(); + values["error"].ToString().ShouldBe("expired_token"); } } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/DPoPTokenEndpointTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/DPoPTokenEndpointTests.cs index 626e9a33b..99dbced1f 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/DPoPTokenEndpointTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/DPoPTokenEndpointTests.cs @@ -2,7 +2,7 @@ // See LICENSE in the project root for license information. -using FluentAssertions; +using Shouldly; using System.Collections.Generic; using System.Security.Claims; using System.Text.Json; @@ -211,7 +211,7 @@ string CreateDPoPProofToken(string alg = "RS256", SecurityKey key = null) private IEnumerable ParseAccessTokenClaims(TokenResponse tokenResponse) { - tokenResponse.IsError.Should().BeFalse(tokenResponse.Error); + tokenResponse.IsError.ShouldBeFalse(tokenResponse.Error); var handler = new JwtSecurityTokenHandler(); var token = handler.ReadJwtToken(tokenResponse.AccessToken); @@ -248,10 +248,10 @@ public async Task valid_dpop_request_should_return_bound_access_token() request.Headers.Add("DPoP", dpopToken); var response = await _mockPipeline.BackChannelClient.RequestClientCredentialsTokenAsync(request); - response.IsError.Should().BeFalse(); - response.TokenType.Should().Be("DPoP"); + response.IsError.ShouldBeFalse(); + response.TokenType.ShouldBe("DPoP"); var jkt = GetJKTFromAccessToken(response); - jkt.Should().Be(_JKT); + jkt.ShouldBe(_JKT); } [Fact] @@ -273,10 +273,10 @@ public async Task valid_dpop_request_with_unusual_but_valid_proof_token_should_r request.Headers.Add("DPoP", dpopToken); var response = await _mockPipeline.BackChannelClient.RequestClientCredentialsTokenAsync(request); - response.IsError.Should().BeFalse(); - response.TokenType.Should().Be("DPoP"); + response.IsError.ShouldBeFalse(); + response.TokenType.ShouldBe("DPoP"); var jkt = GetJKTFromAccessToken(response); - jkt.Should().Be(_JKT); + jkt.ShouldBe(_JKT); } [Fact] @@ -296,7 +296,7 @@ public async Task dpop_proof_token_too_long_should_fail() request.Headers.Add("DPoP", dpopToken); var response = await _mockPipeline.BackChannelClient.RequestClientCredentialsTokenAsync(request); - response.IsError.Should().BeTrue(); + response.IsError.ShouldBeTrue(); } [Fact] @@ -316,10 +316,10 @@ public async Task replayed_dpop_token_should_fail() request.Headers.Add("DPoP", dpopToken); var response = await _mockPipeline.BackChannelClient.RequestClientCredentialsTokenAsync(request); - response.IsError.Should().BeFalse(); - response.TokenType.Should().Be("DPoP"); + response.IsError.ShouldBeFalse(); + response.TokenType.ShouldBe("DPoP"); var jkt = GetJKTFromAccessToken(response); - jkt.Should().Be(_JKT); + jkt.ShouldBe(_JKT); } { @@ -333,7 +333,7 @@ public async Task replayed_dpop_token_should_fail() request.Headers.Add("DPoP", dpopToken); var response = await _mockPipeline.BackChannelClient.RequestClientCredentialsTokenAsync(request); - response.IsError.Should().BeTrue(); + response.IsError.ShouldBeTrue(); } } @@ -351,8 +351,8 @@ public async Task invalid_dpop_request_should_fail() request.Headers.Add("DPoP", "malformed"); var response = await _mockPipeline.BackChannelClient.RequestClientCredentialsTokenAsync(request); - response.IsError.Should().BeTrue(); - response.Error.Should().Be("invalid_dpop_proof"); + response.IsError.ShouldBeTrue(); + response.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -370,8 +370,8 @@ public async Task missing_dpop_token_when_required_should_fail() }; var response = await _mockPipeline.BackChannelClient.RequestClientCredentialsTokenAsync(request); - response.IsError.Should().BeTrue(); - response.Error.Should().Be("invalid_dpop_proof"); + response.IsError.ShouldBeTrue(); + response.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -390,8 +390,8 @@ public async Task multiple_dpop_tokens_should_fail() request.Headers.Add("DPoP", dpopToken); var response = await _mockPipeline.BackChannelClient.RequestClientCredentialsTokenAsync(request); - response.IsError.Should().BeTrue(); - response.Error.Should().Be("invalid_dpop_proof"); + response.IsError.ShouldBeTrue(); + response.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -410,11 +410,11 @@ public async Task valid_dpop_request_should_return_bound_refresh_token() redirectUri: "https://client1/callback"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client1/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client1/callback"); var authorization = new AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); + authorization.IsError.ShouldBeFalse(); var codeRequest = new AuthorizationCodeTokenRequest { @@ -427,9 +427,9 @@ public async Task valid_dpop_request_should_return_bound_refresh_token() codeRequest.Headers.Add("DPoP", CreateDPoPProofToken()); var codeResponse = await _mockPipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest); - codeResponse.IsError.Should().BeFalse(); - codeResponse.TokenType.Should().Be("DPoP"); - GetJKTFromAccessToken(codeResponse).Should().Be(_JKT); + codeResponse.IsError.ShouldBeFalse(); + codeResponse.TokenType.ShouldBe("DPoP"); + GetJKTFromAccessToken(codeResponse).ShouldBe(_JKT); var rtRequest = new RefreshTokenRequest { @@ -441,9 +441,9 @@ public async Task valid_dpop_request_should_return_bound_refresh_token() rtRequest.Headers.Add("DPoP", CreateDPoPProofToken()); var rtResponse = await _mockPipeline.BackChannelClient.RequestRefreshTokenAsync(rtRequest); - rtResponse.IsError.Should().BeFalse(); - rtResponse.TokenType.Should().Be("DPoP"); - GetJKTFromAccessToken(rtResponse).Should().Be(_JKT); + rtResponse.IsError.ShouldBeFalse(); + rtResponse.TokenType.ShouldBe("DPoP"); + GetJKTFromAccessToken(rtResponse).ShouldBe(_JKT); } [Fact] @@ -462,11 +462,11 @@ public async Task confidential_client_dpop_proof_should_be_required_on_renewal() redirectUri: "https://client1/callback"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client1/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client1/callback"); var authorization = new AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); + authorization.IsError.ShouldBeFalse(); var codeRequest = new AuthorizationCodeTokenRequest { @@ -479,9 +479,9 @@ public async Task confidential_client_dpop_proof_should_be_required_on_renewal() codeRequest.Headers.Add("DPoP", CreateDPoPProofToken()); var codeResponse = await _mockPipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest); - codeResponse.IsError.Should().BeFalse(); - codeResponse.TokenType.Should().Be("DPoP"); - GetJKTFromAccessToken(codeResponse).Should().Be(_JKT); + codeResponse.IsError.ShouldBeFalse(); + codeResponse.TokenType.ShouldBe("DPoP"); + GetJKTFromAccessToken(codeResponse).ShouldBe(_JKT); var rtRequest = new RefreshTokenRequest { @@ -493,8 +493,8 @@ public async Task confidential_client_dpop_proof_should_be_required_on_renewal() // no DPoP header passed here var rtResponse = await _mockPipeline.BackChannelClient.RequestRefreshTokenAsync(rtRequest); - rtResponse.IsError.Should().BeTrue(); - rtResponse.Error.Should().Be("invalid_request"); + rtResponse.IsError.ShouldBeTrue(); + rtResponse.Error.ShouldBe("invalid_request"); } [Fact] @@ -515,11 +515,11 @@ public async Task public_client_dpop_proof_should_be_required_on_renewal() redirectUri: "https://client1/callback"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client1/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client1/callback"); var authorization = new AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); + authorization.IsError.ShouldBeFalse(); var codeRequest = new AuthorizationCodeTokenRequest { @@ -532,9 +532,9 @@ public async Task public_client_dpop_proof_should_be_required_on_renewal() codeRequest.Headers.Add("DPoP", CreateDPoPProofToken()); var codeResponse = await _mockPipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest); - codeResponse.IsError.Should().BeFalse(); - codeResponse.TokenType.Should().Be("DPoP"); - GetJKTFromAccessToken(codeResponse).Should().Be(_JKT); + codeResponse.IsError.ShouldBeFalse(); + codeResponse.TokenType.ShouldBe("DPoP"); + GetJKTFromAccessToken(codeResponse).ShouldBe(_JKT); var rtRequest = new RefreshTokenRequest { @@ -546,8 +546,8 @@ public async Task public_client_dpop_proof_should_be_required_on_renewal() // no DPoP header passed here var rtResponse = await _mockPipeline.BackChannelClient.RequestRefreshTokenAsync(rtRequest); - rtResponse.IsError.Should().BeTrue(); - rtResponse.Error.Should().Be("invalid_request"); + rtResponse.IsError.ShouldBeTrue(); + rtResponse.Error.ShouldBe("invalid_request"); } [Fact] @@ -566,11 +566,11 @@ public async Task no_dpop_should_not_be_able_to_start_on_renewal() redirectUri: "https://client1/callback"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client1/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client1/callback"); var authorization = new AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); + authorization.IsError.ShouldBeFalse(); var codeRequest = new AuthorizationCodeTokenRequest { @@ -584,7 +584,7 @@ public async Task no_dpop_should_not_be_able_to_start_on_renewal() // no dpop here var codeResponse = await _mockPipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest); - codeResponse.IsError.Should().BeFalse(); + codeResponse.IsError.ShouldBeFalse(); var rtRequest = new RefreshTokenRequest { @@ -599,7 +599,7 @@ public async Task no_dpop_should_not_be_able_to_start_on_renewal() rtRequest.Headers.Add("DPoP", CreateDPoPProofToken()); var rtResponse = await _mockPipeline.BackChannelClient.RequestRefreshTokenAsync(rtRequest); - rtResponse.IsError.Should().BeTrue(); + rtResponse.IsError.ShouldBeTrue(); } [Fact] @@ -618,11 +618,11 @@ public async Task confidential_client_should_be_able_to_use_different_dpop_key_f redirectUri: "https://client1/callback"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client1/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client1/callback"); var authorization = new AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); + authorization.IsError.ShouldBeFalse(); var codeRequest = new AuthorizationCodeTokenRequest { @@ -635,9 +635,9 @@ public async Task confidential_client_should_be_able_to_use_different_dpop_key_f codeRequest.Headers.Add("DPoP", CreateDPoPProofToken()); var codeResponse = await _mockPipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest); - codeResponse.IsError.Should().BeFalse(); - codeResponse.TokenType.Should().Be("DPoP"); - GetJKTFromAccessToken(codeResponse).Should().Be(_JKT); + codeResponse.IsError.ShouldBeFalse(); + codeResponse.TokenType.ShouldBe("DPoP"); + GetJKTFromAccessToken(codeResponse).ShouldBe(_JKT); var rtRequest = new RefreshTokenRequest { @@ -651,9 +651,9 @@ public async Task confidential_client_should_be_able_to_use_different_dpop_key_f rtRequest.Headers.Add("DPoP", CreateDPoPProofToken()); var rtResponse = await _mockPipeline.BackChannelClient.RequestRefreshTokenAsync(rtRequest); - rtResponse.IsError.Should().BeFalse(); - rtResponse.TokenType.Should().Be("DPoP"); - GetJKTFromAccessToken(rtResponse).Should().Be(_JKT); + rtResponse.IsError.ShouldBeFalse(); + rtResponse.TokenType.ShouldBe("DPoP"); + GetJKTFromAccessToken(rtResponse).ShouldBe(_JKT); } [Fact] @@ -674,11 +674,11 @@ public async Task public_client_should_not_be_able_to_use_different_dpop_key_for redirectUri: "https://client1/callback"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client1/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client1/callback"); var authorization = new AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); + authorization.IsError.ShouldBeFalse(); var codeRequest = new AuthorizationCodeTokenRequest { @@ -691,9 +691,9 @@ public async Task public_client_should_not_be_able_to_use_different_dpop_key_for codeRequest.Headers.Add("DPoP", CreateDPoPProofToken()); var codeResponse = await _mockPipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest); - codeResponse.IsError.Should().BeFalse(); - codeResponse.TokenType.Should().Be("DPoP"); - GetJKTFromAccessToken(codeResponse).Should().Be(_JKT); + codeResponse.IsError.ShouldBeFalse(); + codeResponse.TokenType.ShouldBe("DPoP"); + GetJKTFromAccessToken(codeResponse).ShouldBe(_JKT); var rtRequest = new RefreshTokenRequest { @@ -711,8 +711,8 @@ public async Task public_client_should_not_be_able_to_use_different_dpop_key_for rtRequest.Headers.Add("DPoP", CreateDPoPProofToken()); var rtResponse = await _mockPipeline.BackChannelClient.RequestRefreshTokenAsync(rtRequest); - rtResponse.IsError.Should().BeTrue(); - rtResponse.Error.Should().Be("invalid_dpop_proof"); + rtResponse.IsError.ShouldBeTrue(); + rtResponse.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -733,11 +733,11 @@ public async Task public_client_using_same_dpop_key_for_refresh_token_request_sh redirectUri: "https://client1/callback"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client1/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client1/callback"); var authorization = new AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); + authorization.IsError.ShouldBeFalse(); var codeRequest = new AuthorizationCodeTokenRequest { @@ -750,9 +750,9 @@ public async Task public_client_using_same_dpop_key_for_refresh_token_request_sh codeRequest.Headers.Add("DPoP", CreateDPoPProofToken()); var codeResponse = await _mockPipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest); - codeResponse.IsError.Should().BeFalse(); - codeResponse.TokenType.Should().Be("DPoP"); - GetJKTFromAccessToken(codeResponse).Should().Be(_JKT); + codeResponse.IsError.ShouldBeFalse(); + codeResponse.TokenType.ShouldBe("DPoP"); + GetJKTFromAccessToken(codeResponse).ShouldBe(_JKT); var firstRefreshRequest = new RefreshTokenRequest { @@ -764,9 +764,9 @@ public async Task public_client_using_same_dpop_key_for_refresh_token_request_sh firstRefreshRequest.Headers.Add("DPoP", CreateDPoPProofToken()); var firstRefreshResponse = await _mockPipeline.BackChannelClient.RequestRefreshTokenAsync(firstRefreshRequest); - firstRefreshResponse.IsError.Should().BeFalse(); - firstRefreshResponse.TokenType.Should().Be("DPoP"); - GetJKTFromAccessToken(firstRefreshResponse).Should().Be(_JKT); + firstRefreshResponse.IsError.ShouldBeFalse(); + firstRefreshResponse.TokenType.ShouldBe("DPoP"); + GetJKTFromAccessToken(firstRefreshResponse).ShouldBe(_JKT); var secondRefreshRequest = new RefreshTokenRequest { @@ -777,13 +777,13 @@ public async Task public_client_using_same_dpop_key_for_refresh_token_request_sh }; secondRefreshRequest.Headers.Add("DPoP", CreateDPoPProofToken()); - firstRefreshRequest.Headers.GetValues("DPoP").FirstOrDefault().Should().NotBe( + firstRefreshRequest.Headers.GetValues("DPoP").FirstOrDefault().ShouldNotBe( secondRefreshRequest.Headers.GetValues("DPoP").FirstOrDefault()); var secondRefreshResponse = await _mockPipeline.BackChannelClient.RequestRefreshTokenAsync(secondRefreshRequest); - secondRefreshResponse.IsError.Should().BeFalse(secondRefreshResponse.Error); - secondRefreshResponse.TokenType.Should().Be("DPoP"); - GetJKTFromAccessToken(secondRefreshResponse).Should().Be(_JKT); + secondRefreshResponse.IsError.ShouldBeFalse(secondRefreshResponse.Error); + secondRefreshResponse.TokenType.ShouldBe("DPoP"); + GetJKTFromAccessToken(secondRefreshResponse).ShouldBe(_JKT); } @@ -805,11 +805,11 @@ public async Task missing_proof_token_when_required_on_refresh_token_request_sho redirectUri: "https://client1/callback"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client1/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client1/callback"); var authorization = new AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); + authorization.IsError.ShouldBeFalse(); var codeRequest = new AuthorizationCodeTokenRequest { @@ -822,9 +822,9 @@ public async Task missing_proof_token_when_required_on_refresh_token_request_sho codeRequest.Headers.Add("DPoP", CreateDPoPProofToken()); var codeResponse = await _mockPipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest); - codeResponse.IsError.Should().BeFalse(); - codeResponse.TokenType.Should().Be("DPoP"); - GetJKTFromAccessToken(codeResponse).Should().Be(_JKT); + codeResponse.IsError.ShouldBeFalse(); + codeResponse.TokenType.ShouldBe("DPoP"); + GetJKTFromAccessToken(codeResponse).ShouldBe(_JKT); var rtRequest = new RefreshTokenRequest { @@ -835,8 +835,8 @@ public async Task missing_proof_token_when_required_on_refresh_token_request_sho }; var rtResponse = await _mockPipeline.BackChannelClient.RequestRefreshTokenAsync(rtRequest); - rtResponse.IsError.Should().BeTrue(); - rtResponse.Error.Should().Be("invalid_dpop_proof"); + rtResponse.IsError.ShouldBeTrue(); + rtResponse.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -857,11 +857,11 @@ public async Task valid_dpop_request_using_reference_token_at_introspection_shou redirectUri: "https://client1/callback"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client1/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client1/callback"); var authorization = new AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); + authorization.IsError.ShouldBeFalse(); var codeRequest = new AuthorizationCodeTokenRequest { @@ -883,8 +883,8 @@ public async Task valid_dpop_request_using_reference_token_at_introspection_shou Token = codeResponse.AccessToken, }; var introspectionResponse = await _mockPipeline.BackChannelClient.IntrospectTokenAsync(introspectionRequest); - introspectionResponse.IsError.Should().BeFalse(); - GetJKTFromCnfClaim(introspectionResponse.Claims).Should().Be(_JKT); + introspectionResponse.IsError.ShouldBeFalse(); + GetJKTFromCnfClaim(introspectionResponse.Claims).ShouldBe(_JKT); } [Fact] @@ -903,11 +903,11 @@ public async Task valid_dpop_request_using_jwt_at_introspection_should_return_bi redirectUri: "https://client1/callback"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client1/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client1/callback"); var authorization = new AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); + authorization.IsError.ShouldBeFalse(); var codeRequest = new AuthorizationCodeTokenRequest { @@ -929,8 +929,8 @@ public async Task valid_dpop_request_using_jwt_at_introspection_should_return_bi Token = codeResponse.AccessToken, }; var introspectionResponse = await _mockPipeline.BackChannelClient.IntrospectTokenAsync(introspectionRequest); - introspectionResponse.IsError.Should().BeFalse(); - GetJKTFromCnfClaim(introspectionResponse.Claims).Should().Be(_JKT); + introspectionResponse.IsError.ShouldBeFalse(); + GetJKTFromCnfClaim(introspectionResponse.Claims).ShouldBe(_JKT); } [Fact] @@ -953,11 +953,11 @@ public async Task matching_dpop_key_thumbprint_on_authorize_endpoint_and_token_e }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client1/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client1/callback"); var authorization = new AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); + authorization.IsError.ShouldBeFalse(); var codeRequest = new AuthorizationCodeTokenRequest { @@ -970,8 +970,8 @@ public async Task matching_dpop_key_thumbprint_on_authorize_endpoint_and_token_e codeRequest.Headers.Add("DPoP", CreateDPoPProofToken()); var codeResponse = await _mockPipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest); - codeResponse.IsError.Should().BeFalse(); - GetJKTFromAccessToken(codeResponse).Should().Be(_JKT); + codeResponse.IsError.ShouldBeFalse(); + GetJKTFromAccessToken(codeResponse).ShouldBe(_JKT); } [Fact] @@ -994,7 +994,7 @@ public async Task dpop_key_thumbprint_too_long_should_fail() }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.ErrorWasCalled.Should().BeTrue(); + _mockPipeline.ErrorWasCalled.ShouldBeTrue(); } [Fact] @@ -1017,11 +1017,11 @@ public async Task mismatched_dpop_key_thumbprint_on_authorize_endpoint_and_token }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client1/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client1/callback"); var authorization = new AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); + authorization.IsError.ShouldBeFalse(); var codeRequest = new AuthorizationCodeTokenRequest { @@ -1034,8 +1034,8 @@ public async Task mismatched_dpop_key_thumbprint_on_authorize_endpoint_and_token codeRequest.Headers.Add("DPoP", CreateDPoPProofToken()); var codeResponse = await _mockPipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest); - codeResponse.IsError.Should().BeTrue(); - codeResponse.Error.Should().Be("invalid_dpop_proof"); + codeResponse.IsError.ShouldBeTrue(); + codeResponse.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -1072,11 +1072,11 @@ public async Task server_issued_nonce_should_be_emitted() }); var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client1/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client1/callback"); var authorization = new AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); + authorization.IsError.ShouldBeFalse(); var codeRequest = new AuthorizationCodeTokenRequest { @@ -1091,9 +1091,9 @@ public async Task server_issued_nonce_should_be_emitted() nonce = "nonce"; var codeResponse = await _mockPipeline.BackChannelClient.RequestAuthorizationCodeTokenAsync(codeRequest); - codeResponse.IsError.Should().BeTrue(); - codeResponse.Error.Should().Be("invalid_dpop_proof"); - codeResponse.HttpResponse.Headers.GetValues("DPoP-Nonce").Single().Should().Be("nonce"); + codeResponse.IsError.ShouldBeTrue(); + codeResponse.Error.ShouldBe("invalid_dpop_proof"); + codeResponse.HttpResponse.Headers.GetValues("DPoP-Nonce").Single().ShouldBe("nonce"); // TODO: make IdentityModel expose the response headers? } @@ -1142,10 +1142,10 @@ public async Task different_rsa_proof_tokens_should_work(string alg) request.Headers.Add("DPoP", proofToken); var response = await _mockPipeline.BackChannelClient.RequestClientCredentialsTokenAsync(request); - response.IsError.Should().BeFalse(); - response.TokenType.Should().Be("DPoP"); + response.IsError.ShouldBeFalse(); + response.TokenType.ShouldBe("DPoP"); var jkt = GetJKTFromAccessToken(response); - jkt.Should().Be(_JKT); + jkt.ShouldBe(_JKT); } [Theory] @@ -1168,10 +1168,10 @@ public async Task different_ps_proof_tokens_should_work(string alg) request.Headers.Add("DPoP", proofToken); var response = await _mockPipeline.BackChannelClient.RequestClientCredentialsTokenAsync(request); - response.IsError.Should().BeFalse(); - response.TokenType.Should().Be("DPoP"); + response.IsError.ShouldBeFalse(); + response.TokenType.ShouldBe("DPoP"); var jkt = GetJKTFromAccessToken(response); - jkt.Should().Be(_JKT); + jkt.ShouldBe(_JKT); } } diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/RefreshTokenTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/RefreshTokenTests.cs index 532e510c9..ca3b93a17 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/RefreshTokenTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/RefreshTokenTests.cs @@ -2,7 +2,7 @@ // See LICENSE in the project root for license information. -using FluentAssertions; +using Shouldly; using System.Collections.Generic; using System.Net.Http; using System.Security.Claims; @@ -81,7 +81,7 @@ public async Task sid_should_be_in_access_token_after_token_is_renewed() responseType: "code", scope: "openid scope offline_access", redirectUri: "https://client/callback"); - authz.Code.Should().NotBeNull(); + authz.Code.ShouldNotBeNull(); var code = authz.Code; @@ -98,13 +98,13 @@ public async Task sid_should_be_in_access_token_after_token_is_renewed() RedirectUri = "https://client/callback" }); - tokenResult1.IsError.Should().BeFalse(); - tokenResult1.AccessToken.Should().NotBeNull(); + tokenResult1.IsError.ShouldBeFalse(); + tokenResult1.AccessToken.ShouldNotBeNull(); var payload1 = JsonSerializer.Deserialize(Base64Url.Decode(tokenResult1.AccessToken.Split('.')[1])); var sid1 = payload1.TryGetValue("sid").GetString(); - sid1.Should().Be(_mockPipeline.GetSessionCookie().Value); + sid1.ShouldBe(_mockPipeline.GetSessionCookie().Value); var tokenResult2 = await tokenClient.RequestRefreshTokenAsync(new RefreshTokenRequest { @@ -116,12 +116,12 @@ public async Task sid_should_be_in_access_token_after_token_is_renewed() RefreshToken = tokenResult1.RefreshToken }); - tokenResult2.IsError.Should().BeFalse(); - tokenResult2.AccessToken.Should().NotBeNull(); + tokenResult2.IsError.ShouldBeFalse(); + tokenResult2.AccessToken.ShouldNotBeNull(); var payload2 = JsonSerializer.Deserialize(Base64Url.Decode(tokenResult2.AccessToken.Split('.')[1])); var sid2 = payload2.TryGetValue("sid").GetString(); - sid1.Should().Be(sid2); + sid1.ShouldBe(sid2); } [Fact] @@ -139,7 +139,7 @@ public async Task when_UpdateAccessTokenClaimsOnRefresh_is_set_sid_should_be_in_ responseType: "code", scope: "openid scope offline_access", redirectUri: "https://client/callback"); - authz.Code.Should().NotBeNull(); + authz.Code.ShouldNotBeNull(); var code = authz.Code; @@ -156,13 +156,13 @@ public async Task when_UpdateAccessTokenClaimsOnRefresh_is_set_sid_should_be_in_ RedirectUri = "https://client/callback" }); - tokenResult1.IsError.Should().BeFalse(); - tokenResult1.AccessToken.Should().NotBeNull(); + tokenResult1.IsError.ShouldBeFalse(); + tokenResult1.AccessToken.ShouldNotBeNull(); var payload1 = JsonSerializer.Deserialize(Base64Url.Decode(tokenResult1.AccessToken.Split('.')[1])); var sid1 = payload1.TryGetValue("sid").GetString(); - sid1.Should().Be(_mockPipeline.GetSessionCookie().Value); + sid1.ShouldBe(_mockPipeline.GetSessionCookie().Value); var tokenResult2 = await tokenClient.RequestRefreshTokenAsync(new RefreshTokenRequest { @@ -174,11 +174,11 @@ public async Task when_UpdateAccessTokenClaimsOnRefresh_is_set_sid_should_be_in_ RefreshToken = tokenResult1.RefreshToken }); - tokenResult2.IsError.Should().BeFalse(); - tokenResult2.AccessToken.Should().NotBeNull(); + tokenResult2.IsError.ShouldBeFalse(); + tokenResult2.AccessToken.ShouldNotBeNull(); var payload2 = JsonSerializer.Deserialize(Base64Url.Decode(tokenResult2.AccessToken.Split('.')[1])); var sid2 = payload2.TryGetValue("sid").GetString(); - sid1.Should().Be(sid2); + sid1.ShouldBe(sid2); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/ResourceTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/ResourceTests.cs index f5c543eb9..e369055da 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/ResourceTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/ResourceTests.cs @@ -2,7 +2,7 @@ // See LICENSE in the project root for license information. -using FluentAssertions; +using Shouldly; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; @@ -74,7 +74,7 @@ public ResourceTests() ////////////////////////////////////////////////////////////////// private IEnumerable ParseAccessTokenClaims(TokenResponse tokenResponse) { - tokenResponse.IsError.Should().BeFalse(tokenResponse.Error); + tokenResponse.IsError.ShouldBeFalse(tokenResponse.Error); var handler = new JwtSecurityTokenHandler(); var token = handler.ReadJwtToken(tokenResponse.AccessToken); @@ -95,8 +95,8 @@ public async Task client_credentials_without_resource_without_scope_should_succe }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api1", "urn:api2" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "scope2", "scope3", "scope4" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api1", "urn:api2" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "scope2", "scope3", "scope4" }); } [Fact] [Trait("Category", Category)] @@ -115,8 +115,8 @@ public async Task client_credentials_with_resource_without_scope_should_succeed( }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api1" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "scope3" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api1" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "scope3" }); } { var tokenResponse = await _mockPipeline.BackChannelClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest @@ -131,8 +131,8 @@ public async Task client_credentials_with_resource_without_scope_should_succeed( }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api2" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope2" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api2" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope2" }); } { var tokenResponse = await _mockPipeline.BackChannelClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest @@ -147,8 +147,8 @@ public async Task client_credentials_with_resource_without_scope_should_succeed( }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api3" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "scope3" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api3" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "scope3" }); } } [Fact] @@ -164,8 +164,8 @@ public async Task client_credentials_without_resource_with_scope_should_succeed( }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api1" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api1" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1" }); } [Fact] [Trait("Category", Category)] @@ -185,8 +185,8 @@ public async Task client_credentials_with_resource_with_scope_should_succeed() }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api1" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api1" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1" }); } { var tokenResponse = await _mockPipeline.BackChannelClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest @@ -202,8 +202,8 @@ public async Task client_credentials_with_resource_with_scope_should_succeed() }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api3" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api3" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1" }); } } [Fact] @@ -222,8 +222,8 @@ public async Task client_credentials_with_invalid_resource_and_scope_should_fail { "resource", "urn:api2" } } }); - tokenResponse.IsError.Should().BeTrue(); - tokenResponse.Error.Should().Be("invalid_target"); + tokenResponse.IsError.ShouldBeTrue(); + tokenResponse.Error.ShouldBe("invalid_target"); } { var tokenResponse = await _mockPipeline.BackChannelClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest @@ -237,8 +237,8 @@ public async Task client_credentials_with_invalid_resource_and_scope_should_fail { "resource", "urn:api3" } } }); - tokenResponse.IsError.Should().BeTrue(); - tokenResponse.Error.Should().Be("invalid_target"); + tokenResponse.IsError.ShouldBeTrue(); + tokenResponse.Error.ShouldBe("invalid_target"); } { var tokenResponse = await _mockPipeline.BackChannelClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest @@ -252,8 +252,8 @@ public async Task client_credentials_with_invalid_resource_and_scope_should_fail { "resource", "urn:api4" } } }); - tokenResponse.IsError.Should().BeTrue(); - tokenResponse.Error.Should().Be("invalid_target"); + tokenResponse.IsError.ShouldBeTrue(); + tokenResponse.Error.ShouldBe("invalid_target"); } { var tokenResponse = await _mockPipeline.BackChannelClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest @@ -267,8 +267,8 @@ public async Task client_credentials_with_invalid_resource_and_scope_should_fail } }); - tokenResponse.IsError.Should().BeTrue(); - tokenResponse.Error.Should().Be("invalid_target"); + tokenResponse.IsError.ShouldBeTrue(); + tokenResponse.Error.ShouldBe("invalid_target"); } } @@ -289,8 +289,8 @@ public async Task client_credentials_with_empty_resource_should_be_treated_as_if }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api1", "urn:api2" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "scope2", "scope3", "scope4" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api1", "urn:api2" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "scope2", "scope3", "scope4" }); } [Fact] @@ -307,8 +307,8 @@ public async Task refresh_token_requested_without_resource_without_scope_should_ }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api1", "urn:api2" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "scope2", "scope3", "scope4", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api1", "urn:api2" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "scope2", "scope3", "scope4", "offline_access" }); } [Fact] [Trait("Category", Category)] @@ -329,8 +329,8 @@ public async Task refresh_token_requested_with_resource_without_scope_should_suc }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api1" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "scope3", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api1" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "scope3", "offline_access" }); } { @@ -348,8 +348,8 @@ public async Task refresh_token_requested_with_resource_without_scope_should_suc }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api2" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope2", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api2" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope2", "offline_access" }); } { @@ -367,8 +367,8 @@ public async Task refresh_token_requested_with_resource_without_scope_should_suc }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api3" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "scope3", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api3" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "scope3", "offline_access" }); } } [Fact] @@ -386,8 +386,8 @@ public async Task refresh_token_requested_without_resource_with_scope_should_suc }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api1" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api1" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "offline_access" }); } [Fact] [Trait("Category", Category)] @@ -409,8 +409,8 @@ public async Task refresh_token_requested_with_resource_with_scope_should_succee }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api1" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api1" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "offline_access" }); } { var tokenResponse = await _mockPipeline.BackChannelClient.RequestPasswordTokenAsync(new PasswordTokenRequest @@ -428,8 +428,8 @@ public async Task refresh_token_requested_with_resource_with_scope_should_succee }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api3" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api3" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "offline_access" }); } } [Fact] @@ -450,8 +450,8 @@ public async Task refresh_token_requested_with_invalid_resource_and_scope_should { "resource", "urn:api2" } } }); - tokenResponse.IsError.Should().BeTrue(); - tokenResponse.Error.Should().Be("invalid_target"); + tokenResponse.IsError.ShouldBeTrue(); + tokenResponse.Error.ShouldBe("invalid_target"); } { var tokenResponse = await _mockPipeline.BackChannelClient.RequestPasswordTokenAsync(new PasswordTokenRequest @@ -467,8 +467,8 @@ public async Task refresh_token_requested_with_invalid_resource_and_scope_should { "resource", "urn:api3" } } }); - tokenResponse.IsError.Should().BeTrue(); - tokenResponse.Error.Should().Be("invalid_target"); + tokenResponse.IsError.ShouldBeTrue(); + tokenResponse.Error.ShouldBe("invalid_target"); } { var tokenResponse = await _mockPipeline.BackChannelClient.RequestPasswordTokenAsync(new PasswordTokenRequest @@ -484,8 +484,8 @@ public async Task refresh_token_requested_with_invalid_resource_and_scope_should { "resource", "urn:api4" } } }); - tokenResponse.IsError.Should().BeTrue(); - tokenResponse.Error.Should().Be("invalid_target"); + tokenResponse.IsError.ShouldBeTrue(); + tokenResponse.Error.ShouldBe("invalid_target"); } { var tokenResponse = await _mockPipeline.BackChannelClient.RequestPasswordTokenAsync(new PasswordTokenRequest @@ -502,8 +502,8 @@ public async Task refresh_token_requested_with_invalid_resource_and_scope_should } }); - tokenResponse.IsError.Should().BeTrue(); - tokenResponse.Error.Should().Be("invalid_target"); + tokenResponse.IsError.ShouldBeTrue(); + tokenResponse.Error.ShouldBe("invalid_target"); } } @@ -532,8 +532,8 @@ public async Task refresh_token_exchange_with_resource_should_succeed() }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api1", "urn:api2" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "scope2", "scope3", "scope4", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api1", "urn:api2" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "scope2", "scope3", "scope4", "offline_access" }); } { tokenResponse = await _mockPipeline.BackChannelClient.RequestRefreshTokenAsync(new RefreshTokenRequest @@ -549,8 +549,8 @@ public async Task refresh_token_exchange_with_resource_should_succeed() }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api1" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "scope3", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api1" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "scope3", "offline_access" }); } { tokenResponse = await _mockPipeline.BackChannelClient.RequestRefreshTokenAsync(new RefreshTokenRequest @@ -566,8 +566,8 @@ public async Task refresh_token_exchange_with_resource_should_succeed() }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api2" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope2", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api2" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope2", "offline_access" }); } { tokenResponse = await _mockPipeline.BackChannelClient.RequestRefreshTokenAsync(new RefreshTokenRequest @@ -583,8 +583,8 @@ public async Task refresh_token_exchange_with_resource_should_succeed() }); var claims = ParseAccessTokenClaims(tokenResponse); - claims.Where(x => x.Type == "aud").Select(x => x.Value).Should().BeEquivalentTo(new[] { "urn:api3" }); - claims.Where(x => x.Type == "scope").Select(x => x.Value).Should().BeEquivalentTo(new[] { "scope1", "scope3", "offline_access" }); + claims.Where(x => x.Type == "aud").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "urn:api3" }); + claims.Where(x => x.Type == "scope").Select(x => x.Value).ShouldBeEquivalentTo(new[] { "scope1", "scope3", "offline_access" }); } } [Fact] @@ -612,8 +612,8 @@ public async Task refresh_token_exchange_with_invalid_resource_should_fail() { "resource", "urn:api4" } } }); - tokenResponse.IsError.Should().BeTrue(); - tokenResponse.Error.Should().Be("invalid_target"); + tokenResponse.IsError.ShouldBeTrue(); + tokenResponse.Error.ShouldBe("invalid_target"); } @@ -638,8 +638,8 @@ public async Task refresh_token_exchange_with_invalid_resource_should_fail() { "resource", "urn:api1" } } }); - tokenResponse.IsError.Should().BeTrue(); - tokenResponse.Error.Should().Be("invalid_target"); + tokenResponse.IsError.ShouldBeTrue(); + tokenResponse.Error.ShouldBe("invalid_target"); } { @@ -663,8 +663,8 @@ public async Task refresh_token_exchange_with_invalid_resource_should_fail() { "resource", "urn:api1" } } }); - tokenResponse.IsError.Should().BeTrue(); - tokenResponse.Error.Should().Be("invalid_target"); + tokenResponse.IsError.ShouldBeTrue(); + tokenResponse.Error.ShouldBe("invalid_target"); } } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/TokenEndpointTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/TokenEndpointTests.cs index 1c8cb8423..e58eb09be 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/TokenEndpointTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/TokenEndpointTests.cs @@ -2,7 +2,7 @@ // See LICENSE in the project root for license information. -using FluentAssertions; +using Shouldly; using System.Collections.Generic; using System.Net; using System.Net.Http; @@ -91,10 +91,10 @@ public async Task client_credentials_request_with_funny_headers_should_not_hang( _mockPipeline.BackChannelClient.DefaultRequestHeaders.Add("Referer", "http://127.0.0.1:33086/appservice/appservice?t=1564165664142?load"); var response = await _mockPipeline.BackChannelClient.PostAsync(IdentityServerPipeline.TokenEndpoint, form); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); var json = await response.Content.ReadAsStringAsync(); var result = JsonSerializer.Deserialize>(json); - result.ContainsKey("error").Should().BeFalse(); + result.ContainsKey("error").ShouldBeFalse(); } [Fact] @@ -114,10 +114,10 @@ public async Task resource_owner_request_with_funny_headers_should_not_hang() _mockPipeline.BackChannelClient.DefaultRequestHeaders.Add("Referer", "http://127.0.0.1:33086/appservice/appservice?t=1564165664142?load"); var response = await _mockPipeline.BackChannelClient.PostAsync(IdentityServerPipeline.TokenEndpoint, form); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); var json = await response.Content.ReadAsStringAsync(); var result = JsonSerializer.Deserialize>(json); - result.ContainsKey("error").Should().BeFalse(); + result.ContainsKey("error").ShouldBeFalse(); } [Fact] @@ -129,10 +129,10 @@ public async Task invalid_form_post_text_values_should_return_400_error() var response = await _mockPipeline.BackChannelClient.PostAsync(IdentityServerPipeline.TokenEndpoint, content); - response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var json = await response.Content.ReadAsStringAsync(); var result = JsonSerializer.Deserialize>(json); var error = result["error"].GetString(); - error.Should().Be("invalid_request"); + error.ShouldBe("invalid_request"); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomClaimsServiceTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomClaimsServiceTests.cs index b21703330..110388c9f 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomClaimsServiceTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomClaimsServiceTests.cs @@ -11,7 +11,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using Duende.IdentityModel.Client; using IntegrationTests.Common; @@ -64,14 +64,14 @@ public async Task custom_claims_should_be_in_access_token() ClientId = "test", ClientSecret = "secret" }); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); var accessToken = result.AccessToken; var payload = accessToken.Split('.')[1]; var json = Encoding.UTF8.GetString(Base64Url.Decode(payload)); var obj = JsonSerializer.Deserialize>(json); - obj["foo"].GetString().Should().Be("foo1"); + obj["foo"].GetString().ShouldBe("foo1"); } } diff --git a/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomProfileServiceTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomProfileServiceTests.cs index b2ef179e3..a1e723030 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomProfileServiceTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomProfileServiceTests.cs @@ -10,7 +10,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using IntegrationTests.Common; using Microsoft.Extensions.DependencyInjection; @@ -69,18 +69,18 @@ public async Task custom_profile_should_return_claims_for_implicit_client() _mockPipeline.BrowserClient.AllowAutoRedirect = false; var response = await _mockPipeline.BrowserClient.GetAsync(url); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://client/callback"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://client/callback"); var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); - authorization.IsError.Should().BeFalse(); - authorization.IdentityToken.Should().NotBeNull(); + authorization.IsError.ShouldBeFalse(); + authorization.IdentityToken.ShouldNotBeNull(); var payload = authorization.IdentityToken.Split('.')[1]; var json = Encoding.UTF8.GetString(Base64Url.Decode(payload)); var obj = JsonSerializer.Deserialize>(json); - obj["foo"].GetString().Should().Be("bar"); + obj["foo"].GetString().ShouldBe("bar"); } } diff --git a/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomTokenCreationServiceTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomTokenCreationServiceTests.cs index 10186ea56..7817abfd7 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomTokenCreationServiceTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Extensibility/CustomTokenCreationServiceTests.cs @@ -10,7 +10,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using Duende.IdentityModel.Client; using IntegrationTests.Common; @@ -63,14 +63,14 @@ public async Task custom_aud_should_be_in_access_token() ClientId = "test", ClientSecret = "secret" }); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); var accessToken = result.AccessToken; var payload = accessToken.Split('.')[1]; var json = Encoding.UTF8.GetString(Base64Url.Decode(payload)); var obj = JsonSerializer.Deserialize>(json); - obj["aud"].ToStringList().Should().Contain("custom1"); + obj["aud"].ToStringList().ShouldContain("custom1"); } } diff --git a/identity-server/test/IdentityServer.IntegrationTests/Hosting/CorsTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Hosting/CorsTests.cs index 1ec9134f3..8bb86ee21 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Hosting/CorsTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Hosting/CorsTests.cs @@ -10,7 +10,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using IntegrationTests.Common; using Microsoft.Extensions.DependencyInjection; using Xunit; @@ -90,8 +90,8 @@ public async Task cors_request_to_allowed_endpoints_should_succeed(string url) var message = new HttpRequestMessage(HttpMethod.Options, url); var response = await _pipeline.BackChannelClient.SendAsync(message); - response.StatusCode.Should().Be(HttpStatusCode.NoContent); - response.Headers.Contains("Access-Control-Allow-Origin").Should().BeTrue(); + response.StatusCode.ShouldBe(HttpStatusCode.NoContent); + response.Headers.Contains("Access-Control-Allow-Origin").ShouldBeTrue(); } [Theory] @@ -110,7 +110,7 @@ public async Task cors_request_to_restricted_endpoints_should_not_succeed(string var message = new HttpRequestMessage(HttpMethod.Options, url); var response = await _pipeline.BackChannelClient.SendAsync(message); - response.Headers.Contains("Access-Control-Allow-Origin").Should().BeFalse(); + response.Headers.Contains("Access-Control-Allow-Origin").ShouldBeFalse(); } [Fact] @@ -130,7 +130,7 @@ public async Task custom_cors_policy_provider_should_be_used() var message = new HttpRequestMessage(HttpMethod.Options, IdentityServerPipeline.DiscoveryEndpoint); var response = await _pipeline.BackChannelClient.SendAsync(message); - policy.WasCalled.Should().BeTrue(); + policy.WasCalled.ShouldBeTrue(); } } diff --git a/identity-server/test/IdentityServer.IntegrationTests/Hosting/DynamicProvidersTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Hosting/DynamicProvidersTests.cs index 9aba93f05..a7b97c78b 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Hosting/DynamicProvidersTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Hosting/DynamicProvidersTests.cs @@ -7,7 +7,7 @@ using Duende.IdentityServer.IntegrationTests.TestFramework; using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; -using FluentAssertions; +using Shouldly; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.Builder; @@ -240,8 +240,8 @@ public async Task challenge_should_trigger_authorize_request_to_dynamic_idp() { var response = await _host.HttpClient.GetAsync(_host.Url("/challenge?scheme=idp1")); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://idp1/connect/authorize"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://idp1/connect/authorize"); } [Fact] @@ -249,8 +249,8 @@ public async Task signout_should_trigger_endsession_request_to_dynamic_idp() { var response = await _host.HttpClient.GetAsync(_host.Url("/logout?scheme=idp1")); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://idp1/connect/endsession"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://idp1/connect/endsession"); } [Fact] @@ -258,8 +258,8 @@ public async Task challenge_should_trigger_authorize_request_to_static_idp() { var response = await _host.HttpClient.GetAsync(_host.Url("/challenge?scheme=idp2")); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Headers.Location.ToString().Should().StartWith("https://idp2/connect/authorize"); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location.ToString().ShouldStartWith("https://idp2/connect/authorize"); } #if NET5_0_OR_GREATER @@ -275,15 +275,15 @@ public async Task redirect_uri_should_process_dynamic_provider_signin_result() await _idp1.BrowserClient.GetAsync(_idp1.Url("/signin")); response = await _idp1.BrowserClient.GetAsync(authzUrl); var redirectUri = response.Headers.Location.ToString(); - redirectUri.Should().StartWith("https://server/federation/idp1/signin"); + redirectUri.ShouldStartWith("https://server/federation/idp1/signin"); response = await _host.BrowserClient.GetAsync(redirectUri); - response.Headers.Location.ToString().Should().StartWith("/callback"); + response.Headers.Location.ToString().ShouldStartWith("/callback"); response = await _host.BrowserClient.GetAsync(_host.Url("/callback")); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); var body = await response.Content.ReadAsStringAsync(); - body.Should().Be("1"); // sub + body.ShouldBe("1"); // sub } [Fact] @@ -295,13 +295,13 @@ public async Task redirect_uri_should_process_static_provider_signin_result() await _idp2.BrowserClient.GetAsync(_idp2.Url("/signin")); response = await _idp2.BrowserClient.GetAsync(authzUrl); var redirectUri = response.Headers.Location.ToString(); - redirectUri.Should().StartWith("https://server/signin-oidc"); + redirectUri.ShouldStartWith("https://server/signin-oidc"); response = await _host.BrowserClient.GetAsync(redirectUri); response = await _host.BrowserClient.GetAsync(_host.Url(response.Headers.Location.ToString())); // ~/callback - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); var body = await response.Content.ReadAsStringAsync(); - body.Should().Be("2"); // sub + body.ShouldBe("2"); // sub } [Fact] @@ -313,7 +313,7 @@ public async Task redirect_uri_should_work_when_dynamic_provider_not_in_cache() await _idp1.BrowserClient.GetAsync(_idp1.Url("/signin")); response = await _idp1.BrowserClient.GetAsync(authzUrl); var redirectUri = response.Headers.Location.ToString(); - redirectUri.Should().StartWith("https://server/federation/idp1/signin"); + redirectUri.ShouldStartWith("https://server/federation/idp1/signin"); var cache = _host.Resolve>() as DefaultCache; await cache.RemoveAsync("test"); @@ -321,9 +321,9 @@ public async Task redirect_uri_should_work_when_dynamic_provider_not_in_cache() response = await _host.BrowserClient.GetAsync(redirectUri); response = await _host.BrowserClient.GetAsync(_host.Url(response.Headers.Location.ToString())); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); var body = await response.Content.ReadAsStringAsync(); - body.Should().Be("1"); // sub + body.ShouldBe("1"); // sub } [Fact] @@ -340,7 +340,7 @@ public async Task front_channel_signout_from_dynamic_idp_should_sign_user_out() response = await _host.BrowserClient.GetAsync(_host.Url("/callback")); // signs the user in response = await _host.BrowserClient.GetAsync(_host.Url("/user")); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); response = await _host.BrowserClient.GetAsync(_host.Url("/logout?scheme=idp1")); @@ -353,14 +353,14 @@ public async Task front_channel_signout_from_dynamic_idp_should_sign_user_out() var iframeUrl = await _idp1.BrowserClient.ReadElementAttributeAsync("iframe", "src"); response = await _host.BrowserClient.GetAsync(_host.Url("/user")); - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); - iframeUrl.Should().StartWith(_host.Url("/federation/idp1/signout")); + iframeUrl.ShouldStartWith(_host.Url("/federation/idp1/signout")); response = await _host.BrowserClient.GetAsync(iframeUrl); // ~/federation/idp1/signout - response.IsSuccessStatusCode.Should().BeTrue(); + response.IsSuccessStatusCode.ShouldBeTrue(); response = await _host.BrowserClient.GetAsync(_host.Url("/user")); - response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); + response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); } #endif @@ -368,12 +368,12 @@ public async Task front_channel_signout_from_dynamic_idp_should_sign_user_out() public async Task missing_segments_in_redirect_uri_should_return_not_found() { var response = await _host.HttpClient.GetAsync(_host.Url("/federation/idp1")); - response.StatusCode.Should().Be(HttpStatusCode.NotFound); + response.StatusCode.ShouldBe(HttpStatusCode.NotFound); } [Fact] public async Task federation_endpoint_with_no_scheme_should_return_not_found() { var response = await _host.HttpClient.GetAsync(_host.Url("/federation")); - response.StatusCode.Should().Be(HttpStatusCode.NotFound); + response.StatusCode.ShouldBe(HttpStatusCode.NotFound); } } diff --git a/identity-server/test/IdentityServer.IntegrationTests/Hosting/FederatedSignoutTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Hosting/FederatedSignoutTests.cs index 1ac762978..6ad301a40 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Hosting/FederatedSignoutTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Hosting/FederatedSignoutTests.cs @@ -11,7 +11,7 @@ using Duende.IdentityServer; using Duende.IdentityServer.Models; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using IntegrationTests.Common; using Microsoft.AspNetCore.Authentication; @@ -81,10 +81,10 @@ await _pipeline.RequestAuthorizationEndpointAsync( var response = await _pipeline.BrowserClient.GetAsync(IdentityServerPipeline.FederatedSignOutUrl + "?sid=123"); - response.StatusCode.Should().Be(HttpStatusCode.OK); - response.Content.Headers.ContentType.MediaType.Should().Be("text/html"); + response.StatusCode.ShouldBe(HttpStatusCode.OK); + response.Content.Headers.ContentType.MediaType.ShouldBe("text/html"); var html = await response.Content.ReadAsStringAsync(); - html.Should().Contain("https://server/connect/endsession/callback?endSessionId="); + html.ShouldContain("https://server/connect/endsession/callback?endSessionId="); } [Fact] @@ -102,10 +102,10 @@ await _pipeline.RequestAuthorizationEndpointAsync( var response = await _pipeline.BrowserClient.PostAsync(IdentityServerPipeline.FederatedSignOutUrl, new FormUrlEncodedContent(new Dictionary { { "sid", "123" } })); - response.StatusCode.Should().Be(HttpStatusCode.OK); - response.Content.Headers.ContentType.MediaType.Should().Be("text/html"); + response.StatusCode.ShouldBe(HttpStatusCode.OK); + response.Content.Headers.ContentType.MediaType.ShouldBe("text/html"); var html = await response.Content.ReadAsStringAsync(); - html.Should().Contain("https://server/connect/endsession/callback?endSessionId="); + html.ShouldContain("https://server/connect/endsession/callback?endSessionId="); } [Fact] @@ -115,10 +115,10 @@ public async Task no_clients_signed_into_should_not_render_page_with_iframe() var response = await _pipeline.BrowserClient.GetAsync(IdentityServerPipeline.FederatedSignOutUrl + "?sid=123"); - response.StatusCode.Should().Be(HttpStatusCode.OK); - response.Content.Headers.ContentType.Should().BeNull(); + response.StatusCode.ShouldBe(HttpStatusCode.OK); + response.Content.Headers.ContentType.ShouldBeNull(); var html = await response.Content.ReadAsStringAsync(); - html.Should().Be(String.Empty); + html.ShouldBe(String.Empty); } [Fact] @@ -126,10 +126,10 @@ public async Task no_authenticated_user_should_not_render_page_with_iframe() { var response = await _pipeline.BrowserClient.GetAsync(IdentityServerPipeline.FederatedSignOutUrl + "?sid=123"); - response.StatusCode.Should().Be(HttpStatusCode.OK); - response.Content.Headers.ContentType.Should().BeNull(); + response.StatusCode.ShouldBe(HttpStatusCode.OK); + response.Content.Headers.ContentType.ShouldBeNull(); var html = await response.Content.ReadAsStringAsync(); - html.Should().Be(String.Empty); + html.ShouldBe(String.Empty); } [Fact] @@ -152,10 +152,10 @@ await _pipeline.RequestAuthorizationEndpointAsync( var response = await _pipeline.BrowserClient.GetAsync(IdentityServerPipeline.FederatedSignOutUrl + "?sid=123"); - response.StatusCode.Should().Be(HttpStatusCode.OK); - response.Content.Headers.ContentType.Should().BeNull(); + response.StatusCode.ShouldBe(HttpStatusCode.OK); + response.Content.Headers.ContentType.ShouldBeNull(); var html = await response.Content.ReadAsStringAsync(); - html.Should().Be(String.Empty); + html.ShouldBe(String.Empty); } [Fact] @@ -181,9 +181,9 @@ await _pipeline.RequestAuthorizationEndpointAsync( _pipeline.BrowserClient.AllowAutoRedirect = false; var response = await _pipeline.BrowserClient.GetAsync(IdentityServerPipeline.FederatedSignOutUrl + "?sid=123"); - response.StatusCode.Should().Be(HttpStatusCode.Redirect); - response.Content.Headers.ContentType.Should().BeNull(); + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Content.Headers.ContentType.ShouldBeNull(); var html = await response.Content.ReadAsStringAsync(); - html.Should().Be(String.Empty); + html.ShouldBe(String.Empty); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Hosting/IdentityServerMiddlewareTests..cs b/identity-server/test/IdentityServer.IntegrationTests/Hosting/IdentityServerMiddlewareTests..cs index 78974dc99..d4797d7e6 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Hosting/IdentityServerMiddlewareTests..cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Hosting/IdentityServerMiddlewareTests..cs @@ -4,7 +4,7 @@ using System.Threading; using System.Threading.Tasks; using Duende.IdentityServer.Hosting; -using FluentAssertions; +using Shouldly; using IntegrationTests.Common; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; @@ -61,22 +61,22 @@ public async Task expected_exception_types_are_filtered_from_logs_when_incoming_ var canceledHttpRequest = async () => await _pipeline.BackChannelClient.GetAsync(IdentityServerPipeline.DiscoveryEndpoint, token); // The middleware will always throw - var exceptionShould = await canceledHttpRequest.Should().ThrowAsync(); + var exceptionShould = await canceledHttpRequest.ShouldThrowAsync(); // The middleware will log most exceptions, but not TaskCanceled or OperationCanceled if (filteringExpected) { - _pipeline.MockLogger.LogMessages.Should().NotContain(m => m.StartsWith("Unhandled exception: ")); + _pipeline.MockLogger.LogMessages.ShouldNotContain(m => m.StartsWith("Unhandled exception: ")); } else { - _pipeline.MockLogger.LogMessages.Should().Contain(m => m.StartsWith("Unhandled exception: ")); + _pipeline.MockLogger.LogMessages.ShouldContain(m => m.StartsWith("Unhandled exception: ")); } // Now reset the log messages so that we can verify that we always log for requests that are not canceled _pipeline.MockLogger.LogMessages.Clear(); var notCanceledRequest = async () => await _pipeline.BackChannelClient.GetAsync(IdentityServerPipeline.DiscoveryKeysEndpoint, CancellationToken.None); - await notCanceledRequest.Should().ThrowAsync(); - _pipeline.MockLogger.LogMessages.Should().Contain(m => m.StartsWith("Unhandled exception: ")); + await notCanceledRequest.ShouldThrowAsync(); + _pipeline.MockLogger.LogMessages.ShouldContain(m => m.StartsWith("Unhandled exception: ")); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Hosting/LicenseTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Hosting/LicenseTests.cs index 6af4e2c58..cfcb66718 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Hosting/LicenseTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Hosting/LicenseTests.cs @@ -8,7 +8,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Licensing.V2; using Duende.IdentityServer.Models; -using FluentAssertions; +using Shouldly; using IntegrationTests.Common; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Time.Testing; @@ -79,7 +79,7 @@ public async Task unlicensed_protocol_requests_log_a_warning() await _mockPipeline.BackChannelClient.PostAsync(IdentityServerPipeline.TokenEndpoint, form); } - _mockPipeline.MockLogger.LogMessages.Should().Contain( + _mockPipeline.MockLogger.LogMessages.ShouldContain( $"You are using IdentityServer in trial mode and have exceeded the trial threshold of {threshold} requests handled by IdentityServer. In a future version, you will need to restart the server or configure a license key to continue testing. For more information, please see https://docs.duendesoftware.com/trial-mode."); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/Hosting/LocalApiAuthentication/LocalApiAuthenticationTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Hosting/LocalApiAuthentication/LocalApiAuthenticationTests.cs index c0a10b1b2..2cccc5548 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Hosting/LocalApiAuthentication/LocalApiAuthenticationTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Hosting/LocalApiAuthentication/LocalApiAuthenticationTests.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Hosting.LocalApiAuthentication; using Duende.IdentityServer.Models; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using Duende.IdentityModel.Client; using IntegrationTests.Common; @@ -159,10 +159,10 @@ async Task GetAccessTokenAsync(bool dpop = false, bool reference = false } var result = await _pipeline.BackChannelClient.RequestClientCredentialsTokenAsync(req); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); - if (dpop) result.TokenType.Should().Be("DPoP"); - else result.TokenType.Should().Be("Bearer"); + if (dpop) result.TokenType.ShouldBe("DPoP"); + else result.TokenType.ShouldBe("Bearer"); return result.AccessToken; } @@ -244,9 +244,9 @@ public async Task bearer_jwt_token_should_validate() var response = await _pipeline.BackChannelClient.SendAsync(req); - response.IsSuccessStatusCode.Should().BeTrue(); - ApiWasCalled.Should().BeTrue(); - ApiPrincipal.Identity.IsAuthenticated.Should().BeTrue(); + response.IsSuccessStatusCode.ShouldBeTrue(); + ApiWasCalled.ShouldBeTrue(); + ApiPrincipal.Identity.IsAuthenticated.ShouldBeTrue(); } [Fact] @@ -261,9 +261,9 @@ public async Task bearer_ref_token_should_validate() var response = await _pipeline.BackChannelClient.SendAsync(req); - response.IsSuccessStatusCode.Should().BeTrue(); - ApiWasCalled.Should().BeTrue(); - ApiPrincipal.Identity.IsAuthenticated.Should().BeTrue(); + response.IsSuccessStatusCode.ShouldBeTrue(); + ApiWasCalled.ShouldBeTrue(); + ApiPrincipal.Identity.IsAuthenticated.ShouldBeTrue(); } [Fact] @@ -277,9 +277,9 @@ public async Task dpop_token_should_validate() var response = await _pipeline.BackChannelClient.SendAsync(req); - response.IsSuccessStatusCode.Should().BeTrue(); - ApiWasCalled.Should().BeTrue(); - ApiPrincipal.Identity.IsAuthenticated.Should().BeTrue(); + response.IsSuccessStatusCode.ShouldBeTrue(); + ApiWasCalled.ShouldBeTrue(); + ApiPrincipal.Identity.IsAuthenticated.ShouldBeTrue(); } [Fact] @@ -309,12 +309,12 @@ public async Task dpop_token_should_not_validate_if_cnf_from_jwt_access_token_do if (json.TryGetValue(JwtClaimTypes.ConfirmationMethods.JwkThumbprint, out var jktJson)) { var accessTokenJkt = jktJson.ToString(); - accessTokenJkt.Should().NotBeEquivalentTo(newJkt); + accessTokenJkt.ShouldNotBeEquivalentTo(newJkt); } var response = await _pipeline.BackChannelClient.SendAsync(req); - response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); + response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); } [Fact] @@ -342,19 +342,19 @@ public async Task dpop_token_should_not_validate_if_cnf_from_introspection_does_ Token = at }; var introspectionResponse = await _pipeline.BackChannelClient.IntrospectTokenAsync(introspectionRequest); - introspectionResponse.IsError.Should().BeFalse(); + introspectionResponse.IsError.ShouldBeFalse(); var cnf = introspectionResponse.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Confirmation); var json = JsonSerializer.Deserialize>(cnf.Value); if (json.TryGetValue(JwtClaimTypes.ConfirmationMethods.JwkThumbprint, out var jktJson)) { var accessTokenJkt = jktJson.ToString(); - accessTokenJkt.Should().NotBeEquivalentTo(newJkt); + accessTokenJkt.ShouldNotBeEquivalentTo(newJkt); } var response = await _pipeline.BackChannelClient.SendAsync(req); - response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); + response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); } [Fact] @@ -369,8 +369,8 @@ public async Task dpop_nonce_required_should_require_nonce() _client.DPoPValidationMode = DPoPTokenExpirationValidationMode.Nonce; var response = await _pipeline.BackChannelClient.SendAsync(req); - response.IsSuccessStatusCode.Should().BeFalse(); - response.Headers.Contains("DPoP-Nonce").Should().BeTrue(); + response.IsSuccessStatusCode.ShouldBeFalse(); + response.Headers.Contains("DPoP-Nonce").ShouldBeTrue(); } [Fact] [Trait("Category", Category)] @@ -391,7 +391,7 @@ public async Task dpop_nonce_should_validate() req2.Headers.Add("DPoP", CreateProofToken("GET", "https://server/api", at, nonce)); var response2 = await _pipeline.BackChannelClient.SendAsync(req2); - response2.IsSuccessStatusCode.Should().BeTrue(); + response2.IsSuccessStatusCode.ShouldBeTrue(); } [Fact] @@ -406,8 +406,8 @@ public async Task bearer_only_dpop_token_should_fail() var response = await _pipeline.BackChannelClient.SendAsync(req); - response.IsSuccessStatusCode.Should().BeFalse(); - response.Headers.WwwAuthenticate.Select(x => x.Scheme).Should().BeEquivalentTo(new[] { "Bearer" }); + response.IsSuccessStatusCode.ShouldBeFalse(); + response.Headers.WwwAuthenticate.Select(x => x.Scheme).ShouldBeEquivalentTo(new[] { "Bearer" }); } @@ -422,8 +422,8 @@ public async Task dpop_only_bearer_should_fail() var response = await _pipeline.BackChannelClient.SendAsync(req); - response.IsSuccessStatusCode.Should().BeFalse(); - response.Headers.WwwAuthenticate.Select(x => x.Scheme).Should().BeEquivalentTo(new[] { "DPoP" }); + response.IsSuccessStatusCode.ShouldBeFalse(); + response.Headers.WwwAuthenticate.Select(x => x.Scheme).ShouldBeEquivalentTo(new[] { "DPoP" }); } [Fact] @@ -434,8 +434,8 @@ public async Task missing_authz_should_fail() var response = await _pipeline.BackChannelClient.SendAsync(req); - response.IsSuccessStatusCode.Should().BeFalse(); - response.Headers.WwwAuthenticate.Select(x => x.Scheme).Should().BeEquivalentTo(new[] { "Bearer", "DPoP" }); + response.IsSuccessStatusCode.ShouldBeFalse(); + response.Headers.WwwAuthenticate.Select(x => x.Scheme).ShouldBeEquivalentTo(new[] { "Bearer", "DPoP" }); } [Fact] [Trait("Category", Category)] @@ -446,7 +446,7 @@ public async Task missing_token_should_fail() var response = await _pipeline.BackChannelClient.SendAsync(req); - response.IsSuccessStatusCode.Should().BeFalse(); + response.IsSuccessStatusCode.ShouldBeFalse(); } [Fact] [Trait("Category", Category)] @@ -458,7 +458,7 @@ public async Task malformed_token_should_fail() var response = await _pipeline.BackChannelClient.SendAsync(req); - response.IsSuccessStatusCode.Should().BeFalse(); + response.IsSuccessStatusCode.ShouldBeFalse(); } [Fact] @@ -474,7 +474,7 @@ public async Task dpop_token_for_disabled_client_should_fail() var response = await _pipeline.BackChannelClient.SendAsync(req); - response.IsSuccessStatusCode.Should().BeFalse(); + response.IsSuccessStatusCode.ShouldBeFalse(); } [Fact] @@ -487,7 +487,7 @@ public async Task dpop_validation_failure_should_fail() var response = await _pipeline.BackChannelClient.SendAsync(req); - response.IsSuccessStatusCode.Should().BeFalse(); + response.IsSuccessStatusCode.ShouldBeFalse(); } [Fact] [Trait("Category", Category)] @@ -499,6 +499,6 @@ public async Task dpop_token_using_bearer_scheme_should_fail() var response = await _pipeline.BackChannelClient.SendAsync(req); - response.IsSuccessStatusCode.Should().BeFalse(); + response.IsSuccessStatusCode.ShouldBeFalse(); } } diff --git a/identity-server/test/IdentityServer.IntegrationTests/Hosting/ServerSideSessionTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Hosting/ServerSideSessionTests.cs index 5ae446869..a39e91e5f 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Hosting/ServerSideSessionTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Hosting/ServerSideSessionTests.cs @@ -6,7 +6,7 @@ using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using IntegrationTests.Common; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; @@ -133,10 +133,10 @@ async Task IsLoggedIn() [Trait("Category", Category)] public async Task login_should_create_server_side_session() { - (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).Should().BeEmpty(); + (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).ShouldBeEmpty(); await _pipeline.LoginAsync("bob"); - (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).Should().NotBeEmpty(); - (await IsLoggedIn()).Should().BeTrue(); + (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).ShouldNotBeEmpty(); + (await IsLoggedIn()).ShouldBeTrue(); } [Fact] @@ -146,9 +146,9 @@ public async Task renewal_should_create_new_record_if_missing() await _pipeline.LoginAsync("bob"); ShouldRenewCookie = true; - (await IsLoggedIn()).Should().BeTrue(); + (await IsLoggedIn()).ShouldBeTrue(); - (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).Should().NotBeEmpty(); + (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).ShouldNotBeEmpty(); } [Fact] @@ -158,9 +158,9 @@ public async Task remove_server_side_session_should_logout_user() await _pipeline.LoginAsync("bob"); await _sessionStore.DeleteSessionsAsync(new SessionFilter { SubjectId = "bob" }); - (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).Should().BeEmpty(); + (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).ShouldBeEmpty(); - (await IsLoggedIn()).Should().BeFalse(); + (await IsLoggedIn()).ShouldBeFalse(); } [Fact] @@ -170,9 +170,9 @@ public async Task logout_should_remove_server_side_session() await _pipeline.LoginAsync("bob"); await _pipeline.LogoutAsync(); - (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).Should().BeEmpty(); + (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).ShouldBeEmpty(); - (await IsLoggedIn()).Should().BeFalse(); + (await IsLoggedIn()).ShouldBeFalse(); } [Fact] @@ -186,8 +186,8 @@ public async Task corrupted_server_side_session_should_logout_user() session.Ticket = "invalid"; await _sessionStore.UpdateSessionAsync(session); - (await IsLoggedIn()).Should().BeFalse(); - (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).Should().BeEmpty(); + (await IsLoggedIn()).ShouldBeFalse(); + (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).ShouldBeEmpty(); } [Fact] @@ -200,9 +200,9 @@ public async Task subsequent_logins_should_update_server_side_session() await _pipeline.LoginAsync("bob"); - (await IsLoggedIn()).Should().BeTrue(); + (await IsLoggedIn()).ShouldBeTrue(); var sessions = await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" }); - sessions.First().Key.Should().Be(key); + sessions.First().Key.ShouldBe(key); } [Fact] @@ -216,12 +216,12 @@ public async Task changing_users_should_create_new_server_side_session() await Task.Delay(1000); await _pipeline.LoginAsync("alice"); - (await IsLoggedIn()).Should().BeTrue(); + (await IsLoggedIn()).ShouldBeTrue(); var alice_session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single(); - alice_session.Key.Should().Be(bob_session.Key); - (alice_session.Created > bob_session.Created).Should().BeTrue(); - alice_session.SessionId.Should().NotBe(bob_session.SessionId); + alice_session.Key.ShouldBe(bob_session.Key); + (alice_session.Created > bob_session.Created).ShouldBeTrue(); + alice_session.SessionId.ShouldNotBe(bob_session.SessionId); } [Fact] @@ -238,7 +238,7 @@ public async Task getsessions_on_ticket_store_should_use_session_store() var tickets = await _ticketService.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }); var sessions = await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" }); - tickets.Select(x => x.SessionId).Should().BeEquivalentTo(sessions.Select(x => x.SessionId)); + tickets.Select(x => x.SessionId).ShouldBeEquivalentTo(sessions.Select(x => x.SessionId)); } [Fact] @@ -253,18 +253,18 @@ public async Task querysessions_on_ticket_store_should_use_session_store() _pipeline.RemoveLoginCookie(); var tickets = await _ticketService.QuerySessionsAsync(new SessionQuery { SubjectId = "alice" }); - tickets.TotalCount.Should().Be(2); + tickets.TotalCount.ShouldBe(2); var sessions = await _sessionStore.QuerySessionsAsync(new SessionQuery { SubjectId = "alice" }); - sessions.TotalCount.Should().Be(2); + sessions.TotalCount.ShouldBe(2); - tickets.ResultsToken.Should().Be(sessions.ResultsToken); - tickets.HasPrevResults.Should().Be(sessions.HasPrevResults); - tickets.HasNextResults.Should().Be(sessions.HasNextResults); - tickets.TotalCount.Should().Be(sessions.TotalCount); - tickets.TotalPages.Should().Be(sessions.TotalPages); - tickets.CurrentPage.Should().Be(sessions.CurrentPage); + tickets.ResultsToken.ShouldBe(sessions.ResultsToken); + tickets.HasPrevResults.ShouldBe(sessions.HasPrevResults); + tickets.HasNextResults.ShouldBe(sessions.HasNextResults); + tickets.TotalCount.ShouldBe(sessions.TotalCount); + tickets.TotalPages.ShouldBe(sessions.TotalPages); + tickets.CurrentPage.ShouldBe(sessions.CurrentPage); - tickets.Results.Select(x => x.SessionId).Should().BeEquivalentTo(sessions.Results.Select(x => x.SessionId)); + tickets.Results.Select(x => x.SessionId).ShouldBeEquivalentTo(sessions.Results.Select(x => x.SessionId)); } [Fact] @@ -281,14 +281,14 @@ public async Task querysessions_on_session_mgmt_service_should_use_ticket_store( var sessions = await _sessionMgmt.QuerySessionsAsync(new SessionQuery { SubjectId = "alice" }); var tickets = await _ticketService.QuerySessionsAsync(new SessionQuery { SubjectId = "alice" }); - tickets.ResultsToken.Should().Be(sessions.ResultsToken); - tickets.HasPrevResults.Should().Be(sessions.HasPrevResults); - tickets.HasNextResults.Should().Be(sessions.HasNextResults); - tickets.TotalCount.Should().Be(sessions.TotalCount); - tickets.TotalPages.Should().Be(sessions.TotalPages); - tickets.CurrentPage.Should().Be(sessions.CurrentPage); + tickets.ResultsToken.ShouldBe(sessions.ResultsToken); + tickets.HasPrevResults.ShouldBe(sessions.HasPrevResults); + tickets.HasNextResults.ShouldBe(sessions.HasNextResults); + tickets.TotalCount.ShouldBe(sessions.TotalCount); + tickets.TotalPages.ShouldBe(sessions.TotalPages); + tickets.CurrentPage.ShouldBe(sessions.CurrentPage); - tickets.Results.Select(x => x.SessionId).Should().BeEquivalentTo(sessions.Results.Select(x => x.SessionId)); + tickets.Results.Select(x => x.SessionId).ShouldBeEquivalentTo(sessions.Results.Select(x => x.SessionId)); } [Fact] @@ -306,7 +306,7 @@ public async Task remove_sessions_should_delete_refresh_tokens() RedirectUri = "https://client/callback" }); - (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).Should().NotBeEmpty(); + (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).ShouldNotBeEmpty(); await _sessionMgmt.RemoveSessionsAsync(new RemoveSessionsContext { @@ -317,7 +317,7 @@ await _sessionMgmt.RemoveSessionsAsync(new RemoveSessionsContext SendBackchannelLogoutNotification = false }); - (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).Should().BeEmpty(); + (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).ShouldBeEmpty(); } [Fact] @@ -335,7 +335,7 @@ public async Task remove_sessions_with_clientid_filter_should_filter_delete_refr RedirectUri = "https://client/callback" }); - (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).Should().NotBeEmpty(); + (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).ShouldNotBeEmpty(); await _sessionMgmt.RemoveSessionsAsync(new RemoveSessionsContext { @@ -347,7 +347,7 @@ await _sessionMgmt.RemoveSessionsAsync(new RemoveSessionsContext ClientIds = new[] { "foo" } }); - (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).Should().NotBeEmpty(); + (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).ShouldNotBeEmpty(); } [Fact] @@ -365,7 +365,7 @@ public async Task remove_sessions_should_invoke_backchannel_logout() RedirectUri = "https://client/callback" }); - _pipeline.BackChannelMessageHandler.InvokeWasCalled.Should().BeFalse(); + _pipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeFalse(); await _sessionMgmt.RemoveSessionsAsync(new RemoveSessionsContext { @@ -376,7 +376,7 @@ await _sessionMgmt.RemoveSessionsAsync(new RemoveSessionsContext SendBackchannelLogoutNotification = true }); - _pipeline.BackChannelMessageHandler.InvokeWasCalled.Should().BeTrue(); + _pipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeTrue(); } @@ -395,7 +395,7 @@ public async Task remove_sessions_with_clientid_filter_should_filter_backchannel RedirectUri = "https://client/callback" }); - _pipeline.BackChannelMessageHandler.InvokeWasCalled.Should().BeFalse(); + _pipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeFalse(); await _sessionMgmt.RemoveSessionsAsync(new RemoveSessionsContext { @@ -407,7 +407,7 @@ await _sessionMgmt.RemoveSessionsAsync(new RemoveSessionsContext ClientIds = new List{ "foo" } }); - _pipeline.BackChannelMessageHandler.InvokeWasCalled.Should().BeFalse(); + _pipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeFalse(); } [Fact] @@ -425,9 +425,9 @@ public async Task remove_sessions_should_remove_server_sessions() RedirectUri = "https://client/callback" }); - _pipeline.BackChannelMessageHandler.InvokeWasCalled.Should().BeFalse(); + _pipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeFalse(); - (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Should().NotBeEmpty(); + (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).ShouldNotBeEmpty(); await _sessionMgmt.RemoveSessionsAsync(new RemoveSessionsContext { @@ -438,7 +438,7 @@ await _sessionMgmt.RemoveSessionsAsync(new RemoveSessionsContext SendBackchannelLogoutNotification = false }); - (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Should().BeEmpty(); + (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).ShouldBeEmpty(); } [Fact] @@ -464,10 +464,10 @@ public async Task expired_sessions_should_invoke_backchannel_logout() var jwt = form.Substring("login_token=".Length + 1); var handler = new JsonWebTokenHandler(); var token = handler.ReadJsonWebToken(jwt); - token.Issuer.Should().Be(IdentityServerPipeline.BaseUrl); - token.GetClaim("sub").Value.Should().Be("alice"); + token.Issuer.ShouldBe(IdentityServerPipeline.BaseUrl); + token.GetClaim("sub").Value.ShouldBe("alice"); }; - _pipeline.BackChannelMessageHandler.InvokeWasCalled.Should().BeFalse(); + _pipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeFalse(); var session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single(); session.Expires = System.DateTime.UtcNow.AddMinutes(-1); @@ -475,7 +475,7 @@ public async Task expired_sessions_should_invoke_backchannel_logout() await Task.Delay(1000); - _pipeline.BackChannelMessageHandler.InvokeWasCalled.Should().BeTrue(); + _pipeline.BackChannelMessageHandler.InvokeWasCalled.ShouldBeTrue(); } [Fact] @@ -493,7 +493,7 @@ public async Task expired_sessions_should_revoke_refresh_token() RedirectUri = "https://client/callback" }); - (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).Should().NotBeEmpty(); + (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).ShouldNotBeEmpty(); var session = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single(); session.Expires = System.DateTime.UtcNow.AddMinutes(-1); @@ -501,7 +501,7 @@ public async Task expired_sessions_should_revoke_refresh_token() await Task.Delay(1000); - (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).Should().BeEmpty(); + (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).ShouldBeEmpty(); } [Fact] @@ -519,11 +519,11 @@ public async Task logout_should_revoke_refresh_token() RedirectUri = "https://client/callback" }); - (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).Should().NotBeEmpty(); + (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).ShouldNotBeEmpty(); await _pipeline.LogoutAsync(); - (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).Should().BeEmpty(); + (await _grantStore.GetAllAsync(new PersistedGrantFilter { SubjectId = "alice" })).ShouldBeEmpty(); } [Fact] @@ -559,8 +559,8 @@ await _pipeline.BackChannelClient.RequestRefreshTokenAsync(new RefreshTokenReque var expiration2 = ticket2.GetExpiration(); var issued2 = ticket2.GetIssued(); - issued2.Should().BeAfter(issued1); - expiration2.Value.Should().BeAfter(expiration1.Value); + issued2.ShouldBeGreaterThan(issued1); + expiration2!.Value.ShouldBeGreaterThan(expiration1.Value); } [Fact] @@ -699,7 +699,7 @@ await _pipeline.BackChannelClient.GetUserInfoAsync(new UserInfoRequest var expiration2 = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single().Expires.Value; - expiration2.Should().BeAfter(expiration1); + expiration2.ShouldBeGreaterThan(expiration1); } [Fact] @@ -844,7 +844,7 @@ public async Task using_refresh_token_for_expired_session_should_fail() ClientId = "client", RefreshToken = tokenResponse.RefreshToken }); - refreshResponse.IsError.Should().BeFalse(); + refreshResponse.IsError.ShouldBeFalse(); } @@ -859,7 +859,7 @@ public async Task using_refresh_token_for_expired_session_should_fail() ClientId = "client", RefreshToken = tokenResponse.RefreshToken }); - refreshResponse.IsError.Should().BeFalse(); + refreshResponse.IsError.ShouldBeFalse(); } @@ -874,7 +874,7 @@ public async Task using_refresh_token_for_expired_session_should_fail() ClientId = "client", RefreshToken = tokenResponse.RefreshToken }); - refreshResponse.IsError.Should().BeTrue(); + refreshResponse.IsError.ShouldBeTrue(); } @@ -887,7 +887,7 @@ public async Task using_refresh_token_for_expired_session_should_fail() ClientId = "client", RefreshToken = tokenResponse.RefreshToken }); - refreshResponse.IsError.Should().BeTrue(); + refreshResponse.IsError.ShouldBeTrue(); } } @@ -917,7 +917,7 @@ public async Task using_access_token_for_expired_session_should_fail() ClientCredentialStyle = ClientCredentialStyle.PostBody, Token = tokenResponse.AccessToken }); - response.IsError.Should().BeFalse(); + response.IsError.ShouldBeFalse(); } @@ -933,7 +933,7 @@ public async Task using_access_token_for_expired_session_should_fail() ClientCredentialStyle = ClientCredentialStyle.PostBody, Token = tokenResponse.AccessToken }); - response.IsError.Should().BeFalse(); + response.IsError.ShouldBeFalse(); } @@ -949,7 +949,7 @@ public async Task using_access_token_for_expired_session_should_fail() ClientCredentialStyle = ClientCredentialStyle.PostBody, Token = tokenResponse.AccessToken }); - response.IsError.Should().BeTrue(); + response.IsError.ShouldBeTrue(); } @@ -963,7 +963,7 @@ public async Task using_access_token_for_expired_session_should_fail() ClientCredentialStyle = ClientCredentialStyle.PostBody, Token = tokenResponse.AccessToken }); - response.IsError.Should().BeTrue(); + response.IsError.ShouldBeTrue(); } } @@ -983,7 +983,7 @@ public async Task claim_issuers_should_be_persisted() var ticket = (await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "alice" })).Single() .Deserialize(_protector, null); var claims = ticket.Principal.Claims; - claims.Should().Contain(c => c.Issuer == "Custom Issuer" && c.Type == "Test"); - claims.Should().Contain(c => c.Issuer == ClaimsIdentity.DefaultIssuer && c.Type == "Test"); + claims.ShouldContain(c => c.Issuer == "Custom Issuer" && c.Type == "Test"); + claims.ShouldContain(c => c.Issuer == ClaimsIdentity.DefaultIssuer && c.Type == "Test"); } } diff --git a/identity-server/test/IdentityServer.IntegrationTests/Hosting/SubpathHosting.cs b/identity-server/test/IdentityServer.IntegrationTests/Hosting/SubpathHosting.cs index 97f56110f..66611a5fc 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Hosting/SubpathHosting.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Hosting/SubpathHosting.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Models; using Duende.IdentityServer.Test; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel.Client; using IntegrationTests.Common; using Xunit; @@ -70,6 +70,6 @@ public async Task anonymous_user_should_be_redirected_to_login_page() nonce: "123_nonce"); var response = await _mockPipeline.BrowserClient.GetAsync(url); - _mockPipeline.LoginWasCalled.Should().BeTrue(); + _mockPipeline.LoginWasCalled.ShouldBeTrue(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/IdentityServer.IntegrationTests.csproj b/identity-server/test/IdentityServer.IntegrationTests/IdentityServer.IntegrationTests.csproj index 9a0ebd7b3..f8ffaf925 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/IdentityServer.IntegrationTests.csproj +++ b/identity-server/test/IdentityServer.IntegrationTests/IdentityServer.IntegrationTests.csproj @@ -13,8 +13,7 @@ - - + @@ -41,6 +40,7 @@ + \ No newline at end of file diff --git a/identity-server/test/IdentityServer.IntegrationTests/TestFramework/GenericHost.cs b/identity-server/test/IdentityServer.IntegrationTests/TestFramework/GenericHost.cs index 872d5c7ce..6a5a80f0e 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/TestFramework/GenericHost.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/TestFramework/GenericHost.cs @@ -2,7 +2,7 @@ // See LICENSE in the project root for license information. -using FluentAssertions; +using Shouldly; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -133,7 +133,7 @@ void ConfigureSignout(IApplicationBuilder app) public async Task RevokeSessionCookieAsync() { var response = await BrowserClient.GetAsync(Url("__signout")); - response.StatusCode.Should().Be(HttpStatusCode.NoContent); + response.StatusCode.ShouldBe(HttpStatusCode.NoContent); } @@ -167,7 +167,7 @@ public async Task IssueSessionCookieAsync(params Claim[] claims) { _userToSignIn = new ClaimsPrincipal(new ClaimsIdentity(claims, "test", "name", "role")); var response = await BrowserClient.GetAsync(Url("__signin")); - response.StatusCode.Should().Be(HttpStatusCode.NoContent); + response.StatusCode.ShouldBe(HttpStatusCode.NoContent); } public Task IssueSessionCookieAsync(AuthenticationProperties props, params Claim[] claims) { diff --git a/identity-server/test/IdentityServer.IntegrationTests/TestFramework/TestBrowserClient.cs b/identity-server/test/IdentityServer.IntegrationTests/TestFramework/TestBrowserClient.cs index dd9b8c91c..c1025d3b0 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/TestFramework/TestBrowserClient.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/TestFramework/TestBrowserClient.cs @@ -5,7 +5,7 @@ using AngleSharp.Dom; using AngleSharp.Html.Dom; using AngleSharp.Html.Parser; -using FluentAssertions; +using Shouldly; using System; using System.Collections.Generic; using System.Diagnostics; @@ -94,7 +94,7 @@ public void RemoveCookie(string uri, string name) public async Task FollowRedirectAsync() { - LastResponse.StatusCode.Should().Be(HttpStatusCode.Found); + LastResponse.StatusCode.ShouldBe(HttpStatusCode.Found); var location = LastResponse.Headers.Location.ToString(); await GetAsync(location); } @@ -110,7 +110,7 @@ public Task ReadFormAsync(string selector = null) } public async Task ReadFormAsync(HttpResponseMessage response, string selector = null) { - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); var htmlForm = new HtmlForm(); @@ -120,7 +120,7 @@ public async Task ReadFormAsync(HttpResponseMessage response, string s var document = await parser.ParseDocumentAsync(html); var form = document.QuerySelector(selector ?? "form") as IHtmlFormElement; - form.Should().NotBeNull(); + form.ShouldNotBeNull(); var postUrl = form.Action; if (!postUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase)) @@ -194,14 +194,14 @@ public Task AssertExistsAsync(string selector) public async Task AssertExistsAsync(HttpResponseMessage response, string selector) { - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); var html = await response.Content.ReadAsStringAsync(); var parser = new HtmlParser(); var dom = parser.ParseDocument(html); var element = dom.QuerySelectorAll(selector); - element.Length.Should().BeGreaterThan(0); + element.Length.ShouldBeGreaterThan(0); } public Task AssertNotExistsAsync(string selector) @@ -210,14 +210,14 @@ public Task AssertNotExistsAsync(string selector) } public async Task AssertNotExistsAsync(HttpResponseMessage response, string selector) { - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); var html = await response.Content.ReadAsStringAsync(); var parser = new HtmlParser(); var dom = parser.ParseDocument(html); var element = dom.QuerySelectorAll(selector); - element.Length.Should().Be(0); + element.Length.ShouldBe(0); } public Task AssertErrorPageAsync(string error = null) @@ -226,13 +226,13 @@ public Task AssertErrorPageAsync(string error = null) } public async Task AssertErrorPageAsync(HttpResponseMessage response, string error = null) { - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); await AssertExistsAsync(response, ".error-page"); if (!String.IsNullOrWhiteSpace(error)) { var errorText = await ReadElementTextAsync(response, ".alert.alert-danger"); - errorText.Should().Contain(error); + errorText.ShouldContain(error); } } @@ -242,13 +242,13 @@ public Task AssertValidationErrorAsync(string error = null) } public async Task AssertValidationErrorAsync(HttpResponseMessage response, string error = null) { - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.ShouldBe(HttpStatusCode.OK); await AssertExistsAsync(response, ".validation-summary-errors"); if (!String.IsNullOrWhiteSpace(error)) { var errorText = await ReadElementTextAsync(response, ".validation-summary-errors"); - errorText.ToLowerInvariant().Should().Contain(error.ToLowerInvariant()); + errorText.ToLowerInvariant().ShouldContain(error.ToLowerInvariant()); } } } diff --git a/identity-server/test/IdentityServer.UnitTests/Caches/ResourceStoreCacheTests.cs b/identity-server/test/IdentityServer.UnitTests/Caches/ResourceStoreCacheTests.cs index 191e3715f..6fed5060c 100644 --- a/identity-server/test/IdentityServer.UnitTests/Caches/ResourceStoreCacheTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Caches/ResourceStoreCacheTests.cs @@ -6,7 +6,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; -using FluentAssertions; +using Shouldly; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; @@ -60,12 +60,12 @@ public async Task FindIdentityResourcesByScopeNameAsync_should_populate_cache() { var cache = (MockCache) _provider.GetRequiredService>(); var store = _provider.GetRequiredService(); - cache.CacheItems.Count.Should().Be(0); + cache.CacheItems.Count.ShouldBe(0); var results = await store.FindIdentityResourcesByScopeNameAsync(new[] { "profile" }); - cache.CacheItems.Count.Should().Be(1); - cache.CacheItems.First().Value.Value.Name.Should().Be("profile"); + cache.CacheItems.Count.ShouldBe(1); + cache.CacheItems.First().Value.Value.Name.ShouldBe("profile"); } [Fact] @@ -74,12 +74,12 @@ public async Task FindApiResourcesByScopeNameAsync_should_populate_cache() var cache = (MockCache.ApiResourceNames>) _provider.GetRequiredService.ApiResourceNames>>(); var store = _provider.GetRequiredService(); - cache.CacheItems.Count.Should().Be(0); + cache.CacheItems.Count.ShouldBe(0); var results = await store.FindApiResourcesByScopeNameAsync(new[] { "scope1" }); - cache.CacheItems.Count.Should().Be(1); - cache.CacheItems.First().Value.Value.Names.Single().Should().Be("urn:api1"); + cache.CacheItems.Count.ShouldBe(1); + cache.CacheItems.First().Value.Value.Names.Single().ShouldBe("urn:api1"); } [Fact] @@ -87,12 +87,12 @@ public async Task FindApiScopesByNameAsync_should_populate_cache() { var cache = (MockCache) _provider.GetRequiredService>(); var store = _provider.GetRequiredService(); - cache.CacheItems.Count.Should().Be(0); + cache.CacheItems.Count.ShouldBe(0); var results = await store.FindApiScopesByNameAsync(new[] { "scope1" }); - cache.CacheItems.Count.Should().Be(1); - cache.CacheItems.First().Value.Value.Name.Should().Be("scope1"); + cache.CacheItems.Count.ShouldBe(1); + cache.CacheItems.First().Value.Value.Name.ShouldBe("scope1"); } } } diff --git a/identity-server/test/IdentityServer.UnitTests/Common/TestEventService.cs b/identity-server/test/IdentityServer.UnitTests/Common/TestEventService.cs index e57f70246..ddc80931d 100644 --- a/identity-server/test/IdentityServer.UnitTests/Common/TestEventService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Common/TestEventService.cs @@ -8,7 +8,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Events; using Duende.IdentityServer.Services; -using FluentAssertions; +using Shouldly; namespace UnitTests.Common; @@ -25,7 +25,7 @@ public Task RaiseAsync(Event evt) public T AssertEventWasRaised() where T : class { - _events.ContainsKey(typeof(T)).Should().BeTrue(); + _events.ContainsKey(typeof(T)).ShouldBeTrue(); return (T)_events.Where(x => x.Key == typeof(T)).Select(x=>x.Value).First(); } diff --git a/identity-server/test/IdentityServer.UnitTests/Cors/PolicyProviderTests.cs b/identity-server/test/IdentityServer.UnitTests/Cors/PolicyProviderTests.cs index 7fa66f4b6..e0c83197c 100644 --- a/identity-server/test/IdentityServer.UnitTests/Cors/PolicyProviderTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Cors/PolicyProviderTests.cs @@ -6,7 +6,7 @@ using Duende.IdentityServer.Configuration.DependencyInjection; using Duende.IdentityServer.Hosting; using Duende.IdentityServer.Services; -using FluentAssertions; +using Shouldly; using Microsoft.AspNetCore.Cors.Infrastructure; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; @@ -77,8 +77,8 @@ public async Task valid_paths_should_call_policy_service(string path) var response = await _subject.GetPolicyAsync(ctx, _options.Cors.CorsPolicyName); - _mockPolicy.WasCalled.Should().BeTrue(); - _mockInner.WasCalled.Should().BeFalse(); + _mockPolicy.WasCalled.ShouldBeTrue(); + _mockInner.WasCalled.ShouldBeFalse(); } [Theory] @@ -105,8 +105,8 @@ public async Task invalid_paths_should_not_call_policy_service(string path) var response = await _subject.GetPolicyAsync(ctx, _options.Cors.CorsPolicyName); - _mockPolicy.WasCalled.Should().BeFalse(); - _mockInner.WasCalled.Should().BeFalse(); + _mockPolicy.WasCalled.ShouldBeFalse(); + _mockInner.WasCalled.ShouldBeFalse(); } [Fact] @@ -128,8 +128,8 @@ public async Task different_policy_name_should_call_inner_policy_service() var response = await _subject.GetPolicyAsync(ctx, "wrong_name"); - _mockPolicy.WasCalled.Should().BeFalse(); - _mockInner.WasCalled.Should().BeTrue(); + _mockPolicy.WasCalled.ShouldBeFalse(); + _mockInner.WasCalled.ShouldBeTrue(); } [Fact] @@ -149,8 +149,8 @@ public async Task origin_same_as_server_should_not_call_policy() var response = await _subject.GetPolicyAsync(ctx, _options.Cors.CorsPolicyName); - _mockPolicy.WasCalled.Should().BeFalse(); - _mockInner.WasCalled.Should().BeFalse(); + _mockPolicy.WasCalled.ShouldBeFalse(); + _mockInner.WasCalled.ShouldBeFalse(); } [Theory] @@ -172,7 +172,7 @@ public async Task origin_not_same_as_server_should_call_policy(string origin) var response = await _subject.GetPolicyAsync(ctx, _options.Cors.CorsPolicyName); - _mockPolicy.WasCalled.Should().BeTrue(); - _mockInner.WasCalled.Should().BeFalse(); + _mockPolicy.WasCalled.ShouldBeTrue(); + _mockInner.WasCalled.ShouldBeFalse(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/AuthorizeCallbackEndpointTests.cs b/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/AuthorizeCallbackEndpointTests.cs index e340a5dc6..13dbcd214 100644 --- a/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/AuthorizeCallbackEndpointTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/AuthorizeCallbackEndpointTests.cs @@ -12,7 +12,7 @@ using Duende.IdentityServer.Extensions; using Duende.IdentityServer.Models; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; @@ -77,7 +77,7 @@ public async Task ProcessAsync_authorize_after_consent_path_should_return_author var result = await _subject.ProcessAsync(_context); - result.Should().BeOfType(); + result.ShouldBeOfType(); } [Fact] @@ -90,7 +90,7 @@ public async Task ProcessAsync_authorize_after_login_path_should_return_authoriz var result = await _subject.ProcessAsync(_context); - result.Should().BeOfType(); + result.ShouldBeOfType(); } [Fact] @@ -114,8 +114,8 @@ public async Task ProcessAsync_consent_missing_consent_data_should_return_error_ var result = await _subject.ProcessAsync(_context); - result.Should().BeOfType(); - ((AuthorizeResult)result).Response.IsError.Should().BeTrue(); + result.ShouldBeOfType(); + ((AuthorizeResult)result).Response.IsError.ShouldBeTrue(); } [Fact] @@ -141,7 +141,7 @@ public async Task ProcessAsync_no_consent_message_should_return_redirect_for_con var result = await _subject.ProcessAsync(_context); - result.Should().BeOfType(); + result.ShouldBeOfType(); } [Fact] @@ -153,8 +153,8 @@ public async Task ProcessAsync_post_to_entry_point_should_return_405() var result = await _subject.ProcessAsync(_context); var statusCode = result as StatusCodeResult; - statusCode.Should().NotBeNull(); - statusCode.StatusCode.Should().Be(405); + statusCode.ShouldNotBeNull(); + statusCode.StatusCode.ShouldBe(405); } [Fact] @@ -178,7 +178,7 @@ public async Task ProcessAsync_valid_consent_message_should_cleanup_consent_cook var result = await _subject.ProcessAsync(_context); - _mockUserConsentResponseMessageStore.Messages.Count.Should().Be(0); + _mockUserConsentResponseMessageStore.Messages.Count.ShouldBe(0); } [Fact] @@ -202,7 +202,7 @@ public async Task ProcessAsync_valid_consent_message_should_return_authorize_res var result = await _subject.ProcessAsync(_context); - result.Should().BeOfType(); + result.ShouldBeOfType(); } internal void Init() diff --git a/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/AuthorizeEndpointBaseTests.cs b/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/AuthorizeEndpointBaseTests.cs index 90ff79046..84a116fa5 100644 --- a/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/AuthorizeEndpointBaseTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/AuthorizeEndpointBaseTests.cs @@ -14,7 +14,7 @@ using Duende.IdentityServer.ResponseHandling; using Duende.IdentityServer.Services; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; @@ -72,9 +72,9 @@ public async Task error_resurect_with_prompt_none_should_include_session_state_i var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user); - result.Should().BeOfType(); - ((AuthorizeResult)result).Response.IsError.Should().BeTrue(); - ((AuthorizeResult)result).Response.SessionState.Should().NotBeNull(); + result.ShouldBeOfType(); + ((AuthorizeResult)result).Response.IsError.ShouldBeTrue(); + ((AuthorizeResult)result).Response.SessionState.ShouldNotBeNull(); } [Fact] @@ -86,8 +86,8 @@ public async Task authorize_request_validation_produces_error_should_display_err var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user); - result.Should().BeOfType(); - ((AuthorizeResult)result).Response.IsError.Should().BeTrue(); + result.ShouldBeOfType(); + ((AuthorizeResult)result).Response.IsError.ShouldBeTrue(); } [Fact] @@ -98,7 +98,7 @@ public async Task interaction_generator_consent_produces_consent_should_show_con var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user); - result.Should().BeOfType(); + result.ShouldBeOfType(); } [Fact] @@ -109,8 +109,8 @@ public async Task interaction_produces_error_should_show_error_page() var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user); - result.Should().BeOfType(); - ((AuthorizeResult)result).Response.IsError.Should().BeTrue(); + result.ShouldBeOfType(); + ((AuthorizeResult)result).Response.IsError.ShouldBeTrue(); } [Fact] @@ -124,10 +124,10 @@ public async Task interaction_produces_error_should_show_error_page_with_error_d var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user); - result.Should().BeOfType(); + result.ShouldBeOfType(); var authorizeResult = ((AuthorizeResult)result); - authorizeResult.Response.IsError.Should().BeTrue(); - authorizeResult.Response.ErrorDescription.Should().Be(errorDescription); + authorizeResult.Response.IsError.ShouldBeTrue(); + authorizeResult.Response.ErrorDescription.ShouldBe(errorDescription); } [Fact] @@ -138,7 +138,7 @@ public async Task interaction_produces_login_result_should_trigger_login() var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user); - result.Should().BeOfType(); + result.ShouldBeOfType(); } [Fact] @@ -150,7 +150,7 @@ public async Task ProcessAuthorizeRequestAsync_custom_interaction_redirect_resul var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user); - result.Should().BeOfType(); + result.ShouldBeOfType(); } [Fact] @@ -159,7 +159,7 @@ public async Task successful_authorization_request_should_generate_authorize_res { var result = await _subject.ProcessAuthorizeRequestAsync(_params, _user); - result.Should().BeOfType(); + result.ShouldBeOfType(); } internal void Init() diff --git a/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/AuthorizeEndpointTests.cs b/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/AuthorizeEndpointTests.cs index dd7da7b32..3ba30ac92 100644 --- a/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/AuthorizeEndpointTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Endpoints/Authorize/AuthorizeEndpointTests.cs @@ -11,7 +11,7 @@ using Duende.IdentityServer.Endpoints.Results; using Duende.IdentityServer.Models; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; @@ -65,7 +65,7 @@ public async Task ProcessAsync_authorize_path_should_return_authorization_result var result = await _subject.ProcessAsync(_context); - result.Should().BeOfType(); + result.ShouldBeOfType(); } [Fact] @@ -77,8 +77,8 @@ public async Task ProcessAsync_post_without_form_content_type_should_return_415( var result = await _subject.ProcessAsync(_context); var statusCode = result as StatusCodeResult; - statusCode.Should().NotBeNull(); - statusCode.StatusCode.Should().Be(415); + statusCode.ShouldNotBeNull(); + statusCode.StatusCode.ShouldBe(415); } internal void Init() diff --git a/identity-server/test/IdentityServer.UnitTests/Endpoints/EndSession/EndSessionCallbackResultTests.cs b/identity-server/test/IdentityServer.UnitTests/Endpoints/EndSession/EndSessionCallbackResultTests.cs index 069d83a29..6d98b63c3 100644 --- a/identity-server/test/IdentityServer.UnitTests/Endpoints/EndSession/EndSessionCallbackResultTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Endpoints/EndSession/EndSessionCallbackResultTests.cs @@ -7,7 +7,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Endpoints.Results; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Microsoft.AspNetCore.Http; using Xunit; @@ -41,7 +41,7 @@ public async Task default_options_should_emit_frame_src_csp_headers() await _subject.WriteHttpResponse(new EndSessionCallbackResult(_validationResult), ctx); - ctx.Response.Headers.ContentSecurityPolicy.First().Should().Contain("frame-src http://foo"); + ctx.Response.Headers.ContentSecurityPolicy.First().ShouldContain("frame-src http://foo"); } [Fact] @@ -55,6 +55,6 @@ public async Task relax_csp_options_should_prevent_frame_src_csp_headers() await _subject.WriteHttpResponse(new EndSessionCallbackResult(_validationResult), ctx); - ctx.Response.Headers.ContentSecurityPolicy.FirstOrDefault().Should().BeNull(); + ctx.Response.Headers.ContentSecurityPolicy.FirstOrDefault().ShouldBeNull(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/AuthorizeResultTests.cs b/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/AuthorizeResultTests.cs index 4720abecd..fe5306a15 100644 --- a/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/AuthorizeResultTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/AuthorizeResultTests.cs @@ -11,7 +11,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.ResponseHandling; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using Microsoft.AspNetCore.Http; @@ -57,12 +57,12 @@ public async Task error_should_redirect_to_error_page_and_passs_info() await _subject.WriteHttpResponse(new AuthorizeResult(_response), _context); - _mockErrorMessageStore.Messages.Count.Should().Be(1); - _context.Response.StatusCode.Should().Be(302); + _mockErrorMessageStore.Messages.Count.ShouldBe(1); + _context.Response.StatusCode.ShouldBe(302); var location = _context.Response.Headers.Location.First(); - location.Should().StartWith("https://server/error"); + location.ShouldStartWith("https://server/error"); var query = QueryHelpers.ParseQuery(new Uri(location).Query); - query["errorId"].First().Should().Be(_mockErrorMessageStore.Messages.First().Key); + query["errorId"].First().ShouldBe(_mockErrorMessageStore.Messages.First().Key); } [Theory] @@ -82,10 +82,10 @@ public async Task prompt_none_errors_should_return_to_client(string error) await _subject.WriteHttpResponse(new AuthorizeResult(_response), _context); - _mockUserSession.Clients.Count.Should().Be(0); - _context.Response.StatusCode.Should().Be(302); + _mockUserSession.Clients.Count.ShouldBe(0); + _context.Response.StatusCode.ShouldBe(302); var location = _context.Response.Headers.Location.First(); - location.Should().StartWith("http://client/callback"); + location.ShouldStartWith("http://client/callback"); } [Theory] @@ -106,10 +106,10 @@ public async Task prompt_none_errors_for_anonymous_users_should_include_session_ await _subject.WriteHttpResponse(new AuthorizeResult(_response), _context); - _mockUserSession.Clients.Count.Should().Be(0); - _context.Response.StatusCode.Should().Be(302); + _mockUserSession.Clients.Count.ShouldBe(0); + _context.Response.StatusCode.ShouldBe(302); var location = _context.Response.Headers.Location.First(); - location.Should().Contain("session_state=some_session_state"); + location.ShouldContain("session_state=some_session_state"); } [Fact] @@ -127,16 +127,16 @@ public async Task access_denied_should_return_to_client() await _subject.WriteHttpResponse(new AuthorizeResult(_response), _context); - _mockUserSession.Clients.Count.Should().Be(0); - _context.Response.StatusCode.Should().Be(302); + _mockUserSession.Clients.Count.ShouldBe(0); + _context.Response.StatusCode.ShouldBe(302); var location = _context.Response.Headers.Location.First(); - location.Should().StartWith("http://client/callback"); + location.ShouldStartWith("http://client/callback"); var queryString = new Uri(location).Query; var queryParams = QueryHelpers.ParseQuery(queryString); - queryParams["error"].Should().Equal(OidcConstants.AuthorizeErrors.AccessDenied); - queryParams["error_description"].Should().Equal(errorDescription); + queryParams["error"].ToString().ShouldBe(OidcConstants.AuthorizeErrors.AccessDenied); + queryParams["error_description"].ToString().ShouldBe(errorDescription); } [Fact] @@ -151,7 +151,7 @@ public async Task success_should_add_client_to_client_list() await _subject.WriteHttpResponse(new AuthorizeResult(_response), _context); - _mockUserSession.Clients.Should().Contain("client"); + _mockUserSession.Clients.ShouldContain("client"); } [Fact] @@ -167,13 +167,13 @@ public async Task query_mode_should_pass_results_in_query() await _subject.WriteHttpResponse(new AuthorizeResult(_response), _context); - _context.Response.StatusCode.Should().Be(302); - _context.Response.Headers.CacheControl.First().Should().Contain("no-store"); - _context.Response.Headers.CacheControl.First().Should().Contain("no-cache"); - _context.Response.Headers.CacheControl.First().Should().Contain("max-age=0"); + _context.Response.StatusCode.ShouldBe(302); + _context.Response.Headers.CacheControl.First().ShouldContain("no-store"); + _context.Response.Headers.CacheControl.First().ShouldContain("no-cache"); + _context.Response.Headers.CacheControl.First().ShouldContain("max-age=0"); var location = _context.Response.Headers.Location.First(); - location.Should().StartWith("http://client/callback"); - location.Should().Contain("?state=state"); + location.ShouldStartWith("http://client/callback"); + location.ShouldContain("?state=state"); } [Fact] @@ -189,13 +189,13 @@ public async Task fragment_mode_should_pass_results_in_fragment() await _subject.WriteHttpResponse(new AuthorizeResult(_response), _context); - _context.Response.StatusCode.Should().Be(302); - _context.Response.Headers.CacheControl.First().Should().Contain("no-store"); - _context.Response.Headers.CacheControl.First().Should().Contain("no-cache"); - _context.Response.Headers.CacheControl.First().Should().Contain("max-age=0"); + _context.Response.StatusCode.ShouldBe(302); + _context.Response.Headers.CacheControl.First().ShouldContain("no-store"); + _context.Response.Headers.CacheControl.First().ShouldContain("no-cache"); + _context.Response.Headers.CacheControl.First().ShouldContain("max-age=0"); var location = _context.Response.Headers.Location.First(); - location.Should().StartWith("http://client/callback"); - location.Should().Contain("#state=state"); + location.ShouldStartWith("http://client/callback"); + location.ShouldContain("#state=state"); } [Fact] @@ -211,22 +211,22 @@ public async Task form_post_mode_should_pass_results_in_body() await _subject.WriteHttpResponse(new AuthorizeResult(_response), _context); - _context.Response.StatusCode.Should().Be(200); - _context.Response.ContentType.Should().StartWith("text/html"); - _context.Response.Headers.CacheControl.First().Should().Contain("no-store"); - _context.Response.Headers.CacheControl.First().Should().Contain("no-cache"); - _context.Response.Headers.CacheControl.First().Should().Contain("max-age=0"); - _context.Response.Headers.ContentSecurityPolicy.First().Should().Contain("default-src 'none';"); - _context.Response.Headers.ContentSecurityPolicy.First().Should().Contain($"script-src '{IdentityServerConstants.ContentSecurityPolicyHashes.AuthorizeScript}'"); - _context.Response.Headers["X-Content-Security-Policy"].First().Should().Contain("default-src 'none';"); - _context.Response.Headers["X-Content-Security-Policy"].First().Should().Contain($"script-src '{IdentityServerConstants.ContentSecurityPolicyHashes.AuthorizeScript}'"); + _context.Response.StatusCode.ShouldBe(200); + _context.Response.ContentType.ShouldStartWith("text/html"); + _context.Response.Headers.CacheControl.First().ShouldContain("no-store"); + _context.Response.Headers.CacheControl.First().ShouldContain("no-cache"); + _context.Response.Headers.CacheControl.First().ShouldContain("max-age=0"); + _context.Response.Headers.ContentSecurityPolicy.First().ShouldContain("default-src 'none';"); + _context.Response.Headers.ContentSecurityPolicy.First().ShouldContain($"script-src '{IdentityServerConstants.ContentSecurityPolicyHashes.AuthorizeScript}'"); + _context.Response.Headers["X-Content-Security-Policy"].First().ShouldContain("default-src 'none';"); + _context.Response.Headers["X-Content-Security-Policy"].First().ShouldContain($"script-src '{IdentityServerConstants.ContentSecurityPolicyHashes.AuthorizeScript}'"); _context.Response.Body.Seek(0, SeekOrigin.Begin); using (var rdr = new StreamReader(_context.Response.Body)) { var html = rdr.ReadToEnd(); - html.Should().Contain(""); - html.Should().Contain("
"); - html.Should().Contain(""); + html.ShouldContain(""); + html.ShouldContain(""); + html.ShouldContain(""); } } @@ -245,8 +245,8 @@ public async Task form_post_mode_should_add_unsafe_inline_for_csp_level_1() await _subject.WriteHttpResponse(new AuthorizeResult(_response), _context); - _context.Response.Headers.ContentSecurityPolicy.First().Should().Contain($"script-src 'unsafe-inline' '{IdentityServerConstants.ContentSecurityPolicyHashes.AuthorizeScript}'"); - _context.Response.Headers["X-Content-Security-Policy"].First().Should().Contain($"script-src 'unsafe-inline' '{IdentityServerConstants.ContentSecurityPolicyHashes.AuthorizeScript}'"); + _context.Response.Headers.ContentSecurityPolicy.First().ShouldContain($"script-src 'unsafe-inline' '{IdentityServerConstants.ContentSecurityPolicyHashes.AuthorizeScript}'"); + _context.Response.Headers["X-Content-Security-Policy"].First().ShouldContain($"script-src 'unsafe-inline' '{IdentityServerConstants.ContentSecurityPolicyHashes.AuthorizeScript}'"); } [Fact] @@ -264,8 +264,8 @@ public async Task form_post_mode_should_not_add_deprecated_header_when_it_is_dis await _subject.WriteHttpResponse(new AuthorizeResult(_response), _context); - _context.Response.Headers.ContentSecurityPolicy.First().Should().Contain($"script-src '{IdentityServerConstants.ContentSecurityPolicyHashes.AuthorizeScript}'"); - _context.Response.Headers["X-Content-Security-Policy"].Should().BeEmpty(); + _context.Response.Headers.ContentSecurityPolicy.First().ShouldContain($"script-src '{IdentityServerConstants.ContentSecurityPolicyHashes.AuthorizeScript}'"); + _context.Response.Headers["X-Content-Security-Policy"].ShouldBeEmpty(); } [InlineData(OidcConstants.AuthorizeErrors.AccessDenied)] diff --git a/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/CheckSessionResultTests.cs b/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/CheckSessionResultTests.cs index a043e4538..a4d05c8b9 100644 --- a/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/CheckSessionResultTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/CheckSessionResultTests.cs @@ -9,7 +9,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Endpoints.Results; using Duende.IdentityServer.Models; -using FluentAssertions; +using Shouldly; using Microsoft.AspNetCore.Http; using Xunit; @@ -39,17 +39,17 @@ public async Task should_pass_results_in_body() { await _subject.WriteHttpResponse(new CheckSessionResult(), _context); - _context.Response.StatusCode.Should().Be(200); - _context.Response.ContentType.Should().StartWith("text/html"); - _context.Response.Headers.ContentSecurityPolicy.First().Should().Contain("default-src 'none';"); - _context.Response.Headers.ContentSecurityPolicy.First().Should().Contain($"script-src '{IdentityServerConstants.ContentSecurityPolicyHashes.CheckSessionScript}'"); - _context.Response.Headers["X-Content-Security-Policy"].First().Should().Contain("default-src 'none';"); - _context.Response.Headers["X-Content-Security-Policy"].First().Should().Contain($"script-src '{IdentityServerConstants.ContentSecurityPolicyHashes.CheckSessionScript}'"); + _context.Response.StatusCode.ShouldBe(200); + _context.Response.ContentType.ShouldStartWith("text/html"); + _context.Response.Headers.ContentSecurityPolicy.First().ShouldContain("default-src 'none';"); + _context.Response.Headers.ContentSecurityPolicy.First().ShouldContain($"script-src '{IdentityServerConstants.ContentSecurityPolicyHashes.CheckSessionScript}'"); + _context.Response.Headers["X-Content-Security-Policy"].First().ShouldContain("default-src 'none';"); + _context.Response.Headers["X-Content-Security-Policy"].First().ShouldContain($"script-src '{IdentityServerConstants.ContentSecurityPolicyHashes.CheckSessionScript}'"); _context.Response.Body.Seek(0, SeekOrigin.Begin); using (var rdr = new StreamReader(_context.Response.Body)) { var html = rdr.ReadToEnd(); - html.Should().Contain(""); + html.ShouldContain(""); } } @@ -60,8 +60,8 @@ public async Task form_post_mode_should_add_unsafe_inline_for_csp_level_1() await _subject.WriteHttpResponse(new CheckSessionResult(), _context); - _context.Response.Headers.ContentSecurityPolicy.First().Should().Contain($"script-src 'unsafe-inline' '{IdentityServerConstants.ContentSecurityPolicyHashes.CheckSessionScript}'"); - _context.Response.Headers["X-Content-Security-Policy"].First().Should().Contain($"script-src 'unsafe-inline' '{IdentityServerConstants.ContentSecurityPolicyHashes.CheckSessionScript}'"); + _context.Response.Headers.ContentSecurityPolicy.First().ShouldContain($"script-src 'unsafe-inline' '{IdentityServerConstants.ContentSecurityPolicyHashes.CheckSessionScript}'"); + _context.Response.Headers["X-Content-Security-Policy"].First().ShouldContain($"script-src 'unsafe-inline' '{IdentityServerConstants.ContentSecurityPolicyHashes.CheckSessionScript}'"); } [Fact] @@ -71,8 +71,8 @@ public async Task form_post_mode_should_not_add_deprecated_header_when_it_is_dis await _subject.WriteHttpResponse(new CheckSessionResult(), _context); - _context.Response.Headers.ContentSecurityPolicy.First().Should().Contain($"script-src '{IdentityServerConstants.ContentSecurityPolicyHashes.CheckSessionScript}'"); - _context.Response.Headers["X-Content-Security-Policy"].Should().BeEmpty(); + _context.Response.Headers.ContentSecurityPolicy.First().ShouldContain($"script-src '{IdentityServerConstants.ContentSecurityPolicyHashes.CheckSessionScript}'"); + _context.Response.Headers["X-Content-Security-Policy"].ShouldBeEmpty(); } [Theory] @@ -87,7 +87,7 @@ public async Task can_change_cached_cookiename(string cookieName) using (var rdr = new StreamReader(_context.Response.Body)) { var html = rdr.ReadToEnd(); - html.Should().Contain($""); + html.ShouldContain($""); } } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/EndSessionCallbackResultTests.cs b/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/EndSessionCallbackResultTests.cs index a391a9a56..1ff46b038 100644 --- a/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/EndSessionCallbackResultTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/EndSessionCallbackResultTests.cs @@ -9,7 +9,7 @@ using Duende.IdentityServer.Endpoints.Results; using Duende.IdentityServer.Models; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Microsoft.AspNetCore.Http; using Xunit; @@ -41,7 +41,7 @@ public async Task error_should_return_400() await _subject.WriteHttpResponse(new EndSessionCallbackResult(_result), _context); - _context.Response.StatusCode.Should().Be(400); + _context.Response.StatusCode.ShouldBe(400); } [Fact] @@ -52,22 +52,22 @@ public async Task success_should_render_html_and_iframes() await _subject.WriteHttpResponse(new EndSessionCallbackResult(_result), _context); - _context.Response.ContentType.Should().StartWith("text/html"); - _context.Response.Headers.CacheControl.First().Should().Contain("no-store"); - _context.Response.Headers.CacheControl.First().Should().Contain("no-cache"); - _context.Response.Headers.CacheControl.First().Should().Contain("max-age=0"); - _context.Response.Headers.ContentSecurityPolicy.First().Should().Contain("default-src 'none';"); - _context.Response.Headers.ContentSecurityPolicy.First().Should().Contain("style-src 'sha256-e6FQZewefmod2S/5T11pTXjzE2vn3/8GRwWOs917YE4=';"); - _context.Response.Headers.ContentSecurityPolicy.First().Should().Contain("frame-src http://foo.com http://bar.com"); - _context.Response.Headers["X-Content-Security-Policy"].First().Should().Contain("default-src 'none';"); - _context.Response.Headers["X-Content-Security-Policy"].First().Should().Contain("style-src 'sha256-e6FQZewefmod2S/5T11pTXjzE2vn3/8GRwWOs917YE4=';"); - _context.Response.Headers["X-Content-Security-Policy"].First().Should().Contain("frame-src http://foo.com http://bar.com"); + _context.Response.ContentType.ShouldStartWith("text/html"); + _context.Response.Headers.CacheControl.First().ShouldContain("no-store"); + _context.Response.Headers.CacheControl.First().ShouldContain("no-cache"); + _context.Response.Headers.CacheControl.First().ShouldContain("max-age=0"); + _context.Response.Headers.ContentSecurityPolicy.First().ShouldContain("default-src 'none';"); + _context.Response.Headers.ContentSecurityPolicy.First().ShouldContain("style-src 'sha256-e6FQZewefmod2S/5T11pTXjzE2vn3/8GRwWOs917YE4=';"); + _context.Response.Headers.ContentSecurityPolicy.First().ShouldContain("frame-src http://foo.com http://bar.com"); + _context.Response.Headers["X-Content-Security-Policy"].First().ShouldContain("default-src 'none';"); + _context.Response.Headers["X-Content-Security-Policy"].First().ShouldContain("style-src 'sha256-e6FQZewefmod2S/5T11pTXjzE2vn3/8GRwWOs917YE4=';"); + _context.Response.Headers["X-Content-Security-Policy"].First().ShouldContain("frame-src http://foo.com http://bar.com"); _context.Response.Body.Seek(0, SeekOrigin.Begin); using (var rdr = new StreamReader(_context.Response.Body)) { var html = rdr.ReadToEnd(); - html.Should().Contain(""); - html.Should().Contain(""); + html.ShouldContain(""); + html.ShouldContain(""); } } @@ -80,8 +80,8 @@ public async Task fsuccess_should_add_unsafe_inline_for_csp_level_1() await _subject.WriteHttpResponse(new EndSessionCallbackResult(_result), _context); - _context.Response.Headers.ContentSecurityPolicy.First().Should().Contain("style-src 'unsafe-inline' 'sha256-e6FQZewefmod2S/5T11pTXjzE2vn3/8GRwWOs917YE4='"); - _context.Response.Headers["X-Content-Security-Policy"].First().Should().Contain("style-src 'unsafe-inline' 'sha256-e6FQZewefmod2S/5T11pTXjzE2vn3/8GRwWOs917YE4='"); + _context.Response.Headers.ContentSecurityPolicy.First().ShouldContain("style-src 'unsafe-inline' 'sha256-e6FQZewefmod2S/5T11pTXjzE2vn3/8GRwWOs917YE4='"); + _context.Response.Headers["X-Content-Security-Policy"].First().ShouldContain("style-src 'unsafe-inline' 'sha256-e6FQZewefmod2S/5T11pTXjzE2vn3/8GRwWOs917YE4='"); } [Fact] @@ -93,7 +93,7 @@ public async Task form_post_mode_should_not_add_deprecated_header_when_it_is_dis await _subject.WriteHttpResponse(new EndSessionCallbackResult(_result), _context); - _context.Response.Headers.ContentSecurityPolicy.First().Should().Contain("style-src 'sha256-e6FQZewefmod2S/5T11pTXjzE2vn3/8GRwWOs917YE4='"); - _context.Response.Headers["X-Content-Security-Policy"].Should().BeEmpty(); + _context.Response.Headers.ContentSecurityPolicy.First().ShouldContain("style-src 'sha256-e6FQZewefmod2S/5T11pTXjzE2vn3/8GRwWOs917YE4='"); + _context.Response.Headers["X-Content-Security-Policy"].ShouldBeEmpty(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/EndSessionResultTests.cs b/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/EndSessionResultTests.cs index ac6ef9f5b..a93e66366 100644 --- a/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/EndSessionResultTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Endpoints/Results/EndSessionResultTests.cs @@ -9,7 +9,7 @@ using Duende.IdentityServer.Endpoints.Results; using Duende.IdentityServer.Models; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.WebUtilities; @@ -57,12 +57,12 @@ public async Task validated_signout_should_pass_logout_message() await _subject.WriteHttpResponse(new EndSessionResult(_result), _context); - _mockLogoutMessageStore.Messages.Count.Should().Be(1); + _mockLogoutMessageStore.Messages.Count.ShouldBe(1); var location = _context.Response.Headers.Location.Single(); var query = QueryHelpers.ParseQuery(new Uri(location).Query); - location.Should().StartWith("https://server/logout"); - query["logoutId"].First().Should().Be(_mockLogoutMessageStore.Messages.First().Key); + location.ShouldStartWith("https://server/logout"); + query["logoutId"].First().ShouldBe(_mockLogoutMessageStore.Messages.First().Key); } [Fact] @@ -72,12 +72,12 @@ public async Task unvalidated_signout_should_not_pass_logout_message() await _subject.WriteHttpResponse(new EndSessionResult(_result), _context); - _mockLogoutMessageStore.Messages.Count.Should().Be(0); + _mockLogoutMessageStore.Messages.Count.ShouldBe(0); var location = _context.Response.Headers.Location.Single(); var query = QueryHelpers.ParseQuery(new Uri(location).Query); - location.Should().StartWith("https://server/logout"); - query.Count.Should().Be(0); + location.ShouldStartWith("https://server/logout"); + query.Count.ShouldBe(0); } [Fact] @@ -95,11 +95,11 @@ public async Task error_result_should_not_pass_logout_message() await _subject.WriteHttpResponse(new EndSessionResult(_result), _context); - _mockLogoutMessageStore.Messages.Count.Should().Be(0); + _mockLogoutMessageStore.Messages.Count.ShouldBe(0); var location = _context.Response.Headers.Location.Single(); var query = QueryHelpers.ParseQuery(new Uri(location).Query); - location.Should().StartWith("https://server/logout"); - query.Count.Should().Be(0); + location.ShouldStartWith("https://server/logout"); + query.Count.ShouldBe(0); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Events/EventTests.cs b/identity-server/test/IdentityServer.UnitTests/Events/EventTests.cs index 25eed4f06..29c31eab2 100644 --- a/identity-server/test/IdentityServer.UnitTests/Events/EventTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Events/EventTests.cs @@ -11,7 +11,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.ResponseHandling; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using Microsoft.AspNetCore.Http; @@ -39,7 +39,7 @@ public void UnhandledExceptionEventCanCallToString() var s = unhandledExceptionEvent.ToString(); - s.Should().NotBeNullOrEmpty(); + s.ShouldNotBeNullOrEmpty(); } } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Extensions/ApiResourceSigningAlgorithmSelectionTests.cs b/identity-server/test/IdentityServer.UnitTests/Extensions/ApiResourceSigningAlgorithmSelectionTests.cs index d0cfe6d55..7857032b8 100644 --- a/identity-server/test/IdentityServer.UnitTests/Extensions/ApiResourceSigningAlgorithmSelectionTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Extensions/ApiResourceSigningAlgorithmSelectionTests.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; using System.Linq; using Duende.IdentityServer.Models; -using FluentAssertions; +using Shouldly; using Xunit; namespace UnitTests.Extensions; @@ -20,7 +20,7 @@ public void Single_resource_no_allowed_algorithms_set_should_return_empty_list() var allowedAlgorithms = new List { resource }.FindMatchingSigningAlgorithms(); - allowedAlgorithms.Count.Should().Be(0); + allowedAlgorithms.Count.ShouldBe(0); } [Fact] @@ -31,7 +31,7 @@ public void Two_resources_no_allowed_algorithms_set_should_return_empty_list() var allowedAlgorithms = new List { resource1, resource2 }.FindMatchingSigningAlgorithms(); - allowedAlgorithms.Count.Should().Be(0); + allowedAlgorithms.Count.ShouldBe(0); } [Theory] @@ -73,12 +73,12 @@ public void Two_resources_with_allowed_algorithms_set_should_return_right_values if (expectedAlgorithms.Any()) { var allowedAlgorithms = new List { resource1, resource2 }.FindMatchingSigningAlgorithms(); - allowedAlgorithms.Should().BeEquivalentTo(expectedAlgorithms); + allowedAlgorithms.ShouldBeEquivalentTo(expectedAlgorithms); } else { Action act = () => new List { resource1, resource2 }.FindMatchingSigningAlgorithms(); - act.Should().Throw(); + act.ShouldThrow(); } } @@ -132,12 +132,12 @@ public void Three_resources_with_allowed_algorithms_set_should_return_right_valu if (expectedAlgorithms.Any()) { var allowedAlgorithms = new List {resource1, resource2, resource3}.FindMatchingSigningAlgorithms(); - allowedAlgorithms.Should().BeEquivalentTo(expectedAlgorithms); + allowedAlgorithms.ShouldBeEquivalentTo(expectedAlgorithms); } else { Action act = () => new List {resource1, resource2, resource3}.FindMatchingSigningAlgorithms(); - act.Should().Throw(); + act.ShouldThrow(); } } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Extensions/HttpRequestExtensionsTests.cs b/identity-server/test/IdentityServer.UnitTests/Extensions/HttpRequestExtensionsTests.cs index b7d335472..b3d829775 100644 --- a/identity-server/test/IdentityServer.UnitTests/Extensions/HttpRequestExtensionsTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Extensions/HttpRequestExtensionsTests.cs @@ -3,7 +3,7 @@ using Duende.IdentityServer.Extensions; -using FluentAssertions; +using Shouldly; using Microsoft.AspNetCore.Http; using Xunit; @@ -19,7 +19,7 @@ public void GetCorsOrigin_valid_cors_request_should_return_cors_origin() ctx.Request.Host = new HostString("foo"); ctx.Request.Headers.Append("Origin", "http://bar"); - ctx.Request.GetCorsOrigin().Should().Be("http://bar"); + ctx.Request.GetCorsOrigin().ShouldBe("http://bar"); } [Fact] @@ -30,7 +30,7 @@ public void GetCorsOrigin_origin_from_same_host_should_not_return_cors_origin() ctx.Request.Host = new HostString("foo"); ctx.Request.Headers.Append("Origin", "http://foo"); - ctx.Request.GetCorsOrigin().Should().BeNull(); + ctx.Request.GetCorsOrigin().ShouldBeNull(); } [Fact] @@ -40,6 +40,6 @@ public void GetCorsOrigin_no_origin_should_not_return_cors_origin() ctx.Request.Scheme = "http"; ctx.Request.Host = new HostString("foo"); - ctx.Request.GetCorsOrigin().Should().BeNull(); + ctx.Request.GetCorsOrigin().ShouldBeNull(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Extensions/IResourceStoreExtensionsTests.cs b/identity-server/test/IdentityServer.UnitTests/Extensions/IResourceStoreExtensionsTests.cs index f2de56e6e..53f3f3dbd 100644 --- a/identity-server/test/IdentityServer.UnitTests/Extensions/IResourceStoreExtensionsTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Extensions/IResourceStoreExtensionsTests.cs @@ -8,7 +8,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; -using FluentAssertions; +using Shouldly; using Xunit; namespace UnitTests.Extensions; @@ -26,7 +26,7 @@ public async Task GetAllEnabledResourcesAsync_on_duplicate_identity_scopes_shoul }; Func a = () => store.GetAllEnabledResourcesAsync(); - await a.Should().ThrowAsync().WithMessage("duplicate identity scopes*"); + await a.ShouldThrowAsync("duplicate identity scopes*"); } [Fact] @@ -51,7 +51,7 @@ public async Task GetAllEnabledResourcesAsync_on_duplicate_api_resources_should_ }; Func a = () => store.GetAllEnabledResourcesAsync(); - await a.Should().ThrowAsync().WithMessage("duplicate api resources*"); + await a.ShouldThrowAsync("duplicate api resources*"); } [Fact] @@ -76,7 +76,7 @@ public async Task FindResourcesByScopeAsync_on_duplicate_identity_scopes_should_ }; Func a = () => store.FindResourcesByScopeAsync(new string[] { "A" }); - await a.Should().ThrowAsync().WithMessage("duplicate identity scopes*"); + await a.ShouldThrowAsync("duplicate identity scopes*"); } [Fact] @@ -107,10 +107,10 @@ public async Task FindResourcesByScopeAsync_on_duplicate_api_scopes_should_succe }; var result = await store.FindResourcesByScopeAsync(new string[] { "a" }); - result.ApiResources.Count.Should().Be(2); - result.ApiScopes.Count.Should().Be(1); - result.ApiResources.Select(x => x.Name).Should().BeEquivalentTo(new[] { "api1", "api2" }); - result.ApiScopes.Select(x => x.Name).Should().BeEquivalentTo(new[] { "a" }); + result.ApiResources.Count.ShouldBe(2); + result.ApiScopes.Count.ShouldBe(1); + result.ApiResources.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "api1", "api2" }); + result.ApiScopes.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "a" }); } [Fact] @@ -140,7 +140,7 @@ public async Task FindResourcesByScopeAsync_with_duplicate_api_scopes_on_single_ }; var result = await store.FindResourcesByScopeAsync(new string[] { "a" }); - result.ApiResources.Count.Should().Be(1); + result.ApiResources.Count.ShouldBe(1); } public class MockResourceStore : IResourceStore diff --git a/identity-server/test/IdentityServer.UnitTests/Extensions/IdentityServerBuilderExtensionsCacheStoreTests.cs b/identity-server/test/IdentityServer.UnitTests/Extensions/IdentityServerBuilderExtensionsCacheStoreTests.cs index 11f33a2b4..662f5bd9d 100644 --- a/identity-server/test/IdentityServer.UnitTests/Extensions/IdentityServerBuilderExtensionsCacheStoreTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Extensions/IdentityServerBuilderExtensionsCacheStoreTests.cs @@ -8,7 +8,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; -using FluentAssertions; +using Shouldly; using Microsoft.Extensions.DependencyInjection; using Xunit; @@ -60,7 +60,7 @@ public void AddClientStoreCache_should_add_concrete_iclientstore_implementation( identityServerBuilder.AddClientStoreCache(); - services.Any(x => x.ImplementationType == typeof(CustomClientStore)).Should().BeTrue(); + services.Any(x => x.ImplementationType == typeof(CustomClientStore)).ShouldBeTrue(); } [Fact] @@ -71,6 +71,6 @@ public void AddResourceStoreCache_should_attempt_to_register_iresourcestore_impl identityServerBuilder.AddResourceStoreCache(); - services.Any(x => x.ImplementationType == typeof(CustomResourceStore)).Should().BeTrue(); + services.Any(x => x.ImplementationType == typeof(CustomResourceStore)).ShouldBeTrue(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Extensions/StringExtensionsTests.cs b/identity-server/test/IdentityServer.UnitTests/Extensions/StringExtensionsTests.cs index 2585626b5..51e7434d1 100644 --- a/identity-server/test/IdentityServer.UnitTests/Extensions/StringExtensionsTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Extensions/StringExtensionsTests.cs @@ -4,7 +4,7 @@ using Xunit; using Duende.IdentityServer.Extensions; -using FluentAssertions; +using Shouldly; using System.Linq; namespace UnitTests.Extensions; @@ -82,7 +82,7 @@ public void TestGetOrigin() public void ToSpaceSeparatedString_should_return_correct_value() { var value = new[] { "foo", "bar", "baz", "baz", "foo", "bar" }.ToSpaceSeparatedString(); - value.Should().Be("foo bar baz baz foo bar"); + value.ShouldBe("foo bar baz baz foo bar"); } [Fact] @@ -90,13 +90,13 @@ public void ToSpaceSeparatedString_should_return_correct_value() public void FromSpaceSeparatedString_should_return_correct_values() { var values = "foo bar baz baz foo bar".FromSpaceSeparatedString().ToArray(); - values.Length.Should().Be(6); - values[0].Should().Be("foo"); - values[1].Should().Be("bar"); - values[2].Should().Be("baz"); - values[3].Should().Be("baz"); - values[4].Should().Be("foo"); - values[5].Should().Be("bar"); + values.Length.ShouldBe(6); + values[0].ShouldBe("foo"); + values[1].ShouldBe("bar"); + values[2].ShouldBe("baz"); + values[3].ShouldBe("baz"); + values[4].ShouldBe("foo"); + values[5].ShouldBe("bar"); } [Fact] @@ -104,11 +104,11 @@ public void FromSpaceSeparatedString_should_return_correct_values() public void FromSpaceSeparatedString_should_only_process_spaces() { var values = "foo bar\tbaz baz\rfoo bar\r\nbar".FromSpaceSeparatedString().ToArray(); - values.Length.Should().Be(4); - values[0].Should().Be("foo"); - values[1].Should().Be("bar\tbaz"); - values[2].Should().Be("baz\rfoo"); - values[3].Should().Be("bar\r\nbar"); + values.Length.ShouldBe(4); + values[0].ShouldBe("foo"); + values[1].ShouldBe("bar\tbaz"); + values[2].ShouldBe("baz\rfoo"); + values[3].ShouldBe("bar\r\nbar"); } @@ -120,7 +120,7 @@ public void Parse_Scopes_with_Empty_Scope_List() { var scopes = string.Empty.ParseScopesString(); - scopes.Should().BeNull(); + scopes.ShouldBeNull(); } [Fact] @@ -129,11 +129,11 @@ public void Parse_Scopes_with_Sorting() { var scopes = "scope3 scope2 scope1".ParseScopesString(); - scopes.Count.Should().Be(3); + scopes.Count.ShouldBe(3); - scopes[0].Should().Be("scope1"); - scopes[1].Should().Be("scope2"); - scopes[2].Should().Be("scope3"); + scopes[0].ShouldBe("scope1"); + scopes[1].ShouldBe("scope2"); + scopes[2].ShouldBe("scope3"); } [Fact] @@ -142,11 +142,11 @@ public void Parse_Scopes_with_Extra_Spaces() { var scopes = " scope3 scope2 scope1 ".ParseScopesString(); - scopes.Count.Should().Be(3); + scopes.Count.ShouldBe(3); - scopes[0].Should().Be("scope1"); - scopes[1].Should().Be("scope2"); - scopes[2].Should().Be("scope3"); + scopes[0].ShouldBe("scope1"); + scopes[1].ShouldBe("scope2"); + scopes[2].ShouldBe("scope3"); } [Fact] @@ -155,19 +155,19 @@ public void Parse_Scopes_with_Duplicate_Scope() { var scopes = "scope2 scope1 scope2".ParseScopesString(); - scopes.Count.Should().Be(2); + scopes.Count.ShouldBe(2); - scopes[0].Should().Be("scope1"); - scopes[1].Should().Be("scope2"); + scopes[0].ShouldBe("scope1"); + scopes[1].ShouldBe("scope2"); } [Fact] [Trait("Category", Category)] public void IsUri_should_allow_uris() { - "https://path".IsUri().Should().BeTrue(); - "https://path?foo=[x]".IsUri().Should().BeTrue(); - "file://path".IsUri().Should().BeTrue(); + "https://path".IsUri().ShouldBeTrue(); + "https://path?foo=[x]".IsUri().ShouldBeTrue(); + "file://path".IsUri().ShouldBeTrue(); } [Fact] @@ -176,12 +176,12 @@ public void IsUri_should_block_paths() { // especially on linux // https://github.com/DuendeSoftware/Support/issues/148 - " /path".IsUri().Should().BeFalse(); - "/path".IsUri().Should().BeFalse(); - " //".IsUri().Should().BeFalse(); - "//".IsUri().Should().BeFalse(); - "://".IsUri().Should().BeFalse(); - " ://".IsUri().Should().BeFalse(); - " file://path".IsUri().Should().BeFalse(); + " /path".IsUri().ShouldBeFalse(); + "/path".IsUri().ShouldBeFalse(); + " //".IsUri().ShouldBeFalse(); + "//".IsUri().ShouldBeFalse(); + "://".IsUri().ShouldBeFalse(); + " ://".IsUri().ShouldBeFalse(); + " file://path".IsUri().ShouldBeFalse(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Hosting/EndpointRouterTests.cs b/identity-server/test/IdentityServer.UnitTests/Hosting/EndpointRouterTests.cs index ee7915f95..dc9d9140a 100644 --- a/identity-server/test/IdentityServer.UnitTests/Hosting/EndpointRouterTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Hosting/EndpointRouterTests.cs @@ -9,7 +9,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Hosting; using Duende.IdentityServer.Licensing.V2; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging.Abstractions; @@ -38,7 +38,7 @@ public EndpointRouterTests() public void Endpoint_ctor_requires_path_to_start_with_slash() { Action a = () => new Duende.IdentityServer.Hosting.Endpoint("ep1", "ep1", typeof(MyEndpointHandler)); - a.Should().Throw(); + a.ShouldThrow(); } [Fact] @@ -52,7 +52,7 @@ public void Find_should_return_null_for_incorrect_path() ctx.RequestServices = new StubServiceProvider(); var result = _subject.Find(ctx); - result.Should().BeNull(); + result.ShouldBeNull(); } [Fact] @@ -66,7 +66,7 @@ public void Find_should_find_path() ctx.RequestServices = new StubServiceProvider(); var result = _subject.Find(ctx); - result.Should().BeOfType(); + result.ShouldBeOfType(); } [Fact] @@ -80,7 +80,7 @@ public void Find_should_not_find_nested_paths() ctx.RequestServices = new StubServiceProvider(); var result = _subject.Find(ctx); - result.Should().BeNull(); + result.ShouldBeNull(); } [Fact] @@ -94,7 +94,7 @@ public void Find_should_find_first_registered_mapping() ctx.RequestServices = new StubServiceProvider(); var result = _subject.Find(ctx); - result.Should().BeOfType(); + result.ShouldBeOfType(); } [Fact] @@ -110,7 +110,7 @@ public void Find_should_return_null_for_disabled_endpoint() ctx.RequestServices = new StubServiceProvider(); var result = _subject.Find(ctx); - result.Should().BeNull(); + result.ShouldBeNull(); } private class MyEndpointHandler : IEndpointHandler diff --git a/identity-server/test/IdentityServer.UnitTests/IdentityServer.UnitTests.csproj b/identity-server/test/IdentityServer.UnitTests/IdentityServer.UnitTests.csproj index 85e2bc58b..5021b472a 100644 --- a/identity-server/test/IdentityServer.UnitTests/IdentityServer.UnitTests.csproj +++ b/identity-server/test/IdentityServer.UnitTests/IdentityServer.UnitTests.csproj @@ -11,7 +11,7 @@ - + @@ -24,6 +24,7 @@ + diff --git a/identity-server/test/IdentityServer.UnitTests/Infrastructure/ObjectSerializerTests.cs b/identity-server/test/IdentityServer.UnitTests/Infrastructure/ObjectSerializerTests.cs index ea5051ff1..0ec6f62f5 100644 --- a/identity-server/test/IdentityServer.UnitTests/Infrastructure/ObjectSerializerTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Infrastructure/ObjectSerializerTests.cs @@ -4,7 +4,7 @@ using System; using Duende.IdentityServer.Models; -using FluentAssertions; +using Shouldly; using Xunit; namespace UnitTests.Infrastructure; @@ -19,6 +19,6 @@ public ObjectSerializerTests() public void Can_be_deserialize_message() { Action a = () => Duende.IdentityServer.ObjectSerializer.FromString>("{\"created\":0, \"data\": {\"error\": \"error\"}}"); - a.Should().NotThrow(); + a.ShouldNotThrow(); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Licensing/IdentityServerLicenseValidatorTests.cs b/identity-server/test/IdentityServer.UnitTests/Licensing/IdentityServerLicenseValidatorTests.cs index 852b76b0b..cd3020a2e 100644 --- a/identity-server/test/IdentityServer.UnitTests/Licensing/IdentityServerLicenseValidatorTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Licensing/IdentityServerLicenseValidatorTests.cs @@ -6,7 +6,7 @@ using System.Security.Claims; using Duende; using Duende.IdentityServer; -using FluentAssertions; +using Shouldly; using Xunit; using static Duende.License; @@ -24,8 +24,8 @@ public void license_should_parse_company_data() new Claim("edition", "enterprise"), new Claim("company_name", "foo"), new Claim("contact_info", "bar")); - subject.CompanyName.Should().Be("foo"); - subject.ContactInfo.Should().Be("bar"); + subject.CompanyName.ShouldBe("foo"); + subject.ContactInfo.ShouldBe("bar"); } [Fact] @@ -34,7 +34,7 @@ public void license_should_parse_expiration() { { var subject = new IdentityServerLicense(new Claim("edition", "enterprise")); - subject.Expiration.Should().BeNull(); + subject.Expiration.ShouldBeNull(); } { @@ -42,7 +42,7 @@ public void license_should_parse_expiration() var subject = new IdentityServerLicense( new Claim("edition", "enterprise"), new Claim("exp", exp.ToString())); - subject.Expiration.Should().Be(new DateTime(2020, 1, 12, 13, 5, 0, DateTimeKind.Utc)); + subject.Expiration.ShouldBe(new DateTime(2020, 1, 12, 13, 5, 0, DateTimeKind.Utc)); } } @@ -53,149 +53,149 @@ public void license_should_parse_edition_and_use_default_values() // non-ISV { var subject = new IdentityServerLicense(new Claim("edition", "enterprise")); - subject.Edition.Should().Be(LicenseEdition.Enterprise); - subject.IsEnterpriseEdition.Should().BeTrue(); - subject.ClientLimit.Should().BeNull(); - subject.IssuerLimit.Should().BeNull(); - subject.KeyManagementFeature.Should().BeTrue(); - subject.ResourceIsolationFeature.Should().BeTrue(); - subject.DynamicProvidersFeature.Should().BeTrue(); - subject.ServerSideSessionsFeature.Should().BeTrue(); - //subject.ConfigApiFeature.Should().BeTrue(); - subject.DPoPFeature.Should().BeTrue(); - //subject.BffFeature.Should().BeTrue(); - subject.RedistributionFeature.Should().BeFalse(); - subject.CibaFeature.Should().BeTrue(); - subject.ParFeature.Should().BeTrue(); + subject.Edition.ShouldBe(LicenseEdition.Enterprise); + subject.IsEnterpriseEdition.ShouldBeTrue(); + subject.ClientLimit.ShouldBeNull(); + subject.IssuerLimit.ShouldBeNull(); + subject.KeyManagementFeature.ShouldBeTrue(); + subject.ResourceIsolationFeature.ShouldBeTrue(); + subject.DynamicProvidersFeature.ShouldBeTrue(); + subject.ServerSideSessionsFeature.ShouldBeTrue(); + //subject.ConfigApiFeature.ShouldBeTrue(); + subject.DPoPFeature.ShouldBeTrue(); + //subject.BffFeature.ShouldBeTrue(); + subject.RedistributionFeature.ShouldBeFalse(); + subject.CibaFeature.ShouldBeTrue(); + subject.ParFeature.ShouldBeTrue(); } { var subject = new IdentityServerLicense(new Claim("edition", "business")); - subject.Edition.Should().Be(LicenseEdition.Business); - subject.IsBusinessEdition.Should().BeTrue(); - subject.ClientLimit.Should().Be(15); - subject.IssuerLimit.Should().Be(1); - subject.KeyManagementFeature.Should().BeTrue(); - subject.ResourceIsolationFeature.Should().BeFalse(); - subject.DynamicProvidersFeature.Should().BeFalse(); - subject.ServerSideSessionsFeature.Should().BeTrue(); - //subject.ConfigApiFeature.Should().BeTrue(); - subject.DPoPFeature.Should().BeFalse(); - //subject.BffFeature.Should().BeTrue(); - subject.RedistributionFeature.Should().BeFalse(); - subject.CibaFeature.Should().BeFalse(); - subject.ParFeature.Should().BeTrue(); + subject.Edition.ShouldBe(LicenseEdition.Business); + subject.IsBusinessEdition.ShouldBeTrue(); + subject.ClientLimit.ShouldBe(15); + subject.IssuerLimit.ShouldBe(1); + subject.KeyManagementFeature.ShouldBeTrue(); + subject.ResourceIsolationFeature.ShouldBeFalse(); + subject.DynamicProvidersFeature.ShouldBeFalse(); + subject.ServerSideSessionsFeature.ShouldBeTrue(); + //subject.ConfigApiFeature.ShouldBeTrue(); + subject.DPoPFeature.ShouldBeFalse(); + //subject.BffFeature.ShouldBeTrue(); + subject.RedistributionFeature.ShouldBeFalse(); + subject.CibaFeature.ShouldBeFalse(); + subject.ParFeature.ShouldBeTrue(); } { var subject = new IdentityServerLicense(new Claim("edition", "starter")); - subject.Edition.Should().Be(LicenseEdition.Starter); - subject.IsStarterEdition.Should().BeTrue(); - subject.ClientLimit.Should().Be(5); - subject.IssuerLimit.Should().Be(1); - subject.KeyManagementFeature.Should().BeFalse(); - subject.ResourceIsolationFeature.Should().BeFalse(); - subject.DynamicProvidersFeature.Should().BeFalse(); - subject.ServerSideSessionsFeature.Should().BeFalse(); - //subject.ConfigApiFeature.Should().BeFalse(); - subject.DPoPFeature.Should().BeFalse(); - //subject.BffFeature.Should().BeFalse(); - subject.RedistributionFeature.Should().BeFalse(); - subject.CibaFeature.Should().BeFalse(); - subject.ParFeature.Should().BeFalse(); + subject.Edition.ShouldBe(LicenseEdition.Starter); + subject.IsStarterEdition.ShouldBeTrue(); + subject.ClientLimit.ShouldBe(5); + subject.IssuerLimit.ShouldBe(1); + subject.KeyManagementFeature.ShouldBeFalse(); + subject.ResourceIsolationFeature.ShouldBeFalse(); + subject.DynamicProvidersFeature.ShouldBeFalse(); + subject.ServerSideSessionsFeature.ShouldBeFalse(); + //subject.ConfigApiFeature.ShouldBeFalse(); + subject.DPoPFeature.ShouldBeFalse(); + //subject.BffFeature.ShouldBeFalse(); + subject.RedistributionFeature.ShouldBeFalse(); + subject.CibaFeature.ShouldBeFalse(); + subject.ParFeature.ShouldBeFalse(); } { var subject = new IdentityServerLicense(new Claim("edition", "community")); - subject.Edition.Should().Be(LicenseEdition.Community); - subject.IsCommunityEdition.Should().BeTrue(); - subject.ClientLimit.Should().BeNull(); - subject.IssuerLimit.Should().BeNull(); - subject.KeyManagementFeature.Should().BeTrue(); - subject.ResourceIsolationFeature.Should().BeTrue(); - subject.DynamicProvidersFeature.Should().BeTrue(); - subject.ServerSideSessionsFeature.Should().BeTrue(); - //subject.ConfigApiFeature.Should().BeTrue(); - subject.DPoPFeature.Should().BeTrue(); - //subject.BffFeature.Should().BeTrue(); - subject.RedistributionFeature.Should().BeFalse(); - subject.CibaFeature.Should().BeTrue(); - subject.ParFeature.Should().BeTrue(); + subject.Edition.ShouldBe(LicenseEdition.Community); + subject.IsCommunityEdition.ShouldBeTrue(); + subject.ClientLimit.ShouldBeNull(); + subject.IssuerLimit.ShouldBeNull(); + subject.KeyManagementFeature.ShouldBeTrue(); + subject.ResourceIsolationFeature.ShouldBeTrue(); + subject.DynamicProvidersFeature.ShouldBeTrue(); + subject.ServerSideSessionsFeature.ShouldBeTrue(); + //subject.ConfigApiFeature.ShouldBeTrue(); + subject.DPoPFeature.ShouldBeTrue(); + //subject.BffFeature.ShouldBeTrue(); + subject.RedistributionFeature.ShouldBeFalse(); + subject.CibaFeature.ShouldBeTrue(); + subject.ParFeature.ShouldBeTrue(); } // BFF // TODO //{ // var subject = new IdentityServerLicense(new Claim("edition", "bff")); - // subject.Edition.Should().Be(LicenseEdition.Bff); - // subject.IsBffEdition.Should().BeTrue(); - // subject.ServerSideSessionsFeature.Should().BeFalse(); - // //subject.ConfigApiFeature.Should().BeFalse(); - // subject.DPoPFeature.Should().BeFalse(); - // //subject.BffFeature.Should().BeTrue(); - // subject.ClientLimit.Should().Be(0); - // subject.IssuerLimit.Should().Be(0); - // subject.KeyManagementFeature.Should().BeFalse(); - // subject.ResourceIsolationFeature.Should().BeFalse(); - // subject.DynamicProvidersFeature.Should().BeFalse(); - // subject.RedistributionFeature.Should().BeFalse(); - // subject.CibaFeature.Should().BeFalse(); + // subject.Edition.ShouldBe(LicenseEdition.Bff); + // subject.IsBffEdition.ShouldBeTrue(); + // subject.ServerSideSessionsFeature.ShouldBeFalse(); + // //subject.ConfigApiFeature.ShouldBeFalse(); + // subject.DPoPFeature.ShouldBeFalse(); + // //subject.BffFeature.ShouldBeTrue(); + // subject.ClientLimit.ShouldBe(0); + // subject.IssuerLimit.ShouldBe(0); + // subject.KeyManagementFeature.ShouldBeFalse(); + // subject.ResourceIsolationFeature.ShouldBeFalse(); + // subject.DynamicProvidersFeature.ShouldBeFalse(); + // subject.RedistributionFeature.ShouldBeFalse(); + // subject.CibaFeature.ShouldBeFalse(); //} // ISV { var subject = new IdentityServerLicense(new Claim("edition", "enterprise"), new Claim("feature", "isv")); - subject.Edition.Should().Be(LicenseEdition.Enterprise); - subject.IsEnterpriseEdition.Should().BeTrue(); - subject.ClientLimit.Should().Be(5); - subject.IssuerLimit.Should().BeNull(); - subject.KeyManagementFeature.Should().BeTrue(); - subject.ResourceIsolationFeature.Should().BeTrue(); - subject.DynamicProvidersFeature.Should().BeTrue(); - subject.ServerSideSessionsFeature.Should().BeTrue(); - //subject.ConfigApiFeature.Should().BeTrue(); - subject.DPoPFeature.Should().BeTrue(); - //subject.BffFeature.Should().BeTrue(); - subject.RedistributionFeature.Should().BeTrue(); - subject.CibaFeature.Should().BeTrue(); + subject.Edition.ShouldBe(LicenseEdition.Enterprise); + subject.IsEnterpriseEdition.ShouldBeTrue(); + subject.ClientLimit.ShouldBe(5); + subject.IssuerLimit.ShouldBeNull(); + subject.KeyManagementFeature.ShouldBeTrue(); + subject.ResourceIsolationFeature.ShouldBeTrue(); + subject.DynamicProvidersFeature.ShouldBeTrue(); + subject.ServerSideSessionsFeature.ShouldBeTrue(); + //subject.ConfigApiFeature.ShouldBeTrue(); + subject.DPoPFeature.ShouldBeTrue(); + //subject.BffFeature.ShouldBeTrue(); + subject.RedistributionFeature.ShouldBeTrue(); + subject.CibaFeature.ShouldBeTrue(); } { var subject = new IdentityServerLicense(new Claim("edition", "business"), new Claim("feature", "isv")); - subject.Edition.Should().Be(LicenseEdition.Business); - subject.IsBusinessEdition.Should().BeTrue(); - subject.ClientLimit.Should().Be(5); - subject.IssuerLimit.Should().Be(1); - subject.KeyManagementFeature.Should().BeTrue(); - subject.ResourceIsolationFeature.Should().BeFalse(); - subject.DynamicProvidersFeature.Should().BeFalse(); - subject.ServerSideSessionsFeature.Should().BeTrue(); - //subject.ConfigApiFeature.Should().BeTrue(); - subject.DPoPFeature.Should().BeFalse(); - //subject.BffFeature.Should().BeTrue(); - subject.RedistributionFeature.Should().BeTrue(); - subject.CibaFeature.Should().BeFalse(); + subject.Edition.ShouldBe(LicenseEdition.Business); + subject.IsBusinessEdition.ShouldBeTrue(); + subject.ClientLimit.ShouldBe(5); + subject.IssuerLimit.ShouldBe(1); + subject.KeyManagementFeature.ShouldBeTrue(); + subject.ResourceIsolationFeature.ShouldBeFalse(); + subject.DynamicProvidersFeature.ShouldBeFalse(); + subject.ServerSideSessionsFeature.ShouldBeTrue(); + //subject.ConfigApiFeature.ShouldBeTrue(); + subject.DPoPFeature.ShouldBeFalse(); + //subject.BffFeature.ShouldBeTrue(); + subject.RedistributionFeature.ShouldBeTrue(); + subject.CibaFeature.ShouldBeFalse(); } { var subject = new IdentityServerLicense(new Claim("edition", "starter"), new Claim("feature", "isv")); - subject.Edition.Should().Be(LicenseEdition.Starter); - subject.IsStarterEdition.Should().BeTrue(); - subject.ClientLimit.Should().Be(5); - subject.IssuerLimit.Should().Be(1); - subject.KeyManagementFeature.Should().BeFalse(); - subject.ResourceIsolationFeature.Should().BeFalse(); - subject.DynamicProvidersFeature.Should().BeFalse(); - subject.ServerSideSessionsFeature.Should().BeFalse(); - //subject.ConfigApiFeature.Should().BeFalse(); - subject.DPoPFeature.Should().BeFalse(); - //subject.BffFeature.Should().BeFalse(); - subject.RedistributionFeature.Should().BeTrue(); - subject.CibaFeature.Should().BeFalse(); + subject.Edition.ShouldBe(LicenseEdition.Starter); + subject.IsStarterEdition.ShouldBeTrue(); + subject.ClientLimit.ShouldBe(5); + subject.IssuerLimit.ShouldBe(1); + subject.KeyManagementFeature.ShouldBeFalse(); + subject.ResourceIsolationFeature.ShouldBeFalse(); + subject.DynamicProvidersFeature.ShouldBeFalse(); + subject.ServerSideSessionsFeature.ShouldBeFalse(); + //subject.ConfigApiFeature.ShouldBeFalse(); + subject.DPoPFeature.ShouldBeFalse(); + //subject.BffFeature.ShouldBeFalse(); + subject.RedistributionFeature.ShouldBeTrue(); + subject.CibaFeature.ShouldBeFalse(); } // TODO: these exceptions were moved to the validator //{ // Action a = () => new IdentityServerLicense(new Claim("edition", "community"), new Claim("feature", "isv")); - // a.Should().Throw(); + // a.ShouldThrow(); //} //{ // Action a = () => new IdentityServerLicense(new Claim("edition", "bff"), new Claim("feature", "isv")); - // a.Should().Throw(); + // a.ShouldThrow(); //} } @@ -208,8 +208,8 @@ public void license_should_handle_overrides_for_default_edition_values() new Claim("edition", "enterprise"), new Claim("client_limit", "20"), new Claim("issuer_limit", "5")); - subject.ClientLimit.Should().BeNull(); - subject.IssuerLimit.Should().BeNull(); + subject.ClientLimit.ShouldBeNull(); + subject.IssuerLimit.ShouldBeNull(); } { @@ -220,11 +220,11 @@ public void license_should_handle_overrides_for_default_edition_values() new Claim("feature", "resource_isolation"), new Claim("feature", "ciba"), new Claim("feature", "dynamic_providers")); - subject.ClientLimit.Should().Be(20); - subject.IssuerLimit.Should().Be(5); - subject.ResourceIsolationFeature.Should().BeTrue(); - subject.DynamicProvidersFeature.Should().BeTrue(); - subject.CibaFeature.Should().BeTrue(); + subject.ClientLimit.ShouldBe(20); + subject.IssuerLimit.ShouldBe(5); + subject.ResourceIsolationFeature.ShouldBeTrue(); + subject.DynamicProvidersFeature.ShouldBeTrue(); + subject.CibaFeature.ShouldBeTrue(); } { var subject = new IdentityServerLicense( @@ -233,8 +233,8 @@ public void license_should_handle_overrides_for_default_edition_values() new Claim("feature", "unlimited_issuers"), new Claim("issuer_limit", "5"), new Claim("feature", "unlimited_clients")); - subject.ClientLimit.Should().BeNull(); - subject.IssuerLimit.Should().BeNull(); + subject.ClientLimit.ShouldBeNull(); + subject.IssuerLimit.ShouldBeNull(); } { @@ -252,18 +252,18 @@ public void license_should_handle_overrides_for_default_edition_values() new Claim("feature", "ciba"), new Claim("feature", "dynamic_providers"), new Claim("feature", "par")); - subject.ClientLimit.Should().Be(20); - subject.IssuerLimit.Should().Be(5); - subject.KeyManagementFeature.Should().BeTrue(); - subject.ResourceIsolationFeature.Should().BeTrue(); - subject.ServerSideSessionsFeature.Should().BeTrue(); - //subject.ConfigApiFeature.Should().BeTrue(); - subject.DPoPFeature.Should().BeTrue(); - //subject.BffFeature.Should().BeTrue(); - subject.DynamicProvidersFeature.Should().BeTrue(); - subject.RedistributionFeature.Should().BeTrue(); - subject.CibaFeature.Should().BeTrue(); - subject.ParFeature.Should().BeTrue(); + subject.ClientLimit.ShouldBe(20); + subject.IssuerLimit.ShouldBe(5); + subject.KeyManagementFeature.ShouldBeTrue(); + subject.ResourceIsolationFeature.ShouldBeTrue(); + subject.ServerSideSessionsFeature.ShouldBeTrue(); + //subject.ConfigApiFeature.ShouldBeTrue(); + subject.DPoPFeature.ShouldBeTrue(); + //subject.BffFeature.ShouldBeTrue(); + subject.DynamicProvidersFeature.ShouldBeTrue(); + subject.RedistributionFeature.ShouldBeTrue(); + subject.CibaFeature.ShouldBeTrue(); + subject.ParFeature.ShouldBeTrue(); } { var subject = new IdentityServerLicense( @@ -272,8 +272,8 @@ public void license_should_handle_overrides_for_default_edition_values() new Claim("feature", "unlimited_issuers"), new Claim("issuer_limit", "5"), new Claim("feature", "unlimited_clients")); - subject.ClientLimit.Should().BeNull(); - subject.IssuerLimit.Should().BeNull(); + subject.ClientLimit.ShouldBeNull(); + subject.IssuerLimit.ShouldBeNull(); } { @@ -281,8 +281,8 @@ public void license_should_handle_overrides_for_default_edition_values() new Claim("edition", "community"), new Claim("client_limit", "20"), new Claim("issuer_limit", "5")); - subject.ClientLimit.Should().BeNull(); - subject.IssuerLimit.Should().BeNull(); + subject.ClientLimit.ShouldBeNull(); + subject.IssuerLimit.ShouldBeNull(); } // ISV @@ -291,7 +291,7 @@ public void license_should_handle_overrides_for_default_edition_values() new Claim("edition", "enterprise"), new Claim("feature", "isv"), new Claim("client_limit", "20")); - subject.ClientLimit.Should().Be(20); + subject.ClientLimit.ShouldBe(20); } { var subject = new IdentityServerLicense( @@ -299,8 +299,8 @@ public void license_should_handle_overrides_for_default_edition_values() new Claim("feature", "isv"), new Claim("feature", "ciba"), new Claim("client_limit", "20")); - subject.ClientLimit.Should().Be(20); - subject.CibaFeature.Should().BeTrue(); + subject.ClientLimit.ShouldBe(20); + subject.CibaFeature.ShouldBeTrue(); } { var subject = new IdentityServerLicense( @@ -312,12 +312,12 @@ public void license_should_handle_overrides_for_default_edition_values() new Claim("feature", "bff"), new Claim("feature", "ciba"), new Claim("client_limit", "20")); - subject.ClientLimit.Should().Be(20); - subject.ServerSideSessionsFeature.Should().BeTrue(); - //subject.ConfigApiFeature.Should().BeTrue(); - subject.DPoPFeature.Should().BeTrue(); - //subject.BffFeature.Should().BeTrue(); - subject.CibaFeature.Should().BeTrue(); + subject.ClientLimit.ShouldBe(20); + subject.ServerSideSessionsFeature.ShouldBeTrue(); + //subject.ConfigApiFeature.ShouldBeTrue(); + subject.DPoPFeature.ShouldBeTrue(); + //subject.BffFeature.ShouldBeTrue(); + subject.CibaFeature.ShouldBeTrue(); } { @@ -326,7 +326,7 @@ public void license_should_handle_overrides_for_default_edition_values() new Claim("feature", "isv"), new Claim("feature", "unlimited_clients"), new Claim("client_limit", "20")); - subject.ClientLimit.Should().BeNull(); + subject.ClientLimit.ShouldBeNull(); } { var subject = new IdentityServerLicense( @@ -334,7 +334,7 @@ public void license_should_handle_overrides_for_default_edition_values() new Claim("feature", "isv"), new Claim("feature", "unlimited_clients"), new Claim("client_limit", "20")); - subject.ClientLimit.Should().BeNull(); + subject.ClientLimit.ShouldBeNull(); } { var subject = new IdentityServerLicense( @@ -342,7 +342,7 @@ public void license_should_handle_overrides_for_default_edition_values() new Claim("feature", "isv"), new Claim("feature", "unlimited_clients"), new Claim("client_limit", "20")); - subject.ClientLimit.Should().BeNull(); + subject.ClientLimit.ShouldBeNull(); } // BFF @@ -357,13 +357,13 @@ public void license_should_handle_overrides_for_default_edition_values() // new Claim("feature", "ciba"), // new Claim("feature", "key_management") // ); - // //subject.BffFeature.Should().BeTrue(); - // subject.ClientLimit.Should().Be(0); - // subject.IssuerLimit.Should().Be(0); - // subject.KeyManagementFeature.Should().BeFalse(); - // subject.ResourceIsolationFeature.Should().BeFalse(); - // subject.DynamicProvidersFeature.Should().BeFalse(); - // subject.CibaFeature.Should().BeFalse(); + // //subject.BffFeature.ShouldBeTrue(); + // subject.ClientLimit.ShouldBe(0); + // subject.IssuerLimit.ShouldBe(0); + // subject.KeyManagementFeature.ShouldBeFalse(); + // subject.ResourceIsolationFeature.ShouldBeFalse(); + // subject.DynamicProvidersFeature.ShouldBeFalse(); + // subject.CibaFeature.ShouldBeFalse(); //} } @@ -373,11 +373,11 @@ public void invalid_edition_should_fail() { { Action func = () => new IdentityServerLicense(new Claim("edition", "invalid")); - func.Should().Throw(); + func.ShouldThrow(); } { Action func = () => new IdentityServerLicense(new Claim("edition", "")); - func.Should().Throw(); + func.ShouldThrow(); } } @@ -408,26 +408,26 @@ public void client_count_exceeded_should_warn(bool hasLicense, int allowedClient } // Adding the allowed number of clients shouldn't log. - subject.ErrorLogCount.Should().Be(0); - subject.WarningLogCount.Should().Be(0); + subject.ErrorLogCount.ShouldBe(0); + subject.WarningLogCount.ShouldBe(0); // Validating same client again shouldn't log. subject.ValidateClient("client3", license); - subject.ErrorLogCount.Should().Be(0); - subject.WarningLogCount.Should().Be(0); + subject.ErrorLogCount.ShouldBe(0); + subject.WarningLogCount.ShouldBe(0); subject.ValidateClient("extra1", license); subject.ValidateClient("extra2", license); if (hasLicense) { - subject.ErrorLogCount.Should().Be(2); - subject.WarningLogCount.Should().Be(0); + subject.ErrorLogCount.ShouldBe(2); + subject.WarningLogCount.ShouldBe(0); } else { - subject.ErrorLogCount.Should().Be(0); - subject.WarningLogCount.Should().Be(1); + subject.ErrorLogCount.ShouldBe(0); + subject.WarningLogCount.ShouldBe(1); } } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Licensing/v2/LicenseAccessorTests.cs b/identity-server/test/IdentityServer.UnitTests/Licensing/v2/LicenseAccessorTests.cs index 3b5104fb0..5744f3f55 100644 --- a/identity-server/test/IdentityServer.UnitTests/Licensing/v2/LicenseAccessorTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Licensing/v2/LicenseAccessorTests.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using Duende.IdentityServer.Licensing.V2; using Duende.IdentityServer.Configuration; -using FluentAssertions; +using Shouldly; using Microsoft.Extensions.Logging.Testing; using Xunit; @@ -32,27 +32,27 @@ internal void license_set_in_options_is_parsed_correctly(int serialNumber, Licen var l = _licenseAccessor.Current; - l.IsConfigured.Should().BeTrue(); - l.Edition.Should().Be(edition); - l.Extras.Should().BeEmpty(); - l.CompanyName.Should().Be("_test"); - l.ContactInfo.Should().Be(contact); - l.SerialNumber.Should().Be(serialNumber); - l.Expiration!.Value.Date.Should().Be(new DateTime(2024, 11, 15)); - l.Redistribution.Should().Be(isRedistribution); + l.IsConfigured.ShouldBeTrue(); + l.Edition.ShouldBe(edition); + l.Extras.ShouldBeEmpty(); + l.CompanyName.ShouldBe("_test"); + l.ContactInfo.ShouldBe(contact); + l.SerialNumber.ShouldBe(serialNumber); + l.Expiration!.Value.Date.ShouldBe(new DateTime(2024, 11, 15)); + l.Redistribution.ShouldBe(isRedistribution); var enterpriseFeaturesEnabled = edition == LicenseEdition.Enterprise || edition == LicenseEdition.Community; var businessFeaturesEnabled = enterpriseFeaturesEnabled || edition == LicenseEdition.Business; - _licenseAccessor.Current.IsEnabled(LicenseFeature.DynamicProviders).Should().Be(enterpriseFeaturesEnabled || addDynamicProviders); - _licenseAccessor.Current.IsEnabled(LicenseFeature.ResourceIsolation).Should().Be(enterpriseFeaturesEnabled); - _licenseAccessor.Current.IsEnabled(LicenseFeature.DPoP).Should().Be(enterpriseFeaturesEnabled); - _licenseAccessor.Current.IsEnabled(LicenseFeature.CIBA).Should().Be(enterpriseFeaturesEnabled); + _licenseAccessor.Current.IsEnabled(LicenseFeature.DynamicProviders).ShouldBe(enterpriseFeaturesEnabled || addDynamicProviders); + _licenseAccessor.Current.IsEnabled(LicenseFeature.ResourceIsolation).ShouldBe(enterpriseFeaturesEnabled); + _licenseAccessor.Current.IsEnabled(LicenseFeature.DPoP).ShouldBe(enterpriseFeaturesEnabled); + _licenseAccessor.Current.IsEnabled(LicenseFeature.CIBA).ShouldBe(enterpriseFeaturesEnabled); - _licenseAccessor.Current.IsEnabled(LicenseFeature.KeyManagement).Should().Be(businessFeaturesEnabled || addKeyManagement); - _licenseAccessor.Current.IsEnabled(LicenseFeature.PAR).Should().Be(businessFeaturesEnabled); - _licenseAccessor.Current.IsEnabled(LicenseFeature.DCR).Should().Be(businessFeaturesEnabled); - _licenseAccessor.Current.IsEnabled(LicenseFeature.ServerSideSessions).Should().Be(businessFeaturesEnabled); + _licenseAccessor.Current.IsEnabled(LicenseFeature.KeyManagement).ShouldBe(businessFeaturesEnabled || addKeyManagement); + _licenseAccessor.Current.IsEnabled(LicenseFeature.PAR).ShouldBe(businessFeaturesEnabled); + _licenseAccessor.Current.IsEnabled(LicenseFeature.DCR).ShouldBe(businessFeaturesEnabled); + _licenseAccessor.Current.IsEnabled(LicenseFeature.ServerSideSessions).ShouldBe(businessFeaturesEnabled); } @@ -83,8 +83,8 @@ public static IEnumerable LicenseTestCases() => public void keys_that_cannot_be_parsed_are_treated_the_same_as_an_absent_license() { _options.LicenseKey = "invalid key"; - _licenseAccessor.Current.IsConfigured.Should().BeFalse(); - _logger.Collector.GetSnapshot().Should().Contain(r => + _licenseAccessor.Current.IsConfigured.ShouldBeFalse(); + _logger.Collector.GetSnapshot().ShouldContain(r => r.Message == "Error validating the Duende software license key"); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Licensing/v2/LicenseUsageTests.cs b/identity-server/test/IdentityServer.UnitTests/Licensing/v2/LicenseUsageTests.cs index 9cbaf5b4f..ce73cbcb2 100644 --- a/identity-server/test/IdentityServer.UnitTests/Licensing/v2/LicenseUsageTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Licensing/v2/LicenseUsageTests.cs @@ -3,7 +3,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Licensing.V2; -using FluentAssertions; +using Shouldly; using Microsoft.Extensions.Logging.Abstractions; using Xunit; @@ -36,19 +36,19 @@ public void used_features_are_reported() var summary = _licenseUsageTracker.GetSummary(); - summary.FeaturesUsed.Should().Contain(LicenseFeature.KeyManagement.ToString()); - summary.FeaturesUsed.Should().Contain(LicenseFeature.PAR.ToString()); - summary.FeaturesUsed.Should().Contain(LicenseFeature.ServerSideSessions.ToString()); - summary.FeaturesUsed.Should().Contain(LicenseFeature.DCR.ToString()); - summary.FeaturesUsed.Should().Contain(LicenseFeature.KeyManagement.ToString()); + summary.FeaturesUsed.ShouldContain(LicenseFeature.KeyManagement.ToString()); + summary.FeaturesUsed.ShouldContain(LicenseFeature.PAR.ToString()); + summary.FeaturesUsed.ShouldContain(LicenseFeature.ServerSideSessions.ToString()); + summary.FeaturesUsed.ShouldContain(LicenseFeature.DCR.ToString()); + summary.FeaturesUsed.ShouldContain(LicenseFeature.KeyManagement.ToString()); - summary.FeaturesUsed.Should().Contain(LicenseFeature.ResourceIsolation.ToString()); - summary.FeaturesUsed.Should().Contain(LicenseFeature.DynamicProviders.ToString()); - summary.FeaturesUsed.Should().Contain(LicenseFeature.CIBA.ToString()); - summary.FeaturesUsed.Should().Contain(LicenseFeature.DPoP.ToString()); + summary.FeaturesUsed.ShouldContain(LicenseFeature.ResourceIsolation.ToString()); + summary.FeaturesUsed.ShouldContain(LicenseFeature.DynamicProviders.ToString()); + summary.FeaturesUsed.ShouldContain(LicenseFeature.CIBA.ToString()); + summary.FeaturesUsed.ShouldContain(LicenseFeature.DPoP.ToString()); - summary.FeaturesUsed.Should().Contain(LicenseFeature.ISV.ToString()); - summary.FeaturesUsed.Should().Contain(LicenseFeature.Redistribution.ToString()); + summary.FeaturesUsed.ShouldContain(LicenseFeature.ISV.ToString()); + summary.FeaturesUsed.ShouldContain(LicenseFeature.Redistribution.ToString()); } [Fact] @@ -59,9 +59,9 @@ public void used_clients_are_reported() var summary = _licenseUsageTracker.GetSummary(); - summary.ClientsUsed.Count.Should().Be(2); - summary.ClientsUsed.Should().Contain("mvc.code"); - summary.ClientsUsed.Should().Contain("mvc.dpop"); + summary.ClientsUsed.Count.ShouldBe(2); + summary.ClientsUsed.ShouldContain("mvc.code"); + summary.ClientsUsed.ShouldContain("mvc.dpop"); } [Fact] @@ -72,8 +72,8 @@ public void used_issuers_are_reported() var summary = _licenseUsageTracker.GetSummary(); - summary.IssuersUsed.Count.Should().Be(2); - summary.IssuersUsed.Should().Contain("https://localhost:5001"); - summary.IssuersUsed.Should().Contain("https://acme.com"); + summary.IssuersUsed.Count.ShouldBe(2); + summary.IssuersUsed.ShouldContain("https://localhost:5001"); + summary.IssuersUsed.ShouldContain("https://acme.com"); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Licensing/v2/ProtocolRequestCounterTests.cs b/identity-server/test/IdentityServer.UnitTests/Licensing/v2/ProtocolRequestCounterTests.cs index 692cd8336..9d194e0b7 100644 --- a/identity-server/test/IdentityServer.UnitTests/Licensing/v2/ProtocolRequestCounterTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Licensing/v2/ProtocolRequestCounterTests.cs @@ -1,6 +1,7 @@ +using System.Linq; using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Licensing.V2; -using FluentAssertions; +using Shouldly; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Testing; using Xunit; @@ -25,7 +26,7 @@ public void number_of_protocol_requests_is_counted() for (uint i = 0; i < 10; i++) { _counter.Increment(); - _counter.RequestCount.Should().Be(i + 1); + _counter.RequestCount.ShouldBe(i + 1); } } @@ -39,10 +40,9 @@ public void warning_is_logged_once_after_too_many_protocol_requests_are_handled( } // REMINDER - If this test needs to change because the log message was updated, so should warning_is_not_logged_before_too_many_protocol_requests_are_handled - _logger.Collector.GetSnapshot().Should() - .ContainSingle(r => - r.Message == - $"You are using IdentityServer in trial mode and have exceeded the trial threshold of {_counter.Threshold} requests handled by IdentityServer. In a future version, you will need to restart the server or configure a license key to continue testing. For more information, please see https://docs.duendesoftware.com/trial-mode."); + var logRecord = _logger.Collector.GetSnapshot().Single(); + logRecord.Message.ShouldBe( + $"You are using IdentityServer in trial mode and have exceeded the trial threshold of {_counter.Threshold} requests handled by IdentityServer. In a future version, you will need to restart the server or configure a license key to continue testing. For more information, please see https://docs.duendesoftware.com/trial-mode."); } [Fact] @@ -54,9 +54,8 @@ public void warning_is_not_logged_before_too_many_protocol_requests_are_handled( _counter.Increment(); } - _logger.Collector.GetSnapshot().Should() - .NotContain(r => - r.Message == - $"You are using IdentityServer in trial mode and have exceeded the trial threshold of {_counter.Threshold} requests handled by IdentityServer. In a future version, you will need to restart the server or configure a license key to continue testing. For more information, please see https://docs.duendesoftware.com/trial-mode."); + var logRecords = _logger.Collector.GetSnapshot().Select(l => l.Message); + logRecords.ShouldNotContain( + $"You are using IdentityServer in trial mode and have exceeded the trial threshold of {_counter.Threshold} requests handled by IdentityServer. In a future version, you will need to restart the server or configure a license key to continue testing. For more information, please see https://docs.duendesoftware.com/trial-mode."); } } diff --git a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests.cs b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests.cs index 44ea0f648..daeb7a526 100644 --- a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests.cs @@ -9,7 +9,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Models; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Xunit; using static Duende.IdentityModel.OidcConstants; @@ -57,8 +57,8 @@ public async Task Authenticated_User_with_restricted_current_Idp_with_prompt_non var result = await _subject.ProcessInteractionAsync(request); - result.IsError.Should().BeTrue(); - result.IsLogin.Should().BeFalse(); + result.IsError.ShouldBeTrue(); + result.IsLogin.ShouldBeFalse(); } [Fact] @@ -84,8 +84,8 @@ public async Task Authenticated_User_with_maxage_with_prompt_none_must_error() var result = await _subject.ProcessInteractionAsync(request); - result.IsError.Should().BeTrue(); - result.IsLogin.Should().BeFalse(); + result.IsError.ShouldBeTrue(); + result.IsLogin.ShouldBeFalse(); } [Fact] @@ -107,8 +107,8 @@ public async Task Authenticated_User_with_different_requested_Idp_with_prompt_no var result = await _subject.ProcessInteractionAsync(request); - result.IsError.Should().BeTrue(); - result.IsLogin.Should().BeFalse(); + result.IsError.ShouldBeTrue(); + result.IsLogin.ShouldBeFalse(); } [Fact] @@ -131,8 +131,8 @@ public async Task Authenticated_User_beyond_client_user_sso_lifetime_with_prompt var result = await _subject.ProcessInteractionAsync(request); - result.IsError.Should().BeTrue(); - result.IsLogin.Should().BeFalse(); + result.IsError.ShouldBeTrue(); + result.IsLogin.ShouldBeFalse(); } [Fact] @@ -154,7 +154,7 @@ public async Task locally_authenticated_user_but_client_does_not_allow_local_wit var result = await _subject.ProcessInteractionAsync(request); - result.IsError.Should().BeTrue(); - result.IsLogin.Should().BeFalse(); + result.IsError.ShouldBeTrue(); + result.IsLogin.ShouldBeFalse(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Consent.cs b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Consent.cs index 9b3892284..c3177f003 100644 --- a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Consent.cs +++ b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Consent.cs @@ -10,7 +10,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Models; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using Xunit; @@ -31,16 +31,16 @@ private void RequiresConsent(bool value) private void AssertUpdateConsentNotCalled() { - _mockConsent.ConsentClient.Should().BeNull(); - _mockConsent.ConsentSubject.Should().BeNull(); - _mockConsent.ConsentScopes.Should().BeNull(); + _mockConsent.ConsentClient.ShouldBeNull(); + _mockConsent.ConsentSubject.ShouldBeNull(); + _mockConsent.ConsentScopes.ShouldBeNull(); } private void AssertUpdateConsentCalled(Client client, ClaimsPrincipal user, params string[] scopes) { - _mockConsent.ConsentClient.Should().BeSameAs(client); - _mockConsent.ConsentSubject.Should().BeSameAs(user); - _mockConsent.ConsentScopes.Should().BeEquivalentTo(scopes); + _mockConsent.ConsentClient.ShouldBeSameAs(client); + _mockConsent.ConsentSubject.ShouldBeSameAs(user); + _mockConsent.ConsentScopes.ShouldBeEquivalentTo(scopes); } private static IEnumerable GetIdentityScopes() @@ -112,8 +112,8 @@ public async Task ProcessConsentAsync_NullRequest_Throws() { Func act = () => _subject.ProcessConsentAsync(null, new ConsentResponse()); - (await act.Should().ThrowAsync()) - .And.ParamName.Should().Be("request"); + var exception = await act.ShouldThrowAsync(); + exception.ParamName.ShouldBe("request"); } [Fact] @@ -147,8 +147,8 @@ public async Task ProcessConsentAsync_PromptModeIsLogin_Throws() Func act = () => _subject.ProcessConsentAsync(request); - await act.Should().ThrowAsync() - .WithMessage("*PromptMode*"); + var exception = await act.ShouldThrowAsync(); + exception.Message.ShouldBe("*PromptMode*"); } [Fact] @@ -167,8 +167,8 @@ public async Task ProcessConsentAsync_PromptModeIsSelectAccount_Throws() Func act = () => _subject.ProcessConsentAsync(request); - await act.Should().ThrowAsync() - .WithMessage("*PromptMode*"); + var exception = await act.ShouldThrowAsync(); + exception.Message.ShouldBe("*PromptMode*"); } @@ -187,9 +187,9 @@ public async Task ProcessConsentAsync_RequiresConsentButPromptModeIsNone_Returns }; var result = await _subject.ProcessConsentAsync(request); - request.WasConsentShown.Should().BeFalse(); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.ConsentRequired); + request.WasConsentShown.ShouldBeFalse(); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.ConsentRequired); AssertUpdateConsentNotCalled(); } @@ -206,8 +206,8 @@ public async Task ProcessConsentAsync_PromptModeIsConsent_NoPriorConsent_Returns ValidatedResources = GetValidatedResources("openid", "read", "write"), }; var result = await _subject.ProcessConsentAsync(request); - request.WasConsentShown.Should().BeFalse(); - result.IsConsent.Should().BeTrue(); + request.WasConsentShown.ShouldBeFalse(); + result.IsConsent.ShouldBeTrue(); AssertUpdateConsentNotCalled(); } @@ -225,8 +225,8 @@ public async Task ProcessConsentAsync_NoPromptMode_ConsentServiceRequiresConsent ValidatedResources = GetValidatedResources("openid", "read", "write"), }; var result = await _subject.ProcessConsentAsync(request); - request.WasConsentShown.Should().BeFalse(); - result.IsConsent.Should().BeTrue(); + request.WasConsentShown.ShouldBeFalse(); + result.IsConsent.ShouldBeTrue(); AssertUpdateConsentNotCalled(); } @@ -249,9 +249,9 @@ public async Task ProcessConsentAsync_PromptModeIsConsent_ConsentNotGranted_Retu ScopesValuesConsented = new string[] {} }; var result = await _subject.ProcessConsentAsync(request, consent); - request.WasConsentShown.Should().BeTrue(); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.AccessDenied); + request.WasConsentShown.ShouldBeTrue(); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.AccessDenied); AssertUpdateConsentNotCalled(); } @@ -273,9 +273,9 @@ public async Task ProcessConsentAsync_NoPromptMode_ConsentServiceRequiresConsent ScopesValuesConsented = new string[] {} }; var result = await _subject.ProcessConsentAsync(request, consent); - request.WasConsentShown.Should().BeTrue(); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.AccessDenied); + request.WasConsentShown.ShouldBeTrue(); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.AccessDenied); AssertUpdateConsentNotCalled(); } @@ -301,8 +301,8 @@ public async Task ProcessConsentAsync_NoPromptMode_ConsentServiceRequiresConsent }; var result = await _subject.ProcessConsentAsync(request, consent); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.AccessDenied); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.AccessDenied); AssertUpdateConsentNotCalled(); } @@ -327,12 +327,12 @@ public async Task ProcessConsentAsync_NoPromptMode_ConsentServiceRequiresConsent ScopesValuesConsented = new string[] { "openid", "read" } }; var result = await _subject.ProcessConsentAsync(request, consent); - request.ValidatedResources.Resources.IdentityResources.Count.Should().Be(1); - request.ValidatedResources.Resources.ApiScopes.Count.Should().Be(1); - "openid".Should().Be(request.ValidatedResources.Resources.IdentityResources.Select(x => x.Name).First()); - "read".Should().Be(request.ValidatedResources.Resources.ApiScopes.First().Name); - request.WasConsentShown.Should().BeTrue(); - result.IsConsent.Should().BeFalse(); + request.ValidatedResources.Resources.IdentityResources.Count.ShouldBe(1); + request.ValidatedResources.Resources.ApiScopes.Count.ShouldBe(1); + "openid".ShouldBe(request.ValidatedResources.Resources.IdentityResources.Select(x => x.Name).First()); + "read".ShouldBe(request.ValidatedResources.Resources.ApiScopes.First().Name); + request.WasConsentShown.ShouldBeTrue(); + result.IsConsent.ShouldBeFalse(); AssertUpdateConsentNotCalled(); } @@ -357,11 +357,11 @@ public async Task ProcessConsentAsync_PromptModeConsent_ConsentGranted_ScopesSel ScopesValuesConsented = new string[] { "openid", "read" } }; var result = await _subject.ProcessConsentAsync(request, consent); - request.ValidatedResources.Resources.IdentityResources.Count.Should().Be(1); - request.ValidatedResources.Resources.ApiScopes.Count.Should().Be(1); - "read".Should().Be(request.ValidatedResources.Resources.ApiScopes.First().Name); - request.WasConsentShown.Should().BeTrue(); - result.IsConsent.Should().BeFalse(); + request.ValidatedResources.Resources.IdentityResources.Count.ShouldBe(1); + request.ValidatedResources.Resources.ApiScopes.Count.ShouldBe(1); + "read".ShouldBe(request.ValidatedResources.Resources.ApiScopes.First().Name); + request.WasConsentShown.ShouldBeTrue(); + result.IsConsent.ShouldBeFalse(); AssertUpdateConsentNotCalled(); } diff --git a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Custom.cs b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Custom.cs index dc8a50ee5..4dde81755 100644 --- a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Custom.cs +++ b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Custom.cs @@ -9,7 +9,7 @@ using Duende.IdentityServer.ResponseHandling; using Duende.IdentityServer.Services; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Microsoft.Extensions.Logging; using Xunit; @@ -90,8 +90,8 @@ public async Task ProcessInteractionAsync_with_overridden_login_returns_redirect var result = await _subject.ProcessInteractionAsync(request); - result.IsRedirect.Should().BeTrue(); - result.RedirectUrl.Should().Be("/custom"); + result.IsRedirect.ShouldBeTrue(); + result.RedirectUrl.ShouldBe("/custom"); } [Fact] @@ -117,8 +117,8 @@ public async Task ProcessInteractionAsync_with_prompt_none_and_login_returns_log var result = await _subject.ProcessInteractionAsync(request); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("login_required"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("login_required"); } [Fact] @@ -144,9 +144,9 @@ public async Task ProcessInteractionAsync_with_prompt_none_and_login_returns_red var result = await _subject.ProcessInteractionAsync(request); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("interaction_required"); - result.RedirectUrl.Should().BeNull(); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("interaction_required"); + result.RedirectUrl.ShouldBeNull(); } [Fact] @@ -172,7 +172,7 @@ public async Task ProcessInteractionAsync_with_prompt_none_and_consent_returns_c var result = await _subject.ProcessInteractionAsync(request); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("consent_required"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("consent_required"); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Login.cs b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Login.cs index 65cd702ff..7f8cb831b 100644 --- a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Login.cs +++ b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/AuthorizeInteractionResponseGenerator/AuthorizeInteractionResponseGeneratorTests_Login.cs @@ -10,7 +10,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Models; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using Xunit; @@ -45,7 +45,7 @@ public async Task Anonymous_User_must_SignIn() var result = await _subject.ProcessLoginAsync(request); - result.IsLogin.Should().BeTrue(); + result.IsLogin.ShouldBeTrue(); } [Fact] @@ -64,7 +64,7 @@ public async Task Authenticated_User_must_not_SignIn() var result = await _subject.ProcessInteractionAsync(request); - result.IsLogin.Should().BeFalse(); + result.IsLogin.ShouldBeFalse(); } [Fact] @@ -87,7 +87,7 @@ public async Task Authenticated_User_with_allowed_current_Idp_must_not_SignIn() var result = await _subject.ProcessLoginAsync(request); - result.IsLogin.Should().BeFalse(); + result.IsLogin.ShouldBeFalse(); } [Fact] @@ -112,7 +112,7 @@ public async Task Authenticated_User_with_restricted_current_Idp_must_SignIn() var result = await _subject.ProcessLoginAsync(request); - result.IsLogin.Should().BeTrue(); + result.IsLogin.ShouldBeTrue(); } [Fact] @@ -133,7 +133,7 @@ public async Task Authenticated_User_with_allowed_requested_Idp_must_not_SignIn( var result = await _subject.ProcessLoginAsync(request); - result.IsLogin.Should().BeFalse(); + result.IsLogin.ShouldBeFalse(); } [Fact] @@ -154,7 +154,7 @@ public async Task Authenticated_User_with_different_requested_Idp_must_SignIn() var result = await _subject.ProcessLoginAsync(request); - result.IsLogin.Should().BeTrue(); + result.IsLogin.ShouldBeTrue(); } [Fact] @@ -175,7 +175,7 @@ public async Task Authenticated_User_within_client_user_sso_lifetime_should_not_ var result = await _subject.ProcessLoginAsync(request); - result.IsLogin.Should().BeFalse(); + result.IsLogin.ShouldBeFalse(); } [Fact] @@ -197,7 +197,7 @@ public async Task Authenticated_User_beyond_client_user_sso_lifetime_should_sign var result = await _subject.ProcessLoginAsync(request); - result.IsLogin.Should().BeTrue(); + result.IsLogin.ShouldBeTrue(); } [Fact] @@ -218,7 +218,7 @@ public async Task locally_authenticated_user_but_client_does_not_allow_local_sho var result = await _subject.ProcessLoginAsync(request); - result.IsLogin.Should().BeTrue(); + result.IsLogin.ShouldBeTrue(); } [Fact] @@ -234,7 +234,7 @@ public async Task prompt_login_should_sign_in() var result = await _subject.ProcessLoginAsync(request); - result.IsLogin.Should().BeTrue(); + result.IsLogin.ShouldBeTrue(); } [Fact] @@ -250,7 +250,7 @@ public async Task prompt_select_account_should_sign_in() var result = await _subject.ProcessLoginAsync(request); - result.IsLogin.Should().BeTrue(); + result.IsLogin.ShouldBeTrue(); } [Fact] @@ -269,6 +269,6 @@ public async Task prompt_for_signin_should_suppress_prompt_from_raw_url() var result = await _subject.ProcessLoginAsync(request); - request.Raw.AllKeys.Should().Contain(Constants.ProcessedPrompt); + request.Raw.AllKeys.ShouldContain(Constants.ProcessedPrompt); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/DeviceAuthorizationResponseGeneratorTests.cs b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/DeviceAuthorizationResponseGeneratorTests.cs index 3c7da6e55..fb097f316 100644 --- a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/DeviceAuthorizationResponseGeneratorTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/DeviceAuthorizationResponseGeneratorTests.cs @@ -13,7 +13,7 @@ using Duende.IdentityServer.Services.Default; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Microsoft.Extensions.Logging.Abstractions; using Xunit; @@ -56,7 +56,7 @@ public DeviceAuthorizationResponseGeneratorTests() public async Task ProcessAsync_when_validationresult_null_expect_exception() { Func act = () => generator.ProcessAsync(null, TestBaseUrl); - await act.Should().ThrowAsync(); + await act.ShouldThrowAsync(); } [Fact] @@ -64,14 +64,14 @@ public async Task ProcessAsync_when_validationresult_client_null_expect_exceptio { var validationResult = new DeviceAuthorizationRequestValidationResult(new ValidatedDeviceAuthorizationRequest()); Func act = () => generator.ProcessAsync(validationResult, TestBaseUrl); - await act.Should().ThrowAsync(); + await act.ShouldThrowAsync(); } [Fact] public async Task ProcessAsync_when_baseurl_null_expect_exception() { Func act = () => generator.ProcessAsync(testResult, null); - await act.Should().ThrowAsync(); + await act.ShouldThrowAsync(); } [Fact] @@ -85,7 +85,7 @@ public async Task ProcessAsync_when_user_code_collision_expect_retry() var response = await generator.ProcessAsync(testResult, TestBaseUrl); - response.UserCode.Should().Be(FakeUserCodeGenerator.TestUniqueUserCode); + response.UserCode.ShouldBe(FakeUserCodeGenerator.TestUniqueUserCode); } [Fact] @@ -115,17 +115,17 @@ public async Task ProcessAsync_when_generated_expect_user_code_stored() var response = await generator.ProcessAsync(testResult, TestBaseUrl); - response.UserCode.Should().NotBeNullOrWhiteSpace(); + response.UserCode.ShouldNotBeNullOrWhiteSpace(); var userCode = await deviceFlowCodeService.FindByUserCodeAsync(response.UserCode); - userCode.Should().NotBeNull(); - userCode.ClientId.Should().Be(testResult.ValidatedRequest.Client.ClientId); - userCode.Lifetime.Should().Be(testResult.ValidatedRequest.Client.DeviceCodeLifetime); - userCode.CreationTime.Should().Be(creationTime); - userCode.Subject.Should().BeNull(); - userCode.AuthorizedScopes.Should().BeNull(); - - userCode.RequestedScopes.Should().Contain(testResult.ValidatedRequest.RequestedScopes); + userCode.ShouldNotBeNull(); + userCode.ClientId.ShouldBe(testResult.ValidatedRequest.Client.ClientId); + userCode.Lifetime.ShouldBe(testResult.ValidatedRequest.Client.DeviceCodeLifetime); + userCode.CreationTime.ShouldBe(creationTime); + userCode.Subject.ShouldBeNull(); + userCode.AuthorizedScopes.ShouldBeNull(); + + userCode.RequestedScopes.ShouldContain(testResult.ValidatedRequest.RequestedScopes); } [Fact] @@ -136,19 +136,19 @@ public async Task ProcessAsync_when_generated_expect_device_code_stored() var response = await generator.ProcessAsync(testResult, TestBaseUrl); - response.DeviceCode.Should().NotBeNullOrWhiteSpace(); - response.Interval.Should().Be(options.DeviceFlow.Interval); + response.DeviceCode.ShouldNotBeNullOrWhiteSpace(); + response.Interval.ShouldBe(options.DeviceFlow.Interval); var deviceCode = await deviceFlowCodeService.FindByDeviceCodeAsync(response.DeviceCode); - deviceCode.Should().NotBeNull(); - deviceCode.ClientId.Should().Be(testResult.ValidatedRequest.Client.ClientId); - deviceCode.IsOpenId.Should().Be(testResult.ValidatedRequest.IsOpenIdRequest); - deviceCode.Lifetime.Should().Be(testResult.ValidatedRequest.Client.DeviceCodeLifetime); - deviceCode.CreationTime.Should().Be(creationTime); - deviceCode.Subject.Should().BeNull(); - deviceCode.AuthorizedScopes.Should().BeNull(); + deviceCode.ShouldNotBeNull(); + deviceCode.ClientId.ShouldBe(testResult.ValidatedRequest.Client.ClientId); + deviceCode.IsOpenId.ShouldBe(testResult.ValidatedRequest.IsOpenIdRequest); + deviceCode.Lifetime.ShouldBe(testResult.ValidatedRequest.Client.DeviceCodeLifetime); + deviceCode.CreationTime.ShouldBe(creationTime); + deviceCode.Subject.ShouldBeNull(); + deviceCode.AuthorizedScopes.ShouldBeNull(); - response.DeviceCodeLifetime.Should().Be(deviceCode.Lifetime); + response.DeviceCodeLifetime.ShouldBe(deviceCode.Lifetime); } [Fact] @@ -160,8 +160,8 @@ public async Task ProcessAsync_when_DeviceVerificationUrl_is_relative_uri_expect var response = await generator.ProcessAsync(testResult, baseUrl); - response.VerificationUri.Should().Be("http://localhost:5000/device"); - response.VerificationUriComplete.Should().StartWith("http://localhost:5000/device?userCode="); + response.VerificationUri.ShouldBe("http://localhost:5000/device"); + response.VerificationUriComplete.ShouldStartWith("http://localhost:5000/device?userCode="); } [Fact] @@ -173,8 +173,8 @@ public async Task ProcessAsync_when_DeviceVerificationUrl_is_absolute_uri_expect var response = await generator.ProcessAsync(testResult, baseUrl); - response.VerificationUri.Should().Be("http://short/device"); - response.VerificationUriComplete.Should().StartWith("http://short/device?userCode="); + response.VerificationUri.ShouldBe("http://short/device"); + response.VerificationUriComplete.ShouldStartWith("http://short/device?userCode="); } } diff --git a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/UserInfoResponseGeneratorTests.cs b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/UserInfoResponseGeneratorTests.cs index 1d575c7dd..51058471f 100644 --- a/identity-server/test/IdentityServer.UnitTests/ResponseHandling/UserInfoResponseGeneratorTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/ResponseHandling/UserInfoResponseGeneratorTests.cs @@ -12,7 +12,7 @@ using Duende.IdentityServer.ResponseHandling; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Xunit; @@ -57,7 +57,7 @@ public async Task GetRequestedClaimTypesAsync_when_no_scopes_requested_should_re { var resources = await _subject.GetRequestedResourcesAsync(null); var claims = await _subject.GetRequestedClaimTypesAsync(resources); - claims.Should().BeEquivalentTo(new string[] { }); + claims.ShouldBeEquivalentTo(new string[] { }); } [Fact] @@ -68,7 +68,7 @@ public async Task GetRequestedClaimTypesAsync_should_return_correct_identity_cla var resources = await _subject.GetRequestedResourcesAsync(new[] { "id1", "id2", "id3" }); var claims = await _subject.GetRequestedClaimTypesAsync(resources); - claims.Should().BeEquivalentTo(new string[] { "c1", "c2", "c3" }); + claims.ShouldBeEquivalentTo(new string[] { "c1", "c2", "c3" }); } [Fact] @@ -79,7 +79,7 @@ public async Task GetRequestedClaimTypesAsync_should_only_return_enabled_identit var resources = await _subject.GetRequestedResourcesAsync(new[] { "id1", "id2", "id3" }); var claims = await _subject.GetRequestedClaimTypesAsync(resources); - claims.Should().BeEquivalentTo(new string[] { "c2", "c3" }); + claims.ShouldBeEquivalentTo(new string[] { "c2", "c3" }); } [Fact] @@ -105,8 +105,8 @@ public async Task ProcessAsync_should_call_profile_service_with_requested_claim_ var claims = await _subject.ProcessAsync(result); - _mockProfileService.GetProfileWasCalled.Should().BeTrue(); - _mockProfileService.ProfileContext.RequestedClaimTypes.Should().BeEquivalentTo(new[] { "foo", "bar" }); + _mockProfileService.GetProfileWasCalled.ShouldBeTrue(); + _mockProfileService.ProfileContext.RequestedClaimTypes.ShouldBeEquivalentTo(new[] { "foo", "bar" }); } [Fact] @@ -148,18 +148,18 @@ public async Task ProcessAsync_should_return_claims_issued_by_profile_service() var claims = await _subject.ProcessAsync(result); - claims.Should().ContainKey("email"); - claims["email"].Should().Be("fred@gmail.com"); - claims.Should().ContainKey("name"); - claims["name"].Should().Be("fred jones"); + claims.ShouldContainKey("email"); + claims["email"].ShouldBe("fred@gmail.com"); + claims.ShouldContainKey("name"); + claims["name"].ShouldBe("fred jones"); // this will be treated as a string because this is not valid JSON from the System.Text library point of view - claims.Should().ContainKey("address"); - claims["address"].Should().Be("{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }"); + claims.ShouldContainKey("address"); + claims["address"].ShouldBe("{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }"); // this is a JsonElement - claims.Should().ContainKey("address2"); - claims["address2"].ToString().Should().Be("{\"street_address\":\"One Hacker Way\",\"locality\":\"Heidelberg\",\"postal_code\":69118,\"country\":\"Germany\"}"); + claims.ShouldContainKey("address2"); + claims["address2"].ToString().ShouldBe("{\"street_address\":\"One Hacker Way\",\"locality\":\"Heidelberg\",\"postal_code\":69118,\"country\":\"Germany\"}"); } [Fact] @@ -185,8 +185,8 @@ public async Task ProcessAsync_should_return_sub_from_user() var claims = await _subject.ProcessAsync(result); - claims.Should().ContainKey("sub"); - claims["sub"].Should().Be("bob"); + claims.ShouldContainKey("sub"); + claims["sub"].ShouldBe("bob"); } [Fact] @@ -216,8 +216,7 @@ public async Task ProcessAsync_should_throw_if_incorrect_sub_issued_by_profile_s Func act = () => _subject.ProcessAsync(result); - await act.Should().ThrowAsync() - .WithMessage("*subject*"); + var exception = await act.ShouldThrowAsync(); + exception.Message.ShouldBe("*subject*"); } - } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultBackChannelLogoutServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultBackChannelLogoutServiceTests.cs index f6d0b77a2..75a3d68df 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultBackChannelLogoutServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultBackChannelLogoutServiceTests.cs @@ -8,7 +8,7 @@ using Duende.IdentityServer; using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Services; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Logging; @@ -71,6 +71,6 @@ public async Task CreateTokenAsync_Should_Set_Issuer_Correctly() var payload = JsonSerializer.Deserialize>(Base64Url.Decode(rawToken.Split('.')[1])); - payload["iss"].GetString().Should().Be(expected); + payload["iss"].GetString().ShouldBe(expected); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultBackchannelAuthenticationInteractionServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultBackchannelAuthenticationInteractionServiceTests.cs index 05e5dac9b..b1a34aa4c 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultBackchannelAuthenticationInteractionServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultBackchannelAuthenticationInteractionServiceTests.cs @@ -11,7 +11,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Xunit; @@ -63,8 +63,8 @@ await _mockStore.CreateRequestAsync(new BackChannelAuthenticationRequest }); var results = await _subject.GetPendingLoginRequestsForCurrentUserAsync(); - results.Count().Should().Be(1); - results.First().InternalId.Should().Be(req.InternalId); + results.Count().ShouldBe(1); + results.First().InternalId.ShouldBe(req.InternalId); } [Fact] @@ -84,7 +84,7 @@ await _mockStore.CreateRequestAsync(new BackChannelAuthenticationRequest }); var result = await _subject.GetLoginRequestByInternalIdAsync(req.InternalId); - result.InternalId.Should().Be(req.InternalId); + result.InternalId.ShouldBe(req.InternalId); } [Fact] @@ -115,17 +115,17 @@ await _subject.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest(req }); var item = _mockStore.Items[requestId]; - item.IsComplete.Should().BeTrue(); - item.Description.Should().Be("desc"); - item.SessionId.Should().Be("sid"); - item.AuthorizedScopes.Should().BeEquivalentTo(new[] { "scope2", "scope1" }); - - item.Subject.HasClaim("sub", "123").Should().BeTrue(); - item.Subject.HasClaim("foo", "bar").Should().BeTrue(); - item.Subject.HasClaim("amr", "phone").Should().BeTrue(); - item.Subject.HasClaim("amr", "pin").Should().BeTrue(); - item.Subject.HasClaim("idp", "idp").Should().BeTrue(); - item.Subject.HasClaim("auth_time", new DateTimeOffset(new DateTime(2000, 02, 03, 8, 15, 00, DateTimeKind.Utc)).ToUnixTimeSeconds().ToString()).Should().BeTrue(); + item.IsComplete.ShouldBeTrue(); + item.Description.ShouldBe("desc"); + item.SessionId.ShouldBe("sid"); + item.AuthorizedScopes.ShouldBeEquivalentTo(new[] { "scope2", "scope1" }); + + item.Subject.HasClaim("sub", "123").ShouldBeTrue(); + item.Subject.HasClaim("foo", "bar").ShouldBeTrue(); + item.Subject.HasClaim("amr", "phone").ShouldBeTrue(); + item.Subject.HasClaim("amr", "pin").ShouldBeTrue(); + item.Subject.HasClaim("idp", "idp").ShouldBeTrue(); + item.Subject.HasClaim("auth_time", new DateTimeOffset(new DateTime(2000, 02, 03, 8, 15, 00, DateTimeKind.Utc)).ToUnixTimeSeconds().ToString()).ShouldBeTrue(); } [Fact] @@ -141,7 +141,7 @@ public async Task CompleteLoginRequestAsync_should_require_request_object() var requestId = await _mockStore.CreateRequestAsync(req); Func f = async () => await _subject.CompleteLoginRequestAsync(null); - await f.Should().ThrowAsync(); + await f.ShouldThrowAsync(); } [Fact] @@ -170,7 +170,8 @@ public async Task CompleteLoginRequestAsync_should_prevent_scopes_not_requested( AuthenticationMethods = { "phone", "pin" } }.CreatePrincipal() }); - await f.Should().ThrowAsync().WithMessage("More scopes consented than originally requested."); + var exception = await f.ShouldThrowAsync(); + exception.Message.ShouldBe("More scopes consented than originally requested."); } [Fact] @@ -199,7 +200,8 @@ public async Task CompleteLoginRequestAsync_should_prevent_invalid_subject_id() AuthenticationMethods = { "phone", "pin" } }.CreatePrincipal() }); - await f.Should().ThrowAsync().WithMessage("User's subject id: 'invalid' does not match subject id for backchannel authentication request: '123'."); + var exception = await f.ShouldThrowAsync(); + exception.Message.ShouldBe("User's subject id: 'invalid' does not match subject id for backchannel authentication request: '123'."); } [Fact] @@ -227,7 +229,8 @@ public async Task CompleteLoginRequestAsync_should_require_a_subject() // AuthenticationMethods = { "phone", "pin" } //}.CreatePrincipal() }); - await f.Should().ThrowAsync().WithMessage("Invalid subject."); + var exception = await f.ShouldThrowAsync(); + exception.Message.ShouldBe("Invalid subject."); } [Fact] @@ -255,7 +258,8 @@ public async Task CompleteLoginRequestAsync_should_require_a_valid_request_id() AuthenticationMethods = { "phone", "pin" } }.CreatePrincipal() }); - await f.Should().ThrowAsync().WithMessage("Invalid backchannel authentication request id."); + var exception = await f.ShouldThrowAsync(); + exception.Message.ShouldBe("Invalid backchannel authentication request id."); } [Fact] @@ -289,14 +293,14 @@ await _subject.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest(req }); var item = _mockStore.Items[requestId]; - item.SessionId.Should().Be("session id"); - - item.Subject.HasClaim("sub", "123").Should().BeTrue(); - item.Subject.HasClaim("foo", "bar").Should().BeTrue(); - item.Subject.HasClaim("amr", "phone").Should().BeTrue(); - item.Subject.HasClaim("amr", "pin").Should().BeTrue(); - item.Subject.HasClaim("idp", "idp").Should().BeTrue(); - item.Subject.HasClaim("auth_time", new DateTimeOffset(new DateTime(2000, 02, 03, 8, 15, 00, DateTimeKind.Utc)).ToUnixTimeSeconds().ToString()).Should().BeTrue(); + item.SessionId.ShouldBe("session id"); + + item.Subject.HasClaim("sub", "123").ShouldBeTrue(); + item.Subject.HasClaim("foo", "bar").ShouldBeTrue(); + item.Subject.HasClaim("amr", "phone").ShouldBeTrue(); + item.Subject.HasClaim("amr", "pin").ShouldBeTrue(); + item.Subject.HasClaim("idp", "idp").ShouldBeTrue(); + item.Subject.HasClaim("auth_time", new DateTimeOffset(new DateTime(2000, 02, 03, 8, 15, 00, DateTimeKind.Utc)).ToUnixTimeSeconds().ToString()).ShouldBeTrue(); } [Fact] @@ -327,7 +331,7 @@ await _subject.CompleteLoginRequestAsync(new CompleteBackchannelLoginRequest(req }); var item = _mockStore.Items[requestId]; - item.Subject.HasClaim("idp", "local").Should().BeTrue(); - item.Subject.HasClaim("auth_time", _mockSystemClock.UtcNow.ToUnixTimeSeconds().ToString()).Should().BeTrue(); + item.Subject.HasClaim("idp", "local").ShouldBeTrue(); + item.Subject.HasClaim("auth_time", _mockSystemClock.UtcNow.ToUnixTimeSeconds().ToString()).ShouldBeTrue(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultClaimsServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultClaimsServiceTests.cs index eb240c2df..9792dd91d 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultClaimsServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultClaimsServiceTests.cs @@ -10,7 +10,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using Xunit; @@ -65,11 +65,11 @@ public async Task GetIdentityTokenClaimsAsync_should_return_standard_user_claims var claims = await _subject.GetIdentityTokenClaimsAsync(_user, ResourceValidationResult, false, _validatedRequest); var types = claims.Select(x => x.Type); - types.Should().Contain(JwtClaimTypes.Subject); - types.Should().Contain(JwtClaimTypes.AuthenticationTime); - types.Should().Contain(JwtClaimTypes.IdentityProvider); - types.Should().Contain(JwtClaimTypes.AuthenticationMethod); - types.Should().Contain(JwtClaimTypes.AuthenticationContextClassReference); + types.ShouldContain(JwtClaimTypes.Subject); + types.ShouldContain(JwtClaimTypes.AuthenticationTime); + types.ShouldContain(JwtClaimTypes.IdentityProvider); + types.ShouldContain(JwtClaimTypes.AuthenticationMethod); + types.ShouldContain(JwtClaimTypes.AuthenticationContextClassReference); } [Fact] @@ -79,7 +79,7 @@ public async Task GetIdentityTokenClaimsAsync_should_return_minimal_claims_when_ var claims = await _subject.GetIdentityTokenClaimsAsync(_user, ResourceValidationResult, false, _validatedRequest); - _mockMockProfileService.GetProfileWasCalled.Should().BeFalse(); + _mockMockProfileService.GetProfileWasCalled.ShouldBeFalse(); } [Fact] @@ -90,8 +90,8 @@ public async Task GetIdentityTokenClaimsAsync_should_return_all_claims_when_incl var claims = await _subject.GetIdentityTokenClaimsAsync(_user, ResourceValidationResult, true, _validatedRequest); - _mockMockProfileService.GetProfileWasCalled.Should().BeTrue(); - _mockMockProfileService.ProfileContext.RequestedClaimTypes.Should().Contain("foo"); + _mockMockProfileService.GetProfileWasCalled.ShouldBeTrue(); + _mockMockProfileService.ProfileContext.RequestedClaimTypes.ShouldContain("foo"); } [Fact] @@ -104,8 +104,8 @@ public async Task GetIdentityTokenClaimsAsync_should_return_all_claims_when_clie var claims = await _subject.GetIdentityTokenClaimsAsync(_user, ResourceValidationResult, false, _validatedRequest); - _mockMockProfileService.GetProfileWasCalled.Should().BeTrue(); - _mockMockProfileService.ProfileContext.RequestedClaimTypes.Should().Contain("foo"); + _mockMockProfileService.GetProfileWasCalled.ShouldBeTrue(); + _mockMockProfileService.ProfileContext.RequestedClaimTypes.ShouldContain("foo"); } [Fact] @@ -116,7 +116,7 @@ public async Task GetIdentityTokenClaimsAsync_should_filter_protocol_claims_from var claims = await _subject.GetIdentityTokenClaimsAsync(_user, ResourceValidationResult, true, _validatedRequest); - claims.Count(x => x.Type == "aud" && x.Value == "bar").Should().Be(0); + claims.Count(x => x.Type == "aud" && x.Value == "bar").ShouldBe(0); } [Fact] @@ -124,7 +124,7 @@ public async Task GetAccessTokenClaimsAsync_should_contain_client_id() { var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); - claims.Count(x => x.Type == JwtClaimTypes.ClientId && x.Value == _client.ClientId).Should().Be(1); + claims.Count(x => x.Type == JwtClaimTypes.ClientId && x.Value == _client.ClientId).ShouldBe(1); } [Fact] @@ -132,7 +132,7 @@ public async Task GetAccessTokenClaimsAsync_client_claims_should_be_prefixed_wit { var claims = await _subject.GetAccessTokenClaimsAsync(null, ResourceValidationResult, _validatedRequest); - claims.Count(x => x.Type == "client_some_claim" && x.Value == "some_claim_value").Should().Be(1); + claims.Count(x => x.Type == "client_some_claim" && x.Value == "some_claim_value").ShouldBe(1); } [Fact] @@ -141,7 +141,7 @@ public async Task GetAccessTokenClaimsAsync_client_claims_should_be_prefixed_wit _validatedRequest.Client.ClientClaimsPrefix = "custom_prefix_"; var claims = await _subject.GetAccessTokenClaimsAsync(null, ResourceValidationResult, _validatedRequest); - claims.Count(x => x.Type == "custom_prefix_some_claim" && x.Value == "some_claim_value").Should().Be(1); + claims.Count(x => x.Type == "custom_prefix_some_claim" && x.Value == "some_claim_value").ShouldBe(1); } [Fact] @@ -150,7 +150,7 @@ public async Task GetAccessTokenClaimsAsync_should_contain_client_claims_when_no _validatedRequest.Client.ClientClaimsPrefix = null; var claims = await _subject.GetAccessTokenClaimsAsync(null, ResourceValidationResult, _validatedRequest); - claims.Count(x => x.Type == "some_claim" && x.Value == "some_claim_value").Should().Be(1); + claims.Count(x => x.Type == "some_claim" && x.Value == "some_claim_value").ShouldBe(1); } [Fact] @@ -161,7 +161,7 @@ public async Task GetAccessTokenClaimsAsync_should_contain_client_claims_when_co var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); - claims.Count(x => x.Type == "some_claim" && x.Value == "some_claim_value").Should().Be(1); + claims.Count(x => x.Type == "some_claim" && x.Value == "some_claim_value").ShouldBe(1); } [Fact] @@ -175,8 +175,8 @@ public async Task GetAccessTokenClaimsAsync_should_contain_scopes() var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); var scopes = claims.Where(x => x.Type == JwtClaimTypes.Scope).Select(x => x.Value); - scopes.Count().Should().Be(4); - scopes.ToArray().Should().BeEquivalentTo(new string[] { "api1", "api2", "id1", "id2" }); + scopes.Count().ShouldBe(4); + scopes.ToArray().ShouldBeEquivalentTo(new string[] { "api1", "api2", "id1", "id2" }); } [Fact] @@ -192,8 +192,8 @@ public async Task GetAccessTokenClaimsAsync_should_contain_parameterized_scope_v var claims = await _subject.GetAccessTokenClaimsAsync(_user, resourceResult, _validatedRequest); var scopes = claims.Where(x => x.Type == JwtClaimTypes.Scope).Select(x => x.Value); - scopes.Count().Should().Be(1); - scopes.ToArray().Should().BeEquivalentTo(new string[] { "api:123" }); + scopes.Count().ShouldBe(1); + scopes.ToArray().ShouldBeEquivalentTo(new string[] { "api:123" }); } [Fact] @@ -204,7 +204,7 @@ public async Task GetAccessTokenClaimsAsync_when_no_ApiScopes_should_not_contain var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); var scopes = claims.Where(x => x.Type == JwtClaimTypes.Scope).Select(x => x.Value); - scopes.Count().Should().Be(0); + scopes.Count().ShouldBe(0); } [Fact] @@ -222,8 +222,8 @@ public async Task GetAccessTokenClaimsAsync_should_only_consider_parsed_scope_va var claims = await _subject.GetAccessTokenClaimsAsync(_user, resourceResult, _validatedRequest); var scopes = claims.Where(x => x.Type == JwtClaimTypes.Scope).Select(x => x.Value); - scopes.Count().Should().Be(1); - scopes.ToArray().Should().BeEquivalentTo(new string[] { "api2" }); + scopes.Count().ShouldBe(1); + scopes.ToArray().ShouldBeEquivalentTo(new string[] { "api2" }); } [Fact] @@ -242,8 +242,8 @@ public async Task GetAccessTokenClaimsAsync_when_multiple_resources_with_same_sc var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); var scopes = claims.Where(x => x.Type == JwtClaimTypes.Scope).Select(x => x.Value); - scopes.Count().Should().Be(1); - scopes.ToArray().Should().BeEquivalentTo(new string[] { "resource" }); + scopes.Count().ShouldBe(1); + scopes.ToArray().ShouldBeEquivalentTo(new string[] { "resource" }); } [Fact] @@ -258,7 +258,7 @@ public async Task GetAccessTokenClaimsAsync_should_contain_offline_scope() var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); var scopes = claims.Where(x => x.Type == JwtClaimTypes.Scope).Select(x => x.Value); - scopes.Should().Contain(IdentityServerConstants.StandardScopes.OfflineAccess); + scopes.ShouldContain(IdentityServerConstants.StandardScopes.OfflineAccess); } [Fact] @@ -273,7 +273,7 @@ public async Task GetAccessTokenClaimsAsync_should_not_contain_offline_scope_if_ var claims = await _subject.GetAccessTokenClaimsAsync(null, ResourceValidationResult, _validatedRequest); var scopes = claims.Where(x => x.Type == JwtClaimTypes.Scope).Select(x => x.Value); - scopes.Should().NotContain(IdentityServerConstants.StandardScopes.OfflineAccess); + scopes.ShouldNotContain(IdentityServerConstants.StandardScopes.OfflineAccess); } [Fact] @@ -282,11 +282,11 @@ public async Task GetAccessTokenClaimsAsync_should_return_standard_user_claims() var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); var types = claims.Select(x => x.Type); - types.Should().Contain(JwtClaimTypes.Subject); - types.Should().Contain(JwtClaimTypes.AuthenticationTime); - types.Should().Contain(JwtClaimTypes.IdentityProvider); - types.Should().Contain(JwtClaimTypes.AuthenticationMethod); - types.Should().Contain(JwtClaimTypes.AuthenticationContextClassReference); + types.ShouldContain(JwtClaimTypes.Subject); + types.ShouldContain(JwtClaimTypes.AuthenticationTime); + types.ShouldContain(JwtClaimTypes.IdentityProvider); + types.ShouldContain(JwtClaimTypes.AuthenticationMethod); + types.ShouldContain(JwtClaimTypes.AuthenticationContextClassReference); } [Fact] @@ -297,9 +297,9 @@ public async Task GetAccessTokenClaimsAsync_should_only_contain_api_claims() var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); - _mockMockProfileService.GetProfileWasCalled.Should().BeTrue(); - _mockMockProfileService.ProfileContext.RequestedClaimTypes.Should().NotContain("foo"); - _mockMockProfileService.ProfileContext.RequestedClaimTypes.Should().Contain("bar"); + _mockMockProfileService.GetProfileWasCalled.ShouldBeTrue(); + _mockMockProfileService.ProfileContext.RequestedClaimTypes.ShouldNotContain("foo"); + _mockMockProfileService.ProfileContext.RequestedClaimTypes.ShouldContain("bar"); } [Fact] @@ -310,7 +310,7 @@ public async Task GetAccessTokenClaimsAsync_should_filter_protocol_claims_from_p var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); - claims.Count(x => x.Type == "aud" && x.Value == "bar").Should().Be(0); + claims.Count(x => x.Type == "aud" && x.Value == "bar").ShouldBe(0); } [Fact] @@ -320,7 +320,7 @@ public async Task GetAccessTokenClaimsAsync_should_request_api_claims() var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); - _mockMockProfileService.ProfileContext.RequestedClaimTypes.Should().Contain("foo"); + _mockMockProfileService.ProfileContext.RequestedClaimTypes.ShouldContain("foo"); } [Fact] @@ -341,7 +341,7 @@ public async Task GetAccessTokenClaimsAsync_should_request_api_scope_claims() var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); - _mockMockProfileService.ProfileContext.RequestedClaimTypes.Should().Contain("foo"); + _mockMockProfileService.ProfileContext.RequestedClaimTypes.ShouldContain("foo"); } [Fact] @@ -363,7 +363,7 @@ public async Task GetAccessTokenClaimsAsync_should_request_both_api_and_api_scop var claims = await _subject.GetAccessTokenClaimsAsync(_user, ResourceValidationResult, _validatedRequest); - _mockMockProfileService.ProfileContext.RequestedClaimTypes.Should().Contain("foo"); - _mockMockProfileService.ProfileContext.RequestedClaimTypes.Should().Contain("bar"); + _mockMockProfileService.ProfileContext.RequestedClaimTypes.ShouldContain("foo"); + _mockMockProfileService.ProfileContext.RequestedClaimTypes.ShouldContain("bar"); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultConsentServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultConsentServiceTests.cs index d29a2b004..7176a936c 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultConsentServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultConsentServiceTests.cs @@ -11,7 +11,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using Xunit; @@ -73,7 +73,7 @@ public async Task UpdateConsentAsync_when_client_does_not_allow_remember_consent await _subject.UpdateConsentAsync(_user, _client, new [] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }); var consent = await _userConsentStore.GetUserConsentAsync(_user.GetSubjectId(), _client.ClientId); - consent.Should().BeNull(); + consent.ShouldBeNull(); } [Fact] @@ -82,9 +82,9 @@ public async Task UpdateConsentAsync_should_persist_consent() await _subject.UpdateConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }); var consent = await _userConsentStore.GetUserConsentAsync(_user.GetSubjectId(), _client.ClientId); - consent.Scopes.Count().Should().Be(2); - consent.Scopes.Should().Contain("scope1"); - consent.Scopes.Should().Contain("scope2"); + consent.Scopes.Count().ShouldBe(2); + consent.Scopes.ShouldContain("scope1"); + consent.Scopes.ShouldContain("scope2"); } [Fact] @@ -95,7 +95,7 @@ public async Task UpdateConsentAsync_empty_scopes_should_remove_consent() await _subject.UpdateConsentAsync(_user, _client, new ParsedScopeValue[] { }); var consent = await _userConsentStore.GetUserConsentAsync(_user.GetSubjectId(), _client.ClientId); - consent.Should().BeNull(); + consent.ShouldBeNull(); } [Fact] @@ -105,7 +105,7 @@ public async Task RequiresConsentAsync_client_does_not_require_consent_should_no var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }); - result.Should().BeFalse(); + result.ShouldBeFalse(); } [Fact] @@ -115,7 +115,7 @@ public async Task RequiresConsentAsync_client_does_not_allow_remember_consent_sh var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }); - result.Should().BeTrue(); + result.ShouldBeTrue(); } [Fact] @@ -123,7 +123,7 @@ public async Task RequiresConsentAsync_no_scopes_should_not_require_consent() { var result = await _subject.RequiresConsentAsync(_user, _client, new ParsedScopeValue[] { }); - result.Should().BeFalse(); + result.ShouldBeFalse(); } [Fact] @@ -131,7 +131,7 @@ public async Task RequiresConsentAsync_offline_access_should_require_consent() { var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("offline_access") }); - result.Should().BeTrue(); + result.ShouldBeTrue(); } [Fact] @@ -139,7 +139,7 @@ public async Task RequiresConsentAsync_no_prior_consent_should_require_consent() { var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }); - result.Should().BeTrue(); + result.ShouldBeTrue(); } [Fact] @@ -149,7 +149,7 @@ public async Task RequiresConsentAsync_prior_consent_should_not_require_consent( var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }); - result.Should().BeFalse(); + result.ShouldBeFalse(); } [Fact] @@ -159,7 +159,7 @@ public async Task RequiresConsentAsync_prior_consent_with_more_scopes_should_not var result = await _subject.RequiresConsentAsync(_user, _client, new [] { new ParsedScopeValue("scope2") }); - result.Should().BeFalse(); + result.ShouldBeFalse(); } [Fact] @@ -169,7 +169,7 @@ public async Task RequiresConsentAsync_prior_consent_with_too_few_scopes_should_ var result = await _subject.RequiresConsentAsync(_user, _client, new[] { new ParsedScopeValue("scope1"), new ParsedScopeValue("scope2") }); - result.Should().BeTrue(); + result.ShouldBeTrue(); } [Fact] @@ -186,7 +186,7 @@ public async Task RequiresConsentAsync_expired_consent_should_require_consent() var result = await _subject.RequiresConsentAsync(_user, _client, scopes); - result.Should().BeTrue(); + result.ShouldBeTrue(); } [Fact] @@ -205,6 +205,6 @@ public async Task RequiresConsentAsync_expired_consent_should_remove_consent() var result = await _userConsentStore.GetUserConsentAsync(_user.GetSubjectId(), _client.ClientId); - result.Should().BeNull(); + result.ShouldBeNull(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultCorsPolicyServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultCorsPolicyServiceTests.cs index 85b6b9e45..981e11f1b 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultCorsPolicyServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultCorsPolicyServiceTests.cs @@ -5,7 +5,7 @@ using System; using System.Threading.Tasks; using Duende.IdentityServer.Services; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Xunit; @@ -26,9 +26,9 @@ public DefaultCorsPolicyServiceTests() [Trait("Category", Category)] public async Task IsOriginAllowed_null_param_ReturnsFalse() { - (await subject.IsOriginAllowedAsync(null)).Should().Be(false); - (await subject.IsOriginAllowedAsync(String.Empty)).Should().Be(false); - (await subject.IsOriginAllowedAsync(" ")).Should().Be(false); + (await subject.IsOriginAllowedAsync(null)).ShouldBe(false); + (await subject.IsOriginAllowedAsync(String.Empty)).ShouldBe(false); + (await subject.IsOriginAllowedAsync(" ")).ShouldBe(false); } [Fact] @@ -36,7 +36,7 @@ public async Task IsOriginAllowed_null_param_ReturnsFalse() public async Task IsOriginAllowed_OriginIsAllowed_ReturnsTrue() { subject.AllowedOrigins.Add("http://foo"); - (await subject.IsOriginAllowedAsync("http://foo")).Should().Be(true); + (await subject.IsOriginAllowedAsync("http://foo")).ShouldBe(true); } [Fact] @@ -44,7 +44,7 @@ public async Task IsOriginAllowed_OriginIsAllowed_ReturnsTrue() public async Task IsOriginAllowed_OriginIsNotAllowed_ReturnsFalse() { subject.AllowedOrigins.Add("http://foo"); - (await subject.IsOriginAllowedAsync("http://bar")).Should().Be(false); + (await subject.IsOriginAllowedAsync("http://bar")).ShouldBe(false); } [Fact] @@ -54,7 +54,7 @@ public async Task IsOriginAllowed_OriginIsInAllowedList_ReturnsTrue() subject.AllowedOrigins.Add("http://foo"); subject.AllowedOrigins.Add("http://bar"); subject.AllowedOrigins.Add("http://baz"); - (await subject.IsOriginAllowedAsync("http://bar")).Should().Be(true); + (await subject.IsOriginAllowedAsync("http://bar")).ShouldBe(true); } [Fact] @@ -64,7 +64,7 @@ public async Task IsOriginAllowed_OriginIsNotInAllowedList_ReturnsFalse() subject.AllowedOrigins.Add("http://foo"); subject.AllowedOrigins.Add("http://bar"); subject.AllowedOrigins.Add("http://baz"); - (await subject.IsOriginAllowedAsync("http://quux")).Should().Be(false); + (await subject.IsOriginAllowedAsync("http://quux")).ShouldBe(false); } [Fact] @@ -72,6 +72,6 @@ public async Task IsOriginAllowed_OriginIsNotInAllowedList_ReturnsFalse() public async Task IsOriginAllowed_AllowAllTrue_ReturnsTrue() { subject.AllowAll = true; - (await subject.IsOriginAllowedAsync("http://foo")).Should().Be(true); + (await subject.IsOriginAllowedAsync("http://foo")).ShouldBe(true); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultEventServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultEventServiceTests.cs index 0bf3d4d47..52c77c8f7 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultEventServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultEventServiceTests.cs @@ -4,7 +4,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Events; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using UnitTests.Services.Default.KeyManagement; using Xunit; @@ -33,7 +33,7 @@ public async Task Raising_an_event_without_http_context_does_not_throw() await sut.RaiseAsync(evt); - sink.Events.Should().Contain(e => e.Id == 123); + sink.Events.ShouldContain(e => e.Id == 123); } diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultIdentityServerInteractionServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultIdentityServerInteractionServiceTests.cs index 09c6c4a98..89f2209b3 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultIdentityServerInteractionServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultIdentityServerInteractionServiceTests.cs @@ -10,7 +10,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Xunit; @@ -62,7 +62,7 @@ public async Task GetLogoutContextAsync_valid_session_and_logout_id_should_not_p var context = await _subject.GetLogoutContextAsync("id"); - context.SignOutIFrameUrl.Should().BeNull(); + context.SignOutIFrameUrl.ShouldBeNull(); } [Fact] @@ -74,7 +74,7 @@ public async Task GetLogoutContextAsync_valid_session_no_logout_id_should_provid var context = await _subject.GetLogoutContextAsync(null); - context.SignOutIFrameUrl.Should().NotBeNull(); + context.SignOutIFrameUrl.ShouldNotBeNull(); } [Fact] @@ -85,7 +85,7 @@ public async Task GetLogoutContextAsync_without_session_should_not_provide_ifram var context = await _subject.GetLogoutContextAsync("id"); - context.SignOutIFrameUrl.Should().BeNull(); + context.SignOutIFrameUrl.ShouldBeNull(); } [Fact] @@ -93,8 +93,8 @@ public async Task CreateLogoutContextAsync_without_session_should_not_create_ses { var context = await _subject.CreateLogoutContextAsync(); - context.Should().BeNull(); - _mockLogoutMessageStore.Messages.Should().BeEmpty(); + context.ShouldBeNull(); + _mockLogoutMessageStore.Messages.ShouldBeEmpty(); } [Fact] @@ -106,8 +106,8 @@ public async Task CreateLogoutContextAsync_with_session_should_create_session() var context = await _subject.CreateLogoutContextAsync(); - context.Should().NotBeNull(); - _mockLogoutMessageStore.Messages.Should().NotBeEmpty(); + context.ShouldNotBeNull(); + _mockLogoutMessageStore.Messages.ShouldNotBeEmpty(); } [Fact] @@ -118,8 +118,8 @@ public async Task GrantConsentAsync_should_throw_if_granted_and_no_subject() new ConsentResponse() { ScopesValuesConsented = new[] { "openid" } }, null); - await act.Should().ThrowAsync() - .WithMessage("*subject*"); + var exception = await act.ShouldThrowAsync(); + exception.ParamName.ShouldBe("*subject*"); } [Fact] @@ -144,8 +144,8 @@ public async Task GrantConsentAsync_should_use_current_subject_and_create_messag }; await _subject.GrantConsentAsync(req, new ConsentResponse(), null); - _mockConsentStore.Messages.Should().NotBeEmpty(); + _mockConsentStore.Messages.ShouldNotBeEmpty(); var consentRequest = new ConsentRequest(req, "bob"); - _mockConsentStore.Messages.First().Key.Should().Be(consentRequest.Id); + _mockConsentStore.Messages.First().Key.ShouldBe(consentRequest.Id); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultPersistedGrantServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultPersistedGrantServiceTests.cs index 1cba7b093..bf29c64a8 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultPersistedGrantServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultPersistedGrantServiceTests.cs @@ -13,7 +13,7 @@ using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Stores.Serialization; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Xunit; @@ -182,16 +182,16 @@ await _userConsent.StoreUserConsentAsync(new Consent() var grants = await _subject.GetAllGrantsAsync("123"); - grants.Count().Should().Be(2); + grants.Count().ShouldBe(2); var grant1 = grants.First(x => x.ClientId == "client1"); - grant1.SubjectId.Should().Be("123"); - grant1.ClientId.Should().Be("client1"); - grant1.Scopes.Should().BeEquivalentTo(new string[] { "foo1", "foo2", "bar1", "bar2", "baz1", "baz2", "quux1", "quux2" }); + grant1.SubjectId.ShouldBe("123"); + grant1.ClientId.ShouldBe("client1"); + grant1.Scopes.ShouldBeEquivalentTo(new string[] { "foo1", "foo2", "bar1", "bar2", "baz1", "baz2", "quux1", "quux2" }); var grant2 = grants.First(x => x.ClientId == "client2"); - grant2.SubjectId.Should().Be("123"); - grant2.ClientId.Should().Be("client2"); - grant2.Scopes.Should().BeEquivalentTo(new string[] { "foo3", "bar3", "baz3", "quux3" }); + grant2.SubjectId.ShouldBe("123"); + grant2.ClientId.ShouldBe("client2"); + grant2.Scopes.ShouldBeEquivalentTo(new string[] { "foo3", "bar3", "baz3", "quux3" }); } [Fact] @@ -322,15 +322,15 @@ await _userConsent.StoreUserConsentAsync(new Consent() await _subject.RemoveAllGrantsAsync("123", "client1"); - (await _referenceTokens.GetReferenceTokenAsync(handle1)).Should().BeNull(); - (await _referenceTokens.GetReferenceTokenAsync(handle2)).Should().NotBeNull(); - (await _referenceTokens.GetReferenceTokenAsync(handle3)).Should().NotBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle4)).Should().BeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle5)).Should().NotBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle6)).Should().NotBeNull(); - (await _codes.GetAuthorizationCodeAsync(handle7)).Should().BeNull(); - (await _codes.GetAuthorizationCodeAsync(handle8)).Should().NotBeNull(); - (await _codes.GetAuthorizationCodeAsync(handle9)).Should().NotBeNull(); + (await _referenceTokens.GetReferenceTokenAsync(handle1)).ShouldBeNull(); + (await _referenceTokens.GetReferenceTokenAsync(handle2)).ShouldNotBeNull(); + (await _referenceTokens.GetReferenceTokenAsync(handle3)).ShouldNotBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle4)).ShouldBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle5)).ShouldNotBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle6)).ShouldNotBeNull(); + (await _codes.GetAuthorizationCodeAsync(handle7)).ShouldBeNull(); + (await _codes.GetAuthorizationCodeAsync(handle8)).ShouldNotBeNull(); + (await _codes.GetAuthorizationCodeAsync(handle9)).ShouldNotBeNull(); } [Fact] public async Task RemoveAllGrantsAsync_should_filter_on_session_id() @@ -366,9 +366,9 @@ public async Task RemoveAllGrantsAsync_should_filter_on_session_id() await _subject.RemoveAllGrantsAsync("123"); - (await _refreshTokens.GetRefreshTokenAsync(handle1)).Should().BeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle2)).Should().BeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle3)).Should().BeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle1)).ShouldBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle2)).ShouldBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle3)).ShouldBeNull(); await _refreshTokens.RemoveRefreshTokenAsync(handle1); await _refreshTokens.RemoveRefreshTokenAsync(handle2); await _refreshTokens.RemoveRefreshTokenAsync(handle3); @@ -404,9 +404,9 @@ public async Task RemoveAllGrantsAsync_should_filter_on_session_id() await _subject.RemoveAllGrantsAsync("123", "client1"); - (await _refreshTokens.GetRefreshTokenAsync(handle1)).Should().BeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle2)).Should().NotBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle3)).Should().NotBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle1)).ShouldBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle2)).ShouldNotBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle3)).ShouldNotBeNull(); await _refreshTokens.RemoveRefreshTokenAsync(handle1); await _refreshTokens.RemoveRefreshTokenAsync(handle2); await _refreshTokens.RemoveRefreshTokenAsync(handle3); @@ -450,10 +450,10 @@ public async Task RemoveAllGrantsAsync_should_filter_on_session_id() }); await _subject.RemoveAllGrantsAsync("123", "client1", "session1"); - (await _refreshTokens.GetRefreshTokenAsync(handle1)).Should().BeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle2)).Should().NotBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle3)).Should().NotBeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle4)).Should().NotBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle1)).ShouldBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle2)).ShouldNotBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle3)).ShouldNotBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle4)).ShouldNotBeNull(); await _refreshTokens.RemoveRefreshTokenAsync(handle1); await _refreshTokens.RemoveRefreshTokenAsync(handle2); await _refreshTokens.RemoveRefreshTokenAsync(handle3); @@ -498,10 +498,10 @@ public async Task RemoveAllGrantsAsync_should_filter_on_session_id() }); await _subject.RemoveAllGrantsAsync("123", sessionId:"session1"); - (await _refreshTokens.GetRefreshTokenAsync(handle1)).Should().BeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle2)).Should().BeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle3)).Should().BeNull(); - (await _refreshTokens.GetRefreshTokenAsync(handle4)).Should().NotBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle1)).ShouldBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle2)).ShouldBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle3)).ShouldBeNull(); + (await _refreshTokens.GetRefreshTokenAsync(handle4)).ShouldNotBeNull(); await _refreshTokens.RemoveRefreshTokenAsync(handle1); await _refreshTokens.RemoveRefreshTokenAsync(handle2); await _refreshTokens.RemoveRefreshTokenAsync(handle3); @@ -521,8 +521,8 @@ await _userConsent.StoreUserConsentAsync(new Consent() var grants = await _subject.GetAllGrantsAsync("123"); - grants.Count().Should().Be(1); - grants.First().Scopes.Should().Contain(new string[] { "foo1", "foo2" }); + grants.Count().ShouldBe(1); + grants.First().Scopes.ShouldBe(["foo1", "foo2"]); var handle9 = await _codes.StoreAuthorizationCodeAsync(new AuthorizationCode() { @@ -538,8 +538,8 @@ await _userConsent.StoreUserConsentAsync(new Consent() grants = await _subject.GetAllGrantsAsync("123"); - grants.Count().Should().Be(1); - grants.First().Scopes.Should().Contain(new string[] { "foo1", "foo2", "quux3" }); + grants.Count().ShouldBe(1); + grants.First().Scopes.ShouldBe(["foo1", "foo2", "quux3"]); } [Fact] @@ -570,8 +570,8 @@ await _userConsent.StoreUserConsentAsync(new Consent() var grants = await _subject.GetAllGrantsAsync("123"); - grants.Count().Should().Be(1); - grants.First().Scopes.Should().Contain(new string[] { "foo1", "foo2" }); + grants.Count().ShouldBe(1); + grants.First().Scopes.ShouldBe(["foo1", "foo2"]); } class CorruptingPersistedGrantStore : IPersistedGrantStore diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultRefreshTokenServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultRefreshTokenServiceTests.cs index c2967d7f3..48401c690 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultRefreshTokenServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultRefreshTokenServiceTests.cs @@ -11,7 +11,7 @@ using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Stores.Serialization; -using FluentAssertions; +using Shouldly; using UnitTests.Validation.Setup; using Xunit; @@ -52,7 +52,7 @@ public async Task CreateRefreshToken_token_exists_in_store() var handle = await _subject.CreateRefreshTokenAsync(new RefreshTokenCreationRequest { Subject = _user, AccessToken = accessToken, Client = client }); - (await _store.GetRefreshTokenAsync(handle)).Should().NotBeNull(); + (await _store.GetRefreshTokenAsync(handle)).ShouldNotBeNull(); } [Fact] @@ -70,8 +70,8 @@ public async Task CreateRefreshToken_should_match_absolute_lifetime() var refreshToken = (await _store.GetRefreshTokenAsync(handle)); - refreshToken.Should().NotBeNull(); - refreshToken.Lifetime.Should().Be(client.AbsoluteRefreshTokenLifetime); + refreshToken.ShouldNotBeNull(); + refreshToken.Lifetime.ShouldBe(client.AbsoluteRefreshTokenLifetime); } [Fact] @@ -90,8 +90,8 @@ public async Task CreateRefreshToken_should_cap_sliding_lifetime_that_exceeds_ab var refreshToken = (await _store.GetRefreshTokenAsync(handle)); - refreshToken.Should().NotBeNull(); - refreshToken.Lifetime.Should().Be(client.AbsoluteRefreshTokenLifetime); + refreshToken.ShouldNotBeNull(); + refreshToken.Lifetime.ShouldBe(client.AbsoluteRefreshTokenLifetime); } [Fact] @@ -109,8 +109,8 @@ public async Task CreateRefreshToken_should_match_sliding_lifetime() var refreshToken = (await _store.GetRefreshTokenAsync(handle)); - refreshToken.Should().NotBeNull(); - refreshToken.Lifetime.Should().Be(client.SlidingRefreshTokenLifetime); + refreshToken.ShouldNotBeNull(); + refreshToken.Lifetime.ShouldBe(client.SlidingRefreshTokenLifetime); } @@ -132,9 +132,7 @@ public async Task UpdateRefreshToken_one_time_use_should_create_new_token() var handle = await _store.StoreRefreshTokenAsync(refreshToken); (await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client })) - .Should().NotBeNull() - .And - .NotBe(handle); + .ShouldNotBe(handle); } [Fact] @@ -160,12 +158,12 @@ public async Task UpdateRefreshToken_sliding_with_non_zero_absolute_should_updat var refreshToken = await _store.GetRefreshTokenAsync(handle); var newHandle = await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client }); - newHandle.Should().NotBeNull().And.Be(handle); + newHandle.ShouldBe(handle); var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle); - newRefreshToken.Should().NotBeNull(); - newRefreshToken.Lifetime.Should().Be((int)(now - newRefreshToken.CreationTime).TotalSeconds + client.SlidingRefreshTokenLifetime); + newRefreshToken.ShouldNotBeNull(); + newRefreshToken.Lifetime.ShouldBe((int)(now - newRefreshToken.CreationTime).TotalSeconds + client.SlidingRefreshTokenLifetime); } [Fact] @@ -191,12 +189,12 @@ public async Task UpdateRefreshToken_lifetime_exceeds_absolute_should_be_absolut var refreshToken = await _store.GetRefreshTokenAsync(handle); var newHandle = await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client }); - newHandle.Should().NotBeNull().And.Be(handle); + newHandle.ShouldBe(handle); var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle); - newRefreshToken.Should().NotBeNull(); - newRefreshToken.Lifetime.Should().Be(client.AbsoluteRefreshTokenLifetime); + newRefreshToken.ShouldNotBeNull(); + newRefreshToken.Lifetime.ShouldBe(client.AbsoluteRefreshTokenLifetime); } [Fact] @@ -222,12 +220,12 @@ public async Task UpdateRefreshToken_sliding_with_zero_absolute_should_update_li var refreshToken = await _store.GetRefreshTokenAsync(handle); var newHandle = await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client }); - newHandle.Should().NotBeNull().And.Be(handle); + newHandle.ShouldBe(handle); var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle); - newRefreshToken.Should().NotBeNull(); - newRefreshToken.Lifetime.Should().Be((int)(now - newRefreshToken.CreationTime).TotalSeconds + client.SlidingRefreshTokenLifetime); + newRefreshToken.ShouldNotBeNull(); + newRefreshToken.Lifetime.ShouldBe((int)(now - newRefreshToken.CreationTime).TotalSeconds + client.SlidingRefreshTokenLifetime); } [Fact] @@ -255,12 +253,12 @@ public async Task UpdateRefreshToken_for_onetime_and_sliding_with_zero_absolute_ var refreshToken = await _store.GetRefreshTokenAsync(handle); var newHandle = await _subject.UpdateRefreshTokenAsync(new RefreshTokenUpdateRequest { Handle = handle, RefreshToken = refreshToken, Client = client }); - newHandle.Should().NotBeNull().And.NotBe(handle); + newHandle.ShouldNotBe(handle); var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle); - newRefreshToken.Should().NotBeNull(); - newRefreshToken.Lifetime.Should().Be((int)(now - newRefreshToken.CreationTime).TotalSeconds + client.SlidingRefreshTokenLifetime); + newRefreshToken.ShouldNotBeNull(); + newRefreshToken.Lifetime.ShouldBe((int)(now - newRefreshToken.CreationTime).TotalSeconds + client.SlidingRefreshTokenLifetime); } [Fact] @@ -291,11 +289,11 @@ public async Task UpdateRefreshToken_one_time_use_with_consume_on_use_should_con var oldToken = await _store.GetRefreshTokenAsync(handle); var newToken = await _store.GetRefreshTokenAsync(newHandle); - oldToken.ConsumedTime.Should().Be(now); - newToken.ConsumedTime.Should().BeNull(); + oldToken.ConsumedTime.ShouldBe(now); + newToken.ConsumedTime.ShouldBeNull(); - newToken.CreationTime.Should().Be(oldToken.CreationTime); - newToken.Lifetime.Should().Be(oldToken.Lifetime); + newToken.CreationTime.ShouldBe(oldToken.CreationTime); + newToken.Lifetime.ShouldBe(oldToken.Lifetime); } [Fact] @@ -326,11 +324,11 @@ public async Task UpdateRefreshToken_one_time_use_with_delete_should_delete_on_u var oldToken = await _store.GetRefreshTokenAsync(handle); var newToken = await _store.GetRefreshTokenAsync(newHandle); - oldToken.Should().BeNull(); - newToken.ConsumedTime.Should().BeNull(); + oldToken.ShouldBeNull(); + newToken.ConsumedTime.ShouldBeNull(); - newToken.CreationTime.Should().Be(refreshToken.CreationTime); - newToken.Lifetime.Should().Be(refreshToken.Lifetime); + newToken.CreationTime.ShouldBe(refreshToken.CreationTime); + newToken.Lifetime.ShouldBe(refreshToken.Lifetime); } [Fact] @@ -344,7 +342,7 @@ public async Task ValidateRefreshToken_invalid_token_should_fail() var result = await _subject.ValidateRefreshTokenAsync("invalid", client); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); } [Fact] @@ -371,7 +369,7 @@ public async Task ValidateRefreshToken_client_without_allow_offline_access_shoul var result = await _subject.ValidateRefreshTokenAsync(handle, client); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); } [Fact] @@ -399,7 +397,7 @@ public async Task ValidateRefreshToken_invalid_client_binding_should_fail() var result = await _subject.ValidateRefreshTokenAsync(handle, client); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); } [Fact] @@ -427,7 +425,7 @@ public async Task ValidateRefreshToken_expired_token_should_fail() var result = await _subject.ValidateRefreshTokenAsync(handle, client); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); } [Fact] @@ -456,7 +454,7 @@ public async Task ValidateRefreshToken_consumed_token_should_fail() var result = await _subject.ValidateRefreshTokenAsync(handle, client); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); } [Fact] @@ -484,7 +482,7 @@ public async Task ValidateRefreshToken_valid_token_should_succeed() var result = await _subject.ValidateRefreshTokenAsync(handle, client); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -513,6 +511,6 @@ public async Task ValidateRefreshToken_valid_token_should_accept_v5_token() var result = await _subject.ValidateRefreshTokenAsync("key", client); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultTokenServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultTokenServiceTests.cs index c3bf3502b..507492db1 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultTokenServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultTokenServiceTests.cs @@ -8,7 +8,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using Microsoft.AspNetCore.Http; @@ -76,8 +76,8 @@ public async Task CreateAccessTokenAsync_should_include_aud_for_each_ApiResource var result = await _subject.CreateAccessTokenAsync(request); - result.Audiences.Count.Should().Be(3); - result.Audiences.Should().BeEquivalentTo(new[] { "api1", "api2", "api3" }); + result.Audiences.Count.ShouldBe(3); + result.Audiences.ShouldBeEquivalentTo(new[] { "api1", "api2", "api3" }); } [Fact] @@ -111,7 +111,7 @@ public async Task CreateAccessTokenAsync_when_no_apiresources_should_not_include var result = await _subject.CreateAccessTokenAsync(request); - result.Audiences.Count.Should().Be(0); + result.Audiences.Count.ShouldBe(0); } [Fact] @@ -129,7 +129,7 @@ public async Task CreateAccessTokenAsync_when_no_session_should_not_include_sid( var result = await _subject.CreateAccessTokenAsync(request); - result.Claims.SingleOrDefault(x => x.Type == JwtClaimTypes.SessionId).Should().BeNull(); + result.Claims.SingleOrDefault(x => x.Type == JwtClaimTypes.SessionId).ShouldBeNull(); } [Fact] @@ -147,7 +147,7 @@ public async Task CreateAccessTokenAsync_when_session_should_include_sid() var result = await _subject.CreateAccessTokenAsync(request); - result.Claims.SingleOrDefault(x => x.Type == JwtClaimTypes.SessionId).Value.Should().Be("123"); + result.Claims.SingleOrDefault(x => x.Type == JwtClaimTypes.SessionId).Value.ShouldBe("123"); } [Fact] @@ -162,28 +162,28 @@ public async Task CreateSecurityTokenAsync_should_include_jti_in_access_tokens() token.IncludeJwtId = false; token.Type = OidcConstants.TokenTypes.IdentityToken; var result = await _subject.CreateSecurityTokenAsync(token); - _mockTokenCreationService.Token.Claims.Should().NotContain(x => x.Type == "jti"); + _mockTokenCreationService.Token.Claims.ShouldNotContain(x => x.Type == "jti"); } { token.IncludeJwtId = false; token.Type = OidcConstants.TokenTypes.AccessToken; var result = await _subject.CreateSecurityTokenAsync(token); - _mockTokenCreationService.Token.Claims.Should().NotContain(x => x.Type == "jti"); + _mockTokenCreationService.Token.Claims.ShouldNotContain(x => x.Type == "jti"); } { token.IncludeJwtId = true; token.Type = OidcConstants.TokenTypes.IdentityToken; var result = await _subject.CreateSecurityTokenAsync(token); - _mockTokenCreationService.Token.Claims.Should().NotContain(x => x.Type == "jti"); + _mockTokenCreationService.Token.Claims.ShouldNotContain(x => x.Type == "jti"); } { token.IncludeJwtId = true; token.Type = OidcConstants.TokenTypes.AccessToken; var result = await _subject.CreateSecurityTokenAsync(token); - _mockTokenCreationService.Token.Claims.Should().Contain(x => x.Type == "jti"); + _mockTokenCreationService.Token.Claims.ShouldContain(x => x.Type == "jti"); } } [Fact] @@ -202,15 +202,15 @@ public async Task CreateSecurityTokenAsync_should_include_jti_access_tokens_for_ { var result = await _subject.CreateSecurityTokenAsync(token); - _mockTokenCreationService.Token.Claims.Should().NotContain(x => x.Type == "jti"); + _mockTokenCreationService.Token.Claims.ShouldNotContain(x => x.Type == "jti"); } { token.Claims.Add(new Claim("jti", "xoxo")); token.Type = OidcConstants.TokenTypes.AccessToken; var result = await _subject.CreateSecurityTokenAsync(token); - _mockTokenCreationService.Token.Claims.Should().Contain(x => x.Type == "jti"); - _mockTokenCreationService.Token.Claims.Single(x => x.Type == "jti").Value.Should().NotBe("xoxo"); + _mockTokenCreationService.Token.Claims.ShouldContain(x => x.Type == "jti"); + _mockTokenCreationService.Token.Claims.Single(x => x.Type == "jti").Value.ShouldNotBe("xoxo"); } } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultUserSessionTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultUserSessionTests.cs index 6b1f1b454..1fd5d0455 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultUserSessionTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DefaultUserSessionTests.cs @@ -11,7 +11,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Extensions; using Duende.IdentityServer.Services; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Microsoft.AspNetCore.Authentication; using Xunit; @@ -49,7 +49,7 @@ public async Task CreateSessionId_when_user_is_anonymous_should_generate_new_sid { await _subject.CreateSessionIdAsync(_user, _props); - _props.GetSessionId().Should().NotBeNull(); + _props.GetSessionId().ShouldNotBeNull(); } [Fact] @@ -62,8 +62,8 @@ public async Task CreateSessionId_should_allow_sid_to_be_indicated_in_properties newProps.SetSessionId("999"); await _subject.CreateSessionIdAsync(_user, newProps); - newProps.GetSessionId().Should().NotBeNull(); - newProps.GetSessionId().Should().Be("999"); + newProps.GetSessionId().ShouldNotBeNull(); + newProps.GetSessionId().ShouldBe("999"); } [Fact] @@ -71,12 +71,12 @@ public async Task CreateSessionId_when_current_props_does_not_contain_key_should { _mockAuthenticationHandler.Result = AuthenticateResult.Success(new AuthenticationTicket(_user, _props, "scheme")); - _props.GetSessionId().Should().BeNull(); + _props.GetSessionId().ShouldBeNull(); var newProps = new AuthenticationProperties(); await _subject.CreateSessionIdAsync(_user, newProps); - newProps.GetSessionId().Should().NotBeNull(); + newProps.GetSessionId().ShouldNotBeNull(); } [Fact] @@ -88,8 +88,8 @@ public async Task CreateSessionId_when_user_is_authenticated_but_different_sub_s var newProps = new AuthenticationProperties(); await _subject.CreateSessionIdAsync(new IdentityServerUser("alice").CreatePrincipal(), newProps); - newProps.GetSessionId().Should().NotBeNull(); - newProps.GetSessionId().Should().NotBe("999"); + newProps.GetSessionId().ShouldNotBeNull(); + newProps.GetSessionId().ShouldNotBe("999"); } [Fact] @@ -101,8 +101,8 @@ public async Task CreateSessionId_when_user_is_authenticated_and_same_sub_should var newProps = new AuthenticationProperties(); await _subject.CreateSessionIdAsync(_user, newProps); - newProps.GetSessionId().Should().NotBeNull(); - newProps.GetSessionId().Should().Be("999"); + newProps.GetSessionId().ShouldNotBeNull(); + newProps.GetSessionId().ShouldBe("999"); } [Fact] @@ -116,7 +116,7 @@ public async Task CreateSessionId_should_issue_session_id_cookie() _mockHttpContext.HttpContext.Response.Headers.Clear(); var cookie = cookieContainer.GetCookies(new Uri("http://server")).FirstOrDefault(x => x.Name == _options.Authentication.CheckSessionCookieName); - cookie.Value.Should().Be(_props.GetSessionId()); + cookie.Value.ShouldBe(_props.GetSessionId()); } [Fact] @@ -133,7 +133,7 @@ public async Task EnsureSessionIdCookieAsync_should_add_cookie() _mockHttpContext.HttpContext.Response.Headers.Clear(); var cookie = cookieContainer.GetCookies(new Uri("http://server")).FirstOrDefault(x => x.Name == _options.Authentication.CheckSessionCookieName); - cookie.Value.Should().Be("999"); + cookie.Value.ShouldBe("999"); } [Fact] @@ -147,7 +147,7 @@ public async Task EnsureSessionIdCookieAsync_should_not_add_cookie_if_no_sid() _mockHttpContext.HttpContext.Response.Headers.Clear(); var cookie = cookieContainer.GetCookies(new Uri("http://server")).FirstOrDefault(x => x.Name == _options.Authentication.CheckSessionCookieName); - cookie.Should().BeNull(); + cookie.ShouldBeNull(); } [Fact] @@ -171,8 +171,8 @@ public async Task RemoveSessionIdCookie_should_remove_cookie() cookies = _mockHttpContext.HttpContext.Response.Headers.Where(x => x.Key.Equals("Set-Cookie", StringComparison.OrdinalIgnoreCase)).Select(x => x.Value); cookieContainer.SetCookies(new Uri("http://server"), string.Join(',', cookies)); - var query = cookieContainer.GetCookies(new Uri("http://server")).Where(x => x.Name == _options.Authentication.CheckSessionCookieName); - query.Count().Should().Be(0); + var query = cookieContainer.GetCookies(new Uri("http://server")).Cast().Where(x => x.Name == _options.Authentication.CheckSessionCookieName); + query.Count().ShouldBe(0); } [Fact] @@ -182,14 +182,14 @@ public async Task GetCurrentSessionIdAsync_when_user_is_authenticated_should_ret _mockAuthenticationHandler.Result = AuthenticateResult.Success(new AuthenticationTicket(_user, _props, "scheme")); var sid = await _subject.GetSessionIdAsync(); - sid.Should().Be("999"); + sid.ShouldBe("999"); } [Fact] public async Task GetCurrentSessionIdAsync_when_user_is_anonymous_should_return_null() { var sid = await _subject.GetSessionIdAsync(); - sid.Should().BeNull(); + sid.ShouldBeNull(); } [Fact] @@ -197,9 +197,9 @@ public async Task adding_client_should_set_item_in_cookie_properties() { _mockAuthenticationHandler.Result = AuthenticateResult.Success(new AuthenticationTicket(_user, _props, "scheme")); - _props.Items.Count.Should().Be(0); + _props.Items.Count.ShouldBe(0); await _subject.AddClientIdAsync("client"); - _props.Items.Count.Should().Be(1); + _props.Items.Count.ShouldBe(1); } [Fact] @@ -208,7 +208,7 @@ public async Task when_handler_successful_GetIdentityServerUserAsync_should_shou _mockAuthenticationHandler.Result = AuthenticateResult.Success(new AuthenticationTicket(_user, _props, "scheme")); var user = await _subject.GetUserAsync(); - user.GetSubjectId().Should().Be("123"); + user.GetSubjectId().ShouldBe("123"); } [Fact] @@ -218,14 +218,14 @@ public async Task when_handler_successful_and_identity_is_anonymous_GetIdentityS _mockAuthenticationHandler.Result = AuthenticateResult.Success(new AuthenticationTicket(cp, _props, "scheme")); var user = await _subject.GetUserAsync(); - user.Should().BeNull(); + user.ShouldBeNull(); } [Fact] public async Task when_anonymous_GetIdentityServerUserAsync_should_return_null() { var user = await _subject.GetUserAsync(); - user.Should().BeNull(); + user.ShouldBeNull(); } [Fact] @@ -238,8 +238,8 @@ public async Task corrupt_properties_entry_should_clear_entry() _props.Items[item.Key] = "junk"; var clients = await _subject.GetClientListAsync(); - clients.Should().BeEmpty(); - _props.Items.Count.Should().Be(0); + clients.ShouldBeEmpty(); + _props.Items.Count.ShouldBe(0); } [Fact] @@ -249,7 +249,7 @@ public async Task adding_client_should_be_able_to_read_client() await _subject.AddClientIdAsync("client"); var clients = await _subject.GetClientListAsync(); - clients.Should().Contain(new string[] { "client" }); + clients.ShouldBe(["client"]); } [Fact] @@ -260,7 +260,7 @@ public async Task adding_clients_should_be_able_to_read_clients() await _subject.AddClientIdAsync("client1"); await _subject.AddClientIdAsync("client2"); var clients = await _subject.GetClientListAsync(); - clients.Should().Contain(new string[] { "client2", "client1" }); + clients.ShouldBe(["client2", "client1"]); } [Fact] @@ -274,7 +274,7 @@ public async Task adding_existing_client_should_not_add_new_client() var clients = await _subject.GetClientListAsync(); - _props.Items.Count.Should().Be(1); - clients.Should().BeEquivalentTo([clientId]); + _props.Items.Count.ShouldBe(1); + clients.ShouldBe([clientId]); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/DistributedDeviceFlowThrottlingServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/DistributedDeviceFlowThrottlingServiceTests.cs index aa8620e80..f4d332bbc 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/DistributedDeviceFlowThrottlingServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/DistributedDeviceFlowThrottlingServiceTests.cs @@ -10,7 +10,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Microsoft.Extensions.Caching.Distributed; using Xunit; @@ -46,7 +46,7 @@ public async Task First_Poll() var result = await service.ShouldSlowDown(handle, deviceCode); - result.Should().BeFalse(); + result.ShouldBeFalse(); CheckCacheEntry(handle); } @@ -61,7 +61,7 @@ public async Task Second_Poll_Too_Fast() var result = await service.ShouldSlowDown(handle, deviceCode); - result.Should().BeTrue(); + result.ShouldBeTrue(); CheckCacheEntry(handle); } @@ -77,7 +77,7 @@ public async Task Second_Poll_After_Interval() var result = await service.ShouldSlowDown(handle, deviceCode); - result.Should().BeFalse(); + result.ShouldBeFalse(); CheckCacheEntry(handle); } @@ -95,21 +95,21 @@ public async Task Expired_Device_Code_Should_Not_Have_Expiry_in_Past() var result = await service.ShouldSlowDown(handle, deviceCode); - result.Should().BeFalse(); + result.ShouldBeFalse(); - cache.Items.TryGetValue(CacheKey + handle, out var values).Should().BeTrue(); - values?.Item2.AbsoluteExpiration.Should().BeOnOrAfter(testDate); + cache.Items.TryGetValue(CacheKey + handle, out var values).ShouldBeTrue(); + values?.Item2.AbsoluteExpiration.Value.ShouldBeGreaterThanOrEqualTo(testDate); } private void CheckCacheEntry(string handle) { - cache.Items.TryGetValue(CacheKey + handle, out var values).Should().BeTrue(); + cache.Items.TryGetValue(CacheKey + handle, out var values).ShouldBeTrue(); var dateTimeAsString = Encoding.UTF8.GetString(values?.Item1); var dateTime = DateTime.Parse(dateTimeAsString).ToUniversalTime(); - dateTime.Should().Be(testDate); + dateTime.ShouldBe(testDate); - values?.Item2.AbsoluteExpiration.Should().BeCloseTo(testDate.AddSeconds(deviceCode.Lifetime), TimeSpan.FromMicroseconds(1)); + values?.Item2.AbsoluteExpiration.Value.ShouldBeCloseTo(testDate.AddSeconds(deviceCode.Lifetime), TimeSpan.FromMicroseconds(1)); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/InMemoryKeyStoreCacheTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/InMemoryKeyStoreCacheTests.cs index 37e78b204..611e6fe6c 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/InMemoryKeyStoreCacheTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/InMemoryKeyStoreCacheTests.cs @@ -5,7 +5,7 @@ using System; using System.Threading.Tasks; using Duende.IdentityServer.Services.KeyManagement; -using FluentAssertions; +using Shouldly; using Xunit; namespace UnitTests.Services.Default.KeyManagement; @@ -32,19 +32,19 @@ public async Task GetKeysAsync_within_expiration_should_return_keys() await _subject.StoreKeysAsync(keys, TimeSpan.FromMinutes(1)); var result = await _subject.GetKeysAsync(); - result.Should().BeSameAs(keys); + result.ShouldBeSameAs(keys); _mockClock.UtcNow = now.Subtract(TimeSpan.FromDays(1)); result = await _subject.GetKeysAsync(); - result.Should().BeSameAs(keys); + result.ShouldBeSameAs(keys); _mockClock.UtcNow = now.Add(TimeSpan.FromSeconds(59)); result = await _subject.GetKeysAsync(); - result.Should().BeSameAs(keys); + result.ShouldBeSameAs(keys); _mockClock.UtcNow = now.Add(TimeSpan.FromMinutes(1)); result = await _subject.GetKeysAsync(); - result.Should().BeSameAs(keys); + result.ShouldBeSameAs(keys); } [Fact] @@ -60,6 +60,6 @@ public async Task GetKeysAsync_past_expiration_should_return_no_keys() _mockClock.UtcNow = now.Add(TimeSpan.FromSeconds(61)); var result = await _subject.GetKeysAsync(); - result.Should().BeNullOrEmpty(); + result.ShouldBeEmpty(); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/KeyManagerOptionsTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/KeyManagerOptionsTests.cs index 5b71ee9f4..fc0976865 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/KeyManagerOptionsTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/KeyManagerOptionsTests.cs @@ -4,7 +4,7 @@ using System; using Duende.IdentityServer.Configuration; -using FluentAssertions; +using Shouldly; using Xunit; namespace UnitTests.Services.Default.KeyManagement; @@ -20,7 +20,7 @@ public void InitializationSynchronizationDelay_should_be_greater_than_or_equal_t }; Action a = () => subject.Validate(); - a.Should().Throw(); + a.ShouldThrow(); } [Fact] @@ -32,7 +32,7 @@ public void InitializationDuration_should_be_greater_than_or_equal_to_zero() }; Action a = () => subject.Validate(); - a.Should().Throw(); + a.ShouldThrow(); } [Fact] @@ -44,7 +44,7 @@ public void InitializationKeyCacheDuration_should_be_greater_than_or_equal_to_ze }; Action a = () => subject.Validate(); - a.Should().Throw(); + a.ShouldThrow(); } [Fact] @@ -56,7 +56,7 @@ public void keycacheduration_should_be_greater_than_or_equal_to_zero() }; Action a = () => subject.Validate(); - a.Should().Throw(); + a.ShouldThrow(); } [Fact] @@ -71,7 +71,7 @@ public void activation_should_be_greater_than_zero() }; Action a = () => subject.Validate(); - a.Should().Throw(); + a.ShouldThrow(); } { var subject = new KeyManagementOptions @@ -82,7 +82,7 @@ public void activation_should_be_greater_than_zero() }; Action a = () => subject.Validate(); - a.Should().Throw(); + a.ShouldThrow(); } } @@ -98,7 +98,7 @@ public void expiration_should_be_greater_than_zero() }; Action a = () => subject.Validate(); - a.Should().Throw(); + a.ShouldThrow(); } { var subject = new KeyManagementOptions @@ -109,7 +109,7 @@ public void expiration_should_be_greater_than_zero() }; Action a = () => subject.Validate(); - a.Should().Throw(); + a.ShouldThrow(); } } @@ -125,7 +125,7 @@ public void retirement_should_be_greater_than_zero() }; Action a = () => subject.Validate(); - a.Should().Throw(); + a.ShouldThrow(); } { var subject = new KeyManagementOptions @@ -136,7 +136,7 @@ public void retirement_should_be_greater_than_zero() }; Action a = () => subject.Validate(); - a.Should().Throw(); + a.ShouldThrow(); } } @@ -152,7 +152,7 @@ public void expiration_should_be_longer_than_activation_delay() }; Action a = () => subject.Validate(); - a.Should().Throw(); + a.ShouldThrow(); } { @@ -164,7 +164,7 @@ public void expiration_should_be_longer_than_activation_delay() }; Action a = () => subject.Validate(); - a.Should().Throw(); + a.ShouldThrow(); } { @@ -176,7 +176,7 @@ public void expiration_should_be_longer_than_activation_delay() }; Action a = () => subject.Validate(); - a.Should().NotThrow(); + a.ShouldNotThrow(); } } @@ -192,7 +192,7 @@ public void retirement_should_be_longer_than_expiration() }; Action a = () => subject.Validate(); - a.Should().Throw(); + a.ShouldThrow(); } { @@ -204,7 +204,7 @@ public void retirement_should_be_longer_than_expiration() }; Action a = () => subject.Validate(); - a.Should().Throw(); + a.ShouldThrow(); } { @@ -216,7 +216,7 @@ public void retirement_should_be_longer_than_expiration() }; Action a = () => subject.Validate(); - a.Should().NotThrow(); + a.ShouldNotThrow(); } } } diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/KeyManagerTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/KeyManagerTests.cs index 3effbe6fb..58ae2c7a8 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/KeyManagerTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/KeyManagement/KeyManagerTests.cs @@ -12,7 +12,7 @@ using Duende.IdentityServer.Internal; using Duende.IdentityServer.Models; using Duende.IdentityServer.Services.KeyManagement; -using FluentAssertions; +using Shouldly; using Microsoft.Extensions.Logging; using UnitTests.Validation.Setup; using Xunit; @@ -111,7 +111,7 @@ public void ctor_should_validate_options() new LoggerFactory().CreateLogger(), new TestIssuerNameService()); }; - a.Should().Throw(); + a.ShouldThrow(); } // GetCurrentKeysAsync @@ -123,7 +123,7 @@ public async Task GetCurrentKeysAsync_should_return_key() var keys = await _subject.GetCurrentKeysAsync(); var key = keys.Single(); - key.Id.Should().Be(id); + key.Id.ShouldBe(id); } // GetAllKeysInternalAsync @@ -136,7 +136,7 @@ public async Task GetAllKeysInternalAsync_when_valid_key_exists_should_use_key() var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); var key = signgingKeys.Single(); - key.Id.Should().Be(id); + key.Id.ShouldBe(id); } [Fact] @@ -148,9 +148,9 @@ public async Task GetAllKeysInternalAsync_when_recently_created_key_exists_shoul var key = signgingKeys.Single(); - key.Should().NotBeNull(); - _mockKeyStore.Keys.Count.Should().Be(1); - _mockKeyStore.Keys.Single().Id.Should().Be(key.Id); + key.ShouldNotBeNull(); + _mockKeyStore.Keys.Count.ShouldBe(1); + _mockKeyStore.Keys.Single().Id.ShouldBe(key.Id); } [Fact] @@ -162,9 +162,9 @@ public async Task GetAllKeysInternalAsync_when_only_one_key_created_in_future_sh var key = signgingKeys.Single(); - key.Should().NotBeNull(); - _mockKeyStore.Keys.Count.Should().Be(1); - _mockKeyStore.Keys.Single().Id.Should().Be(key.Id); + key.ShouldNotBeNull(); + _mockKeyStore.Keys.Count.ShouldBe(1); + _mockKeyStore.Keys.Single().Id.ShouldBe(key.Id); } [Fact] @@ -174,9 +174,9 @@ public async Task GetAllKeysInternalAsync_when_no_keys_should_create_key() var key = signgingKeys.Single(); - key.Should().NotBeNull(); - _mockKeyStore.Keys.Count.Should().Be(1); - _mockKeyStore.Keys.Single().Id.Should().Be(key.Id); + key.ShouldNotBeNull(); + _mockKeyStore.Keys.Count.ShouldBe(1); + _mockKeyStore.Keys.Single().Id.ShouldBe(key.Id); } [Fact] @@ -186,7 +186,7 @@ public async Task GetAllKeysInternalAsync_when_null_keys_should_create_key() var (keys, key) = await _subject.GetAllKeysInternalAsync(); - keys.Should().NotBeEmpty(); + keys.ShouldNotBeEmpty(); } [Fact] @@ -198,9 +198,9 @@ public async Task GetAllKeysInternalAsync_when_all_keys_are_expired_should_creat var key = signgingKeys.Single(); - key.Should().NotBeNull(); - _mockKeyStore.Keys.Count.Should().Be(2); - key.Id.Should().NotBe(id); + key.ShouldNotBeNull(); + _mockKeyStore.Keys.Count.ShouldBe(2); + key.Id.ShouldNotBe(id); } [Fact] @@ -213,8 +213,8 @@ public async Task GetAllKeysInternalAsync_when_all_keys_are_expired_should_reque var key = signgingKeys.Single(); - key.Should().NotBeNull(); - key.Id.Should().Be(id2); + key.ShouldNotBeNull(); + key.Id.ShouldBe(id2); } [Fact] @@ -229,9 +229,9 @@ public async Task GetAllKeysInternalAsync_should_use_oldest_active_key() var key = signgingKeys.Single(); - key.Should().NotBeNull(); - _mockKeyStore.Keys.Count.Should().Be(4); - key.Id.Should().Be(key1); + key.ShouldNotBeNull(); + _mockKeyStore.Keys.Count.ShouldBe(4); + key.Id.ShouldBe(key1); } [Fact] @@ -244,9 +244,9 @@ public async Task GetAllKeysInternalAsync_should_ignore_keys_not_yet_activated() var key = signgingKeys.Single(); - key.Should().NotBeNull(); - _mockKeyStore.Keys.Count.Should().Be(2); - key.Id.Should().Be(key1); + key.ShouldNotBeNull(); + _mockKeyStore.Keys.Count.ShouldBe(2); + key.Id.ShouldBe(key1); } [Fact] @@ -260,7 +260,7 @@ public async Task GetAllKeysInternalAsync_when_cache_empty_should_return_non_ret var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); - allKeys.Select(x => x.Id).Should().BeEquivalentTo(new[] { key1, key2, key3, key4 }); + allKeys.Select(x => x.Id).ShouldBeEquivalentTo(new[] { key1, key2, key3, key4 }); } [Fact] @@ -276,7 +276,7 @@ public async Task GetAllKeysInternalAsync_when_cache_null_should_return_non_reti var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); - allKeys.Select(x => x.Id).Should().BeEquivalentTo(new[] { key1, key2, key3, key4 }); + allKeys.Select(x => x.Id).ShouldBeEquivalentTo(new[] { key1, key2, key3, key4 }); } [Fact] @@ -286,11 +286,11 @@ public async Task GetAllKeysInternalAsync_when_cache_empty_should_update_the_cac var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); - allKeys.Count().Should().Be(1); - allKeys.Single().Id.Should().Be(key); - _mockKeyStoreCache.StoreKeysAsyncWasCalled.Should().BeTrue(); - _mockKeyStoreCache.Cache.Count.Should().Be(1); - _mockKeyStoreCache.Cache.Single().Id.Should().Be(key); + allKeys.Count().ShouldBe(1); + allKeys.Single().Id.ShouldBe(key); + _mockKeyStoreCache.StoreKeysAsyncWasCalled.ShouldBeTrue(); + _mockKeyStoreCache.Cache.Count.ShouldBe(1); + _mockKeyStoreCache.Cache.Single().Id.ShouldBe(key); } [Fact] @@ -304,9 +304,9 @@ public async Task GetAllKeysInternalAsync_should_use_the_cache() var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); - allKeys.Count().Should().Be(1); - allKeys.Single().Id.Should().Be(key.Id); - _mockKeyStore.LoadKeysAsyncWasCalled.Should().BeFalse(); + allKeys.Count().ShouldBe(1); + allKeys.Single().Id.ShouldBe(key.Id); + _mockKeyStore.LoadKeysAsyncWasCalled.ShouldBeFalse(); } [Fact] @@ -318,9 +318,9 @@ public async Task GetAllKeysInternalAsync_when_key_rotation_is_needed_should_cre var key = signgingKeys.Single(); - key.Should().NotBeNull(); - key.Id.Should().Be(key1); - _mockKeyStore.Keys.Count.Should().Be(2); + key.ShouldNotBeNull(); + key.Id.ShouldBe(key1); + _mockKeyStore.Keys.Count.ShouldBe(2); } [Fact] @@ -331,7 +331,7 @@ public async Task GetAllKeysInternalAsync_when_key_rotation_is_needed_for_cached var (allKeys, signgingKeys) = await _subject.GetAllKeysInternalAsync(); - _mockKeyStore.Keys.Count.Should().Be(2); + _mockKeyStore.Keys.Count.ShouldBe(2); } [Fact] @@ -343,8 +343,8 @@ public async Task GetAllKeysInternalAsync_when_key_rotation_is_not_needed_should var key = signgingKeys.Single(); - key.Id.Should().Be(key1); - _mockKeyStore.Keys.Count.Should().Be(1); + key.Id.ShouldBe(key1); + _mockKeyStore.Keys.Count.ShouldBe(1); } // GetKeysFromCacheAsync @@ -356,9 +356,9 @@ public async Task GetKeysFromCacheAsync_should_use_cache() var keys = await _subject.GetAllKeysFromCacheAsync(); - keys.Count().Should().Be(1); - keys.Single().Id.Should().Be(id); - _mockKeyStore.LoadKeysAsyncWasCalled.Should().BeFalse(); + keys.Count().ShouldBe(1); + keys.Single().Id.ShouldBe(id); + _mockKeyStore.LoadKeysAsyncWasCalled.ShouldBeFalse(); } // AreAllKeysWithinInitializationDuration @@ -373,7 +373,7 @@ public void AreAllKeysWithinInitializationDuration_should_ignore_retired_and_exp var result = _subject.AreAllKeysWithinInitializationDuration(new[] { key1, key2, key3 }); - result.Should().BeTrue(); + result.ShouldBeTrue(); } { var key1 = CreateKey(_options.KeyManagement.KeyRetirementAge.Add(TimeSpan.FromSeconds(1))); @@ -382,7 +382,7 @@ public void AreAllKeysWithinInitializationDuration_should_ignore_retired_and_exp var result = _subject.AreAllKeysWithinInitializationDuration(new[] { key1, key2, key3 }); - result.Should().BeTrue(); + result.ShouldBeTrue(); } } @@ -394,21 +394,21 @@ public void AreAllKeysWithinInitializationDuration_for_new_keys_should_return_tr var result = _subject.AreAllKeysWithinInitializationDuration(new[] { key1 }); - result.Should().BeTrue(); + result.ShouldBeTrue(); } { var key1 = CreateKey(_options.KeyManagement.InitializationDuration); var result = _subject.AreAllKeysWithinInitializationDuration(new[] { key1 }); - result.Should().BeTrue(); + result.ShouldBeTrue(); } { var key1 = CreateKey(); var result = _subject.AreAllKeysWithinInitializationDuration(new[] { key1 }); - result.Should().BeTrue(); + result.ShouldBeTrue(); } { var key1 = CreateKey(_options.KeyManagement.InitializationDuration); @@ -417,7 +417,7 @@ public void AreAllKeysWithinInitializationDuration_for_new_keys_should_return_tr var result = _subject.AreAllKeysWithinInitializationDuration(new[] { key1, key2, key3 }); - result.Should().BeTrue(); + result.ShouldBeTrue(); } } @@ -429,7 +429,7 @@ public void AreAllKeysWithinInitializationDuration_for_older_keys_should_return_ var result = _subject.AreAllKeysWithinInitializationDuration(new[] { key0 }); - result.Should().BeFalse(); + result.ShouldBeFalse(); } { var key0 = CreateKey(_options.KeyManagement.InitializationDuration.Add(TimeSpan.FromSeconds(1))); @@ -437,7 +437,7 @@ public void AreAllKeysWithinInitializationDuration_for_older_keys_should_return_ var result = _subject.AreAllKeysWithinInitializationDuration(new[] { key0, key1 }); - result.Should().BeFalse(); + result.ShouldBeFalse(); } { var key0 = CreateKey(_options.KeyManagement.InitializationDuration.Add(TimeSpan.FromSeconds(1))); @@ -445,7 +445,7 @@ public void AreAllKeysWithinInitializationDuration_for_older_keys_should_return_ var result = _subject.AreAllKeysWithinInitializationDuration(new[] { key0, key1 }); - result.Should().BeFalse(); + result.ShouldBeFalse(); } { var key0 = CreateKey(_options.KeyManagement.InitializationDuration.Add(TimeSpan.FromSeconds(1))); @@ -453,7 +453,7 @@ public void AreAllKeysWithinInitializationDuration_for_older_keys_should_return_ var result = _subject.AreAllKeysWithinInitializationDuration(new[] { key0, key1 }); - result.Should().BeFalse(); + result.ShouldBeFalse(); } { var key0 = CreateKey(_options.KeyManagement.InitializationDuration.Add(TimeSpan.FromSeconds(1))); @@ -463,7 +463,7 @@ public void AreAllKeysWithinInitializationDuration_for_older_keys_should_return_ var result = _subject.AreAllKeysWithinInitializationDuration(new[] { key0, key1, key2, key3 }); - result.Should().BeFalse(); + result.ShouldBeFalse(); } } @@ -481,7 +481,7 @@ public async Task FilterRetiredKeys_should_filter_retired_keys() var result = await _subject.FilterAndDeleteRetiredKeysAsync(new[] { key1, key2, key3, key4, key5, key6 }); - result.Select(x => x.Id).Should().BeEquivalentTo(new[] { key3.Id, key4.Id, key5.Id, key6.Id }); + result.Select(x => x.Id).ShouldBeEquivalentTo(new[] { key3.Id, key4.Id, key5.Id, key6.Id }); } [Fact] @@ -498,8 +498,8 @@ public async Task FilterRetiredKeys_should_delete_from_database() var keys = await _subject.GetAllKeysAsync(); - _mockKeyStore.DeleteWasCalled.Should().BeTrue(); - _mockKeyStore.Keys.Select(x => x.Id).Should().BeEquivalentTo(new[] { key3, key4, key5, key6 }); + _mockKeyStore.DeleteWasCalled.ShouldBeTrue(); + _mockKeyStore.Keys.Select(x => x.Id).ShouldBeEquivalentTo(new[] { key3, key4, key5, key6 }); } [Fact] @@ -516,8 +516,8 @@ public async Task FilterRetiredKeys_when_delete_disabled_should_not_delete_from_ var keys = await _subject.GetAllKeysAsync(); - _mockKeyStore.DeleteWasCalled.Should().BeFalse(); - _mockKeyStore.Keys.Select(x => x.Id).Should().BeEquivalentTo(new[] { key1, key2, key3, key4, key5, key6 }); + _mockKeyStore.DeleteWasCalled.ShouldBeFalse(); + _mockKeyStore.Keys.Select(x => x.Id).ShouldBeEquivalentTo(new[] { key1, key2, key3, key4, key5, key6 }); } // FilterExpiredKeys @@ -534,7 +534,7 @@ public void FilterExpiredKeys_should_filter_expired_keys() var result = _subject.FilterExpiredKeys(new[] { key1, key2, key3, key4, key5, key6 }); - result.Select(x => x.Id).Should().BeEquivalentTo(new[] { key3.Id, key4.Id, key5.Id, key6.Id }); + result.Select(x => x.Id).ShouldBeEquivalentTo(new[] { key3.Id, key4.Id, key5.Id, key6.Id }); } // CacheKeysAsync @@ -545,13 +545,13 @@ public async Task CacheKeysAsync_should_not_store_empty_keys() { await _subject.CacheKeysAsync(null); - _mockKeyStoreCache.StoreKeysAsyncWasCalled.Should().BeFalse(); + _mockKeyStoreCache.StoreKeysAsyncWasCalled.ShouldBeFalse(); } { await _subject.CacheKeysAsync(new RsaKeyContainer[0]); - _mockKeyStoreCache.StoreKeysAsyncWasCalled.Should().BeFalse(); + _mockKeyStoreCache.StoreKeysAsyncWasCalled.ShouldBeFalse(); } } @@ -563,10 +563,10 @@ public async Task CacheKeysAsync_should_store_keys_in_cache_with_normal_cache_du await _subject.CacheKeysAsync(new[] { key1, key2 }); - _mockKeyStoreCache.StoreKeysAsyncWasCalled.Should().BeTrue(); - _mockKeyStoreCache.StoreKeysAsyncDuration.Should().Be(_options.KeyManagement.KeyCacheDuration); + _mockKeyStoreCache.StoreKeysAsyncWasCalled.ShouldBeTrue(); + _mockKeyStoreCache.StoreKeysAsyncDuration.ShouldBe(_options.KeyManagement.KeyCacheDuration); - _mockKeyStoreCache.Cache.Select(x => x.Id).Should().BeEquivalentTo(new[] { key1.Id, key2.Id }); + _mockKeyStoreCache.Cache.Select(x => x.Id).ShouldBeEquivalentTo(new[] { key1.Id, key2.Id }); } [Fact] @@ -576,8 +576,8 @@ public async Task CacheKeysAsync_when_keys_are_new_should_use_initialization_dur await _subject.CacheKeysAsync(new[] { key1 }); - _mockKeyStoreCache.StoreKeysAsyncWasCalled.Should().BeTrue(); - _mockKeyStoreCache.StoreKeysAsyncDuration.Should().Be(_options.KeyManagement.InitializationKeyCacheDuration); + _mockKeyStoreCache.StoreKeysAsyncWasCalled.ShouldBeTrue(); + _mockKeyStoreCache.StoreKeysAsyncDuration.ShouldBe(_options.KeyManagement.InitializationKeyCacheDuration); } // GetKeysFromStoreAsync @@ -589,9 +589,9 @@ public async Task GetKeysFromStoreAsync_should_use_store_and_cache_keys() var keys = await _subject.GetAllKeysFromStoreAsync(); - keys.Should().NotBeNull(); - keys.Single().Id.Should().Be(key); - _mockKeyStoreCache.GetKeysAsyncWasCalled.Should().BeFalse(); + keys.ShouldNotBeNull(); + keys.Single().Id.ShouldBe(key); + _mockKeyStoreCache.GetKeysAsyncWasCalled.ShouldBeFalse(); } [Fact] @@ -605,7 +605,7 @@ public async Task GetKeysFromStoreAsync_should_filter_retired_keys() var keys = await _subject.GetAllKeysFromStoreAsync(); - keys.Select(x => x.Id).Should().BeEquivalentTo(new[] { key1, key2, key3, key4 }); + keys.Select(x => x.Id).ShouldBeEquivalentTo(new[] { key1, key2, key3, key4 }); } [Fact] @@ -619,11 +619,11 @@ public async Task GetKeysFromStoreAsync_should_filter_retired_keys_that_cannot_b var keys = await _subject.GetAllKeysFromStoreAsync(); - keys.Select(x => x.Id).Should().BeEquivalentTo(new[] { key1, key2, key3, key4 }); + keys.Select(x => x.Id).ShouldBeEquivalentTo(new[] { key1, key2, key3, key4 }); - _mockKeyStore.DeleteWasCalled.Should().BeTrue(); + _mockKeyStore.DeleteWasCalled.ShouldBeTrue(); var keysInStore = await _mockKeyStore.LoadKeysAsync(); - keysInStore.Select(x => x.Id).Should().BeEquivalentTo(new[] { key1, key2, key3, key4 }); + keysInStore.Select(x => x.Id).ShouldBeEquivalentTo(new[] { key1, key2, key3, key4 }); } [Fact] @@ -634,7 +634,7 @@ public async Task GetKeysFromStoreAsync_should_filter_null_keys() var keys = await _subject.GetAllKeysFromStoreAsync(); - keys.Select(x => x.Id).Should().BeEquivalentTo(new[] { key1 }); + keys.Select(x => x.Id).ShouldBeEquivalentTo(new[] { key1 }); } // CreateNewKeysAndAddToCacheAsync @@ -644,7 +644,7 @@ public async Task CreateNewKeyAndAddToCacheAsync_when_no_keys_should_store_and_r { var (allKeys, signingKeys) = await _subject.CreateNewKeysAndAddToCacheAsync(); var key = signingKeys.Single(); - _mockKeyStore.Keys.Single().Id.Should().Be(key.Id); + _mockKeyStore.Keys.Single().Id.ShouldBe(key.Id); } [Fact] @@ -655,10 +655,10 @@ public async Task CreateNewKeyAndAddToCacheAsync_when_existing_keys_should_store var (allKeys, signingKeys) = await _subject.CreateNewKeysAndAddToCacheAsync(); var key = signingKeys.Single(); - allKeys.Count().Should().Be(2); - _mockKeyStore.Keys.Count.Should().Be(2); + allKeys.Count().ShouldBe(2); + _mockKeyStore.Keys.Count.ShouldBe(2); - key.Id.Should().Be(key1); + key.Id.ShouldBe(key1); } [Fact] @@ -668,7 +668,7 @@ public async Task CreateNewKeyAndAddToCacheAsync_should_return_all_keys() var (allKeys, signingKeys) = await _subject.CreateNewKeysAndAddToCacheAsync(); - allKeys.Select(x => x.Id).Should().BeEquivalentTo(_mockKeyStore.Keys.Select(x => x.Id)); + allKeys.Select(x => x.Id).ShouldBeEquivalentTo(_mockKeyStore.Keys.Select(x => x.Id)); } [Fact] @@ -683,9 +683,9 @@ public async Task CreateNewKeyAndAddToCacheAsync_when_keys_are_new_should_delay_ var (allKeys, signingKeys) = await _subject.CreateNewKeysAndAddToCacheAsync(); sw.Stop(); - sw.Elapsed.Should().BeGreaterOrEqualTo(_options.KeyManagement.InitializationSynchronizationDelay); + sw.Elapsed.ShouldBeGreaterThanOrEqualTo(_options.KeyManagement.InitializationSynchronizationDelay); - allKeys.Select(x => x.Id).Should().BeEquivalentTo(_mockKeyStore.Keys.Select(x => x.Id)); + allKeys.Select(x => x.Id).ShouldBeEquivalentTo(_mockKeyStore.Keys.Select(x => x.Id)); } [Fact] @@ -700,9 +700,9 @@ public async Task CreateNewKeyAndAddToCacheAsync_when_keys_are_old_should_not_de var (allKeys, signingKeys) = await _subject.CreateNewKeysAndAddToCacheAsync(); sw.Stop(); - sw.Elapsed.Should().BeLessThan(_options.KeyManagement.InitializationSynchronizationDelay); + sw.Elapsed.ShouldBeLessThan(_options.KeyManagement.InitializationSynchronizationDelay); - allKeys.Select(x => x.Id).Should().BeEquivalentTo(_mockKeyStore.Keys.Select(x => x.Id)); + allKeys.Select(x => x.Id).ShouldBeEquivalentTo(_mockKeyStore.Keys.Select(x => x.Id)); } // GetCurrentSigningKey @@ -712,11 +712,11 @@ public void GetActiveSigningKey_for_no_keys_should_return_null() { { var key = _subject.GetAllCurrentSigningKeys(null); - key.Should().BeEmpty(); + key.ShouldBeEmpty(); } { var key = _subject.GetAllCurrentSigningKeys(new RsaKeyContainer[0]); - key.Should().BeEmpty(); + key.ShouldBeEmpty(); } } @@ -732,8 +732,8 @@ public void GetCurrentSigningKeyInternal_should_return_the_oldest_active_key() var key = _subject.GetCurrentSigningKeyInternal(new[] { key1, key2, key3, key4 }); - key.Should().NotBeNull(); - key.Id.Should().Be(key1.Id); + key.ShouldNotBeNull(); + key.Id.ShouldBe(key1.Id); } [Fact] @@ -746,15 +746,15 @@ public void GetCurrentSigningKeyInternal_should_return_a_matching_key_type() _rsaOptions.UseX509Certificate = false; var key = _subject.GetCurrentSigningKeyInternal(new[] { rsaKey1, x509Key1 }); - key.Should().NotBeNull(); - key.Id.Should().Be(x509Key1.Id); + key.ShouldNotBeNull(); + key.Id.ShouldBe(x509Key1.Id); } { _rsaOptions.UseX509Certificate = true; var key = _subject.GetCurrentSigningKeyInternal(new[] { rsaKey1, x509Key1 }); - key.Should().NotBeNull(); - key.Id.Should().Be(x509Key1.Id); + key.ShouldNotBeNull(); + key.Id.ShouldBe(x509Key1.Id); } { @@ -763,8 +763,8 @@ public void GetCurrentSigningKeyInternal_should_return_a_matching_key_type() _rsaOptions.UseX509Certificate = false; var key = _subject.GetCurrentSigningKeyInternal(new[] { rsaKey1, x509Key1, rsaKey2 }); - key.Should().NotBeNull(); - key.Id.Should().Be(rsaKey2.Id); + key.ShouldNotBeNull(); + key.Id.ShouldBe(rsaKey2.Id); } } @@ -778,7 +778,7 @@ public void CanBeUsedForSigning_key_created_within_activity_delay_should_not_be_ var result = _subject.CanBeUsedAsCurrentSigningKey(key); - result.Should().BeFalse(); + result.ShouldBeFalse(); } { @@ -786,7 +786,7 @@ public void CanBeUsedForSigning_key_created_within_activity_delay_should_not_be_ var result = _subject.CanBeUsedAsCurrentSigningKey(key); - result.Should().BeFalse(); + result.ShouldBeFalse(); } { @@ -794,7 +794,7 @@ public void CanBeUsedForSigning_key_created_within_activity_delay_should_not_be_ var result = _subject.CanBeUsedAsCurrentSigningKey(key); - result.Should().BeFalse(); + result.ShouldBeFalse(); } } @@ -806,7 +806,7 @@ public void CanBeUsedForSigning_key_created_after_active_delay_should_be_used_fo var result = _subject.CanBeUsedAsCurrentSigningKey(key); - result.Should().BeTrue(); + result.ShouldBeTrue(); } { @@ -814,7 +814,7 @@ public void CanBeUsedForSigning_key_created_after_active_delay_should_be_used_fo var result = _subject.CanBeUsedAsCurrentSigningKey(key); - result.Should().BeTrue(); + result.ShouldBeTrue(); } { @@ -822,7 +822,7 @@ public void CanBeUsedForSigning_key_created_after_active_delay_should_be_used_fo var result = _subject.CanBeUsedAsCurrentSigningKey(key); - result.Should().BeTrue(); + result.ShouldBeTrue(); } { @@ -830,7 +830,7 @@ public void CanBeUsedForSigning_key_created_after_active_delay_should_be_used_fo var result = _subject.CanBeUsedAsCurrentSigningKey(key); - result.Should().BeTrue(); + result.ShouldBeTrue(); } } @@ -842,7 +842,7 @@ public void CanBeUsedForSigning_key_older_than_expiration_should_not_be_used_for var result = _subject.CanBeUsedAsCurrentSigningKey(key); - result.Should().BeFalse(); + result.ShouldBeFalse(); } } @@ -854,7 +854,7 @@ public void CanBeUsedForSigning_ignoring_activity_delay_key_created_within_activ var result = _subject.CanBeUsedAsCurrentSigningKey(key, true); - result.Should().BeTrue(); + result.ShouldBeTrue(); } { @@ -862,7 +862,7 @@ public void CanBeUsedForSigning_ignoring_activity_delay_key_created_within_activ var result = _subject.CanBeUsedAsCurrentSigningKey(key, true); - result.Should().BeTrue(); + result.ShouldBeTrue(); } { @@ -870,7 +870,7 @@ public void CanBeUsedForSigning_ignoring_activity_delay_key_created_within_activ var result = _subject.CanBeUsedAsCurrentSigningKey(key, true); - result.Should().BeTrue(); + result.ShouldBeTrue(); } } @@ -882,7 +882,7 @@ public void CanBeUsedForSigning_ignoring_activity_delay_key_created_after_active var result = _subject.CanBeUsedAsCurrentSigningKey(key, true); - result.Should().BeTrue(); + result.ShouldBeTrue(); } { @@ -890,7 +890,7 @@ public void CanBeUsedForSigning_ignoring_activity_delay_key_created_after_active var result = _subject.CanBeUsedAsCurrentSigningKey(key, true); - result.Should().BeTrue(); + result.ShouldBeTrue(); } { @@ -898,7 +898,7 @@ public void CanBeUsedForSigning_ignoring_activity_delay_key_created_after_active var result = _subject.CanBeUsedAsCurrentSigningKey(key, true); - result.Should().BeTrue(); + result.ShouldBeTrue(); } { @@ -906,7 +906,7 @@ public void CanBeUsedForSigning_ignoring_activity_delay_key_created_after_active var result = _subject.CanBeUsedAsCurrentSigningKey(key); - result.Should().BeTrue(); + result.ShouldBeTrue(); } } @@ -918,7 +918,7 @@ public void CanBeUsedForSigning_ignoring_activity_delay_key_older_than_expiratio var result = _subject.CanBeUsedAsCurrentSigningKey(key, true); - result.Should().BeFalse(); + result.ShouldBeFalse(); } } @@ -929,11 +929,11 @@ public async Task CreateAndStoreNewKeyAsync_should_create_and_store_and_return_k { var result = await _subject.CreateAndStoreNewKeyAsync(_rsaOptions); - _mockKeyProtector.ProtectWasCalled.Should().BeTrue(); - _mockKeyStore.Keys.Count.Should().Be(1); - _mockKeyStore.Keys.Single().Id.Should().Be(result.Id); - result.Created.Should().Be(_mockClock.UtcNow.UtcDateTime); - result.Algorithm.Should().Be("RS256"); + _mockKeyProtector.ProtectWasCalled.ShouldBeTrue(); + _mockKeyStore.Keys.Count.ShouldBe(1); + _mockKeyStore.Keys.Single().Id.ShouldBe(result.Id); + result.Created.ShouldBe(_mockClock.UtcNow.UtcDateTime); + result.Algorithm.ShouldBe("RS256"); } // IsKeyRotationRequired @@ -943,11 +943,11 @@ public void IsKeyRotationRequired_when_no_keys_should_be_true() { { var result = _subject.IsKeyRotationRequired(null); - result.Should().BeTrue(); + result.ShouldBeTrue(); } { var result = _subject.IsKeyRotationRequired(new RsaKeyContainer[0]); - result.Should().BeTrue(); + result.ShouldBeTrue(); } } @@ -959,7 +959,7 @@ public void IsKeyRotationRequired_when_no_active_key_should_be_true() CreateKey(_options.KeyManagement.KeyRetirementAge.Add(TimeSpan.FromDays(1))), }; var result = _subject.IsKeyRotationRequired(keys); - result.Should().BeTrue(); + result.ShouldBeTrue(); } { @@ -968,7 +968,7 @@ public void IsKeyRotationRequired_when_no_active_key_should_be_true() }; var result = _subject.IsKeyRotationRequired(keys); - result.Should().BeTrue(); + result.ShouldBeTrue(); } } @@ -980,7 +980,7 @@ public void IsKeyRotationRequired_when_active_key_is_not_about_to_expire_should_ }; var result = _subject.IsKeyRotationRequired(keys); - result.Should().BeFalse(); + result.ShouldBeFalse(); } [Fact] @@ -992,7 +992,7 @@ public void IsKeyRotationRequired_when_active_key_is_about_to_expire_should_be_t }; var result = _subject.IsKeyRotationRequired(keys); - result.Should().BeTrue(); + result.ShouldBeTrue(); } { var keys = new[] { @@ -1000,7 +1000,7 @@ public void IsKeyRotationRequired_when_active_key_is_about_to_expire_should_be_t }; var result = _subject.IsKeyRotationRequired(keys); - result.Should().BeTrue(); + result.ShouldBeTrue(); } } @@ -1014,7 +1014,7 @@ public void IsKeyRotationRequired_when_younger_keys_exist_should_be_false() }; var result = _subject.IsKeyRotationRequired(keys); - result.Should().BeFalse(); + result.ShouldBeFalse(); } { var keys = new[] { @@ -1023,7 +1023,7 @@ public void IsKeyRotationRequired_when_younger_keys_exist_should_be_false() }; var result = _subject.IsKeyRotationRequired(keys); - result.Should().BeFalse(); + result.ShouldBeFalse(); } } @@ -1038,7 +1038,7 @@ public void IsKeyRotationRequired_when_younger_keys_are_close_to_expiration_shou }; var result = _subject.IsKeyRotationRequired(keys); - result.Should().BeTrue(); + result.ShouldBeTrue(); } } } diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/NumericUserCodeServiceTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/NumericUserCodeServiceTests.cs index 530db9cdd..6aaaad4bb 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/NumericUserCodeServiceTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/NumericUserCodeServiceTests.cs @@ -4,7 +4,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Services; -using FluentAssertions; +using Shouldly; using Xunit; namespace UnitTests.Services.Default; @@ -19,7 +19,7 @@ public async Task GenerateAsync_should_return_expected_code() var userCode = await sut.GenerateAsync(); var userCodeInt = int.Parse(userCode); - userCodeInt.Should().BeGreaterOrEqualTo(100000000); - userCodeInt.Should().BeLessOrEqualTo(999999999); + userCodeInt.ShouldBeGreaterThanOrEqualTo(100000000); + userCodeInt.ShouldBeLessThanOrEqualTo(999999999); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/OidcReturnUrlParserTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/OidcReturnUrlParserTests.cs index 01f28e155..fa324862c 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/OidcReturnUrlParserTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/OidcReturnUrlParserTests.cs @@ -4,7 +4,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Services; -using FluentAssertions; +using Shouldly; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using UnitTests.Common; @@ -40,7 +40,7 @@ public OidcReturnUrlParserTests() public void IsValidReturnUrl_accepts_authorize_or_authorizecallback(string url) { var valid = _subject.IsValidReturnUrl(url); - valid.Should().BeTrue(); + valid.ShouldBeTrue(); } [Theory] @@ -61,7 +61,7 @@ public void IsValidReturnUrl_accepts_authorize_or_authorizecallback(string url) public void IsValidReturnUrl_rejects_non_authorize_or_authorizecallback(string url) { var valid = _subject.IsValidReturnUrl(url); - valid.Should().BeFalse(); + valid.ShouldBeFalse(); } [Theory] @@ -73,7 +73,7 @@ public void IsValidReturnUrl_accepts_urls_with_current_host(string url) { _options.UserInteraction.AllowOriginInReturnUrl = true; var valid = _subject.IsValidReturnUrl(url); - valid.Should().BeTrue(); + valid.ShouldBeTrue(); } [Fact] @@ -81,7 +81,7 @@ public void IsValidReturnUrl_when_AllowHostInReturnUrl_disabled_rejects_urls_wit { _options.UserInteraction.AllowOriginInReturnUrl = false; var valid = _subject.IsValidReturnUrl("https://server/connect/authorize"); - valid.Should().BeFalse(); + valid.ShouldBeFalse(); } [Theory] @@ -97,7 +97,7 @@ public void IsValidReturnUrl_rejects_urls_with_incorrect_current_host(string url { _options.UserInteraction.AllowOriginInReturnUrl = true; var valid = _subject.IsValidReturnUrl(url); - valid.Should().BeFalse(); + valid.ShouldBeFalse(); } @@ -108,7 +108,7 @@ public void IsValidReturnUrl_accepts_urls_with_unicode() _urls.Origin = "https://" + new HostString("грант.рф").ToUriComponent(); var valid = _subject.IsValidReturnUrl("https://xn--80af5akm.xn--p1ai/connect/authorize"); - valid.Should().BeTrue(); + valid.ShouldBeTrue(); } [Theory] @@ -121,7 +121,7 @@ public void IsValidReturnUrl_accepts_urls_with_current_port(string url) _urls.Origin = "https://server:443"; var valid = _subject.IsValidReturnUrl(url); - valid.Should().BeTrue(); + valid.ShouldBeTrue(); } [Theory] @@ -140,6 +140,6 @@ public void IsValidReturnUrl_rejects_urls_with_incorrect_current_port(string url _urls.Origin = "https://server:443"; var valid = _subject.IsValidReturnUrl(url); - valid.Should().BeFalse(); + valid.ShouldBeFalse(); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Services/Default/ParRedirectUriValidatorTests.cs b/identity-server/test/IdentityServer.UnitTests/Services/Default/ParRedirectUriValidatorTests.cs index 2d25bf6d9..0a72b0a65 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/Default/ParRedirectUriValidatorTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/Default/ParRedirectUriValidatorTests.cs @@ -4,7 +4,7 @@ using Xunit; using Duende.IdentityServer.Validation; using System.Collections.Specialized; -using FluentAssertions; +using Shouldly; using System.Threading.Tasks; using Duende.IdentityServer.Models; using Duende.IdentityServer.Configuration; @@ -37,7 +37,7 @@ public async Task PushedRedirectUriCanBeUsedAsync() } }); - result.Should().Be(true); + result.ShouldBe(true); } [Fact] @@ -63,7 +63,7 @@ public async Task AnythingIsPermittedAtParEndpoint() } }); - result.Should().Be(true); + result.ShouldBe(true); } [Fact] @@ -88,7 +88,7 @@ public async Task ConfigurationControlsPermissiveness() Client = new Client() }); - result.Should().Be(false); + result.ShouldBe(false); } [Fact] @@ -116,8 +116,8 @@ public async Task UsingARegisteredPushedUriInsteadOfThePushedRedirectUriShouldSu } }); - registeredRedirectUri.Should().NotBe(pushedRedirectUri); - result.Should().Be(true); + registeredRedirectUri.ShouldNotBe(pushedRedirectUri); + result.ShouldBe(true); } [Fact] @@ -145,7 +145,7 @@ public async Task AuthorizeEndpointWithoutPushedParametersIsStillStrict() } }); - registeredRedirectUri.Should().NotBe(requestedRedirectUri); - result.Should().Be(false); + registeredRedirectUri.ShouldNotBe(requestedRedirectUri); + result.ShouldBe(false); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Services/InMemory/InMemoryCorsPolicyService.cs b/identity-server/test/IdentityServer.UnitTests/Services/InMemory/InMemoryCorsPolicyService.cs index f7780ea94..72f94cf66 100644 --- a/identity-server/test/IdentityServer.UnitTests/Services/InMemory/InMemoryCorsPolicyService.cs +++ b/identity-server/test/IdentityServer.UnitTests/Services/InMemory/InMemoryCorsPolicyService.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Xunit; @@ -37,7 +37,7 @@ public async Task client_has_origin_should_allow_origin() }); var result = await _subject.IsOriginAllowedAsync("http://foo"); - result.Should().BeTrue(); + result.ShouldBeTrue(); } [Theory] @@ -55,7 +55,7 @@ public async Task client_does_not_has_origin_should_not_allow_origin(string clie } }); var result = await _subject.IsOriginAllowedAsync("http://bar"); - result.Should().Be(false); + result.ShouldBe(false); } [Fact] @@ -72,7 +72,7 @@ public async Task client_has_many_origins_and_origin_is_in_list_should_allow_ori } }); var result = await _subject.IsOriginAllowedAsync("http://bar"); - result.Should().Be(true); + result.ShouldBe(true); } [Fact] @@ -89,7 +89,7 @@ public async Task client_has_many_origins_and_origin_is_in_not_list_should_not_a } }); var result = await _subject.IsOriginAllowedAsync("http://quux"); - result.Should().Be(false); + result.ShouldBe(false); } [Fact] @@ -113,7 +113,7 @@ public async Task many_clients_have_same_origins_should_allow_originAsync() } }); var result = await _subject.IsOriginAllowedAsync("http://foo"); - result.Should().BeTrue(); + result.ShouldBeTrue(); } [Fact] @@ -139,6 +139,6 @@ public async Task handle_invalid_cors_origin_format_exceptionAsync() } }); var result = await _subject.IsOriginAllowedAsync("http://bar"); - result.Should().BeTrue(); + result.ShouldBeTrue(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Stores/Default/CachingResourceStoreTests.cs b/identity-server/test/IdentityServer.UnitTests/Stores/Default/CachingResourceStoreTests.cs index 1b918ebff..bbd4f3732 100644 --- a/identity-server/test/IdentityServer.UnitTests/Stores/Default/CachingResourceStoreTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Stores/Default/CachingResourceStoreTests.cs @@ -8,7 +8,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Xunit; @@ -51,12 +51,12 @@ public async Task FindApiScopesByNameAsync_should_populate_cache() _apiScopes.Add(new ApiScope("scope3")); _apiScopes.Add(new ApiScope("scope4")); - _scopeCache.Items.Count.Should().Be(0); + _scopeCache.Items.Count.ShouldBe(0); var items = await _subject.FindApiScopesByNameAsync(new[] { "scope3", "scope1", "scope2", "invalid" }); - items.Count().Should().Be(3); + items.Count().ShouldBe(3); - _scopeCache.Items.Count.Should().Be(3); + _scopeCache.Items.Count.ShouldBe(3); } [Fact] @@ -67,27 +67,27 @@ public async Task FindApiScopesByNameAsync_should_populate_missing_cache_items() _apiScopes.Add(new ApiScope("scope3")); _apiScopes.Add(new ApiScope("scope4")); - _scopeCache.Items.Count.Should().Be(0); + _scopeCache.Items.Count.ShouldBe(0); var items = await _subject.FindApiScopesByNameAsync(new[] { "scope1" }); - items.Count().Should().Be(1); - _scopeCache.Items.Count.Should().Be(1); + items.Count().ShouldBe(1); + _scopeCache.Items.Count.ShouldBe(1); _apiScopes.Remove(_apiScopes.Single(x => x.Name == "scope1")); items = await _subject.FindApiScopesByNameAsync(new[] { "scope1", "scope2" }); - items.Count().Should().Be(2); - _scopeCache.Items.Count.Should().Be(2); + items.Count().ShouldBe(2); + _scopeCache.Items.Count.ShouldBe(2); _apiScopes.Remove(_apiScopes.Single(x => x.Name == "scope2")); items = await _subject.FindApiScopesByNameAsync(new[] { "scope3", "scope2", "scope4" }); - items.Count().Should().Be(3); - _scopeCache.Items.Count.Should().Be(4); + items.Count().ShouldBe(3); + _scopeCache.Items.Count.ShouldBe(4); // this shows we will find it in the cache, even if removed from the DB _apiScopes.Remove(_apiScopes.Single(x => x.Name == "scope3")); items = await _subject.FindApiScopesByNameAsync(new[] { "scope3", "scope1", "scope2" }); - items.Count().Should().Be(3); - _scopeCache.Items.Count.Should().Be(4); + items.Count().ShouldBe(3); + _scopeCache.Items.Count.ShouldBe(4); } [Fact] @@ -101,12 +101,12 @@ public async Task FindApiResourcesByScopeNameAsync_should_populate_cache() _apiScopes.Add(new ApiScope("bar1")); { - _apiCache.Items.Count.Should().Be(0); - _apiResourceNamesCache.Items.Count.Should().Be(0); + _apiCache.Items.Count.ShouldBe(0); + _apiResourceNamesCache.Items.Count.ShouldBe(0); var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "invalid" }); - items.Count().Should().Be(0); - _apiCache.Items.Count.Should().Be(0); - _apiResourceNamesCache.Items.Count.Should().Be(1); + items.Count().ShouldBe(0); + _apiCache.Items.Count.ShouldBe(0); + _apiResourceNamesCache.Items.Count.ShouldBe(1); } { @@ -114,37 +114,37 @@ public async Task FindApiResourcesByScopeNameAsync_should_populate_cache() _apiResourceNamesCache.Items.Clear(); _resourceCache.Items.Clear(); - _apiCache.Items.Count.Should().Be(0); - _apiResourceNamesCache.Items.Count.Should().Be(0); + _apiCache.Items.Count.ShouldBe(0); + _apiResourceNamesCache.Items.Count.ShouldBe(0); var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo1" }); - items.Count().Should().Be(1); - items.Select(x => x.Name).Should().BeEquivalentTo(new[] { "foo" }); - _apiCache.Items.Count.Should().Be(1); - _apiResourceNamesCache.Items.Count.Should().Be(1); + items.Count().ShouldBe(1); + items.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "foo" }); + _apiCache.Items.Count.ShouldBe(1); + _apiResourceNamesCache.Items.Count.ShouldBe(1); } { var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo2" }); - items.Count().Should().Be(1); - items.Select(x => x.Name).Should().BeEquivalentTo(new[] { "foo" }); - _apiCache.Items.Count.Should().Be(1); - _apiResourceNamesCache.Items.Count.Should().Be(2); + items.Count().ShouldBe(1); + items.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "foo" }); + _apiCache.Items.Count.ShouldBe(1); + _apiResourceNamesCache.Items.Count.ShouldBe(2); } { var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo1", "bar1" }); - items.Count().Should().Be(2); - items.Select(x => x.Name).Should().BeEquivalentTo(new[] { "foo", "bar" }); - _apiCache.Items.Count.Should().Be(2); - _apiResourceNamesCache.Items.Count.Should().Be(3); + items.Count().ShouldBe(2); + items.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "foo", "bar" }); + _apiCache.Items.Count.ShouldBe(2); + _apiResourceNamesCache.Items.Count.ShouldBe(3); } { var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo2", "foo1", "bar2", "bar1" }); - items.Count().Should().Be(2); - items.Select(x => x.Name).Should().BeEquivalentTo(new[] { "foo", "bar" }); - _apiCache.Items.Count.Should().Be(2); - _apiResourceNamesCache.Items.Count.Should().Be(4); + items.Count().ShouldBe(2); + items.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "foo", "bar" }); + _apiCache.Items.Count.ShouldBe(2); + _apiResourceNamesCache.Items.Count.ShouldBe(4); } { @@ -153,10 +153,10 @@ public async Task FindApiResourcesByScopeNameAsync_should_populate_cache() _resourceCache.Items.Clear(); var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo2", "foo1", "bar2", "bar1" }); - items.Count().Should().Be(2); - items.Select(x => x.Name).Should().BeEquivalentTo(new[] { "foo", "bar" }); - _apiCache.Items.Count.Should().Be(2); - _apiResourceNamesCache.Items.Count.Should().Be(4); + items.Count().ShouldBe(2); + items.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "foo", "bar" }); + _apiCache.Items.Count.ShouldBe(2); + _apiResourceNamesCache.Items.Count.ShouldBe(4); } { @@ -166,10 +166,10 @@ public async Task FindApiResourcesByScopeNameAsync_should_populate_cache() _identityResources.Clear(); var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo2", "foo1", "bar2", "bar1" }); - items.Count().Should().Be(2); - items.Select(x => x.Name).Should().BeEquivalentTo(new[] { "foo", "bar" }); - _apiCache.Items.Count.Should().Be(2); - _apiResourceNamesCache.Items.Count.Should().Be(4); + items.Count().ShouldBe(2); + items.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "foo", "bar" }); + _apiCache.Items.Count.ShouldBe(2); + _apiResourceNamesCache.Items.Count.ShouldBe(4); } } @@ -185,13 +185,13 @@ public async Task FindApiResourcesByScopeNameAsync_should_return_same_results_tw { var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo", "foo1", "bar", "bar1" }); - items.Count().Should().Be(2); - items.Select(x => x.Name).Should().BeEquivalentTo(new[] { "foo", "bar" }); + items.Count().ShouldBe(2); + items.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "foo", "bar" }); } { var items = await _subject.FindApiResourcesByScopeNameAsync(new[] { "foo", "foo1", "bar", "bar1" }); - items.Count().Should().Be(2); - items.Select(x => x.Name).Should().BeEquivalentTo(new[] { "foo", "bar" }); + items.Count().ShouldBe(2); + items.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "foo", "bar" }); } } } diff --git a/identity-server/test/IdentityServer.UnitTests/Stores/Default/DefaultPersistedGrantStoreTests.cs b/identity-server/test/IdentityServer.UnitTests/Stores/Default/DefaultPersistedGrantStoreTests.cs index b461fde39..34dc461e0 100644 --- a/identity-server/test/IdentityServer.UnitTests/Stores/Default/DefaultPersistedGrantStoreTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Stores/Default/DefaultPersistedGrantStoreTests.cs @@ -12,7 +12,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Stores.Serialization; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Xunit; @@ -67,14 +67,14 @@ public async Task StoreAuthorizationCodeAsync_should_persist_grant() var handle = await _codes.StoreAuthorizationCodeAsync(code1); var code2 = await _codes.GetAuthorizationCodeAsync(handle); - code1.ClientId.Should().Be(code2.ClientId); - code1.CreationTime.Should().Be(code2.CreationTime); - code1.Lifetime.Should().Be(code2.Lifetime); - code1.Subject.GetSubjectId().Should().Be(code2.Subject.GetSubjectId()); - code1.CodeChallenge.Should().Be(code2.CodeChallenge); - code1.RedirectUri.Should().Be(code2.RedirectUri); - code1.Nonce.Should().Be(code2.Nonce); - code1.RequestedScopes.Should().BeEquivalentTo(code2.RequestedScopes); + code1.ClientId.ShouldBe(code2.ClientId); + code1.CreationTime.ShouldBe(code2.CreationTime); + code1.Lifetime.ShouldBe(code2.Lifetime); + code1.Subject.GetSubjectId().ShouldBe(code2.Subject.GetSubjectId()); + code1.CodeChallenge.ShouldBe(code2.CodeChallenge); + code1.RedirectUri.ShouldBe(code2.RedirectUri); + code1.Nonce.ShouldBe(code2.Nonce); + code1.RequestedScopes.ShouldBeEquivalentTo(code2.RequestedScopes); } [Fact] @@ -95,7 +95,7 @@ public async Task RemoveAuthorizationCodeAsync_should_remove_grant() var handle = await _codes.StoreAuthorizationCodeAsync(code1); await _codes.RemoveAuthorizationCodeAsync(handle); var code2 = await _codes.GetAuthorizationCodeAsync(handle); - code2.Should().BeNull(); + code2.ShouldBeNull(); } [Fact] @@ -128,15 +128,15 @@ public async Task refresh_token_in_pre_version_5_format_should_deserialize() var handle = await _refreshTokens.StoreRefreshTokenAsync(token1); var token2 = await _refreshTokens.GetRefreshTokenAsync(handle); - token2.Version.Should().Be(5); + token2.Version.ShouldBe(5); - token2.ClientId.Should().Be("client"); - token2.Subject.GetSubjectId().Should().Be("123"); - token2.SubjectId.Should().Be("123"); - token2.Description.Should().Be("desc"); - token2.SessionId.Should().Be("sessionid"); - token2.AuthorizedScopes.Should().BeEquivalentTo(new[] { "s1", "s2" }); - token2.AccessToken.Should().BeNull(); + token2.ClientId.ShouldBe("client"); + token2.Subject.GetSubjectId().ShouldBe("123"); + token2.SubjectId.ShouldBe("123"); + token2.Description.ShouldBe("desc"); + token2.SessionId.ShouldBe("sessionid"); + token2.AuthorizedScopes.ShouldBeEquivalentTo(new[] { "s1", "s2" }); + token2.AccessToken.ShouldBeNull(); #pragma warning restore CS0618 // Type or member is obsolete } @@ -169,17 +169,17 @@ public async Task StoreRefreshTokenAsync_should_persist_grant() var handle = await _refreshTokens.StoreRefreshTokenAsync(token1); var token2 = await _refreshTokens.GetRefreshTokenAsync(handle); - token1.ClientId.Should().Be(token2.ClientId); - token1.CreationTime.Should().Be(token2.CreationTime); - token1.Lifetime.Should().Be(token2.Lifetime); - token1.Subject.GetSubjectId().Should().Be(token2.Subject.GetSubjectId()); - token1.Version.Should().Be(token2.Version); + token1.ClientId.ShouldBe(token2.ClientId); + token1.CreationTime.ShouldBe(token2.CreationTime); + token1.Lifetime.ShouldBe(token2.Lifetime); + token1.Subject.GetSubjectId().ShouldBe(token2.Subject.GetSubjectId()); + token1.Version.ShouldBe(token2.Version); var at = token2.GetAccessToken(); - at.Audiences.Count.Should().Be(1); - at.Audiences.First().Should().Be("aud"); - at.ClientId.Should().Be("client"); - at.CreationTime.Should().Be(now); - at.Type.Should().Be("type"); + at.Audiences.Count.ShouldBe(1); + at.Audiences.First().ShouldBe("aud"); + at.ClientId.ShouldBe("client"); + at.CreationTime.ShouldBe(now); + at.Type.ShouldBe("type"); } [Fact] @@ -195,7 +195,7 @@ public async Task RemoveRefreshTokenAsync_should_remove_grant() var handle = await _refreshTokens.StoreRefreshTokenAsync(token1); await _refreshTokens.RemoveRefreshTokenAsync(handle); var token2 = await _refreshTokens.GetRefreshTokenAsync(handle); - token2.Should().BeNull(); + token2.ShouldBeNull(); } [Fact] @@ -215,9 +215,9 @@ public async Task RemoveRefreshTokenAsync_by_sub_and_client_should_remove_grant( await _refreshTokens.RemoveRefreshTokensAsync("123", "client"); var token2 = await _refreshTokens.GetRefreshTokenAsync(handle1); - token2.Should().BeNull(); + token2.ShouldBeNull(); token2 = await _refreshTokens.GetRefreshTokenAsync(handle2); - token2.Should().BeNull(); + token2.ShouldBeNull(); } [Fact] @@ -241,13 +241,13 @@ public async Task StoreReferenceTokenAsync_should_persist_grant() var handle = await _referenceTokens.StoreReferenceTokenAsync(token1); var token2 = await _referenceTokens.GetReferenceTokenAsync(handle); - token1.ClientId.Should().Be(token2.ClientId); - token1.Audiences.Count.Should().Be(1); - token1.Audiences.First().Should().Be("aud"); - token1.CreationTime.Should().Be(token2.CreationTime); - token1.Type.Should().Be(token2.Type); - token1.Lifetime.Should().Be(token2.Lifetime); - token1.Version.Should().Be(token2.Version); + token1.ClientId.ShouldBe(token2.ClientId); + token1.Audiences.Count.ShouldBe(1); + token1.Audiences.First().ShouldBe("aud"); + token1.CreationTime.ShouldBe(token2.CreationTime); + token1.Type.ShouldBe(token2.Type); + token1.Lifetime.ShouldBe(token2.Lifetime); + token1.Version.ShouldBe(token2.Version); } [Fact] @@ -270,7 +270,7 @@ public async Task RemoveReferenceTokenAsync_should_remove_grant() var handle = await _referenceTokens.StoreReferenceTokenAsync(token1); await _referenceTokens.RemoveReferenceTokenAsync(handle); var token2 = await _referenceTokens.GetReferenceTokenAsync(handle); - token2.Should().BeNull(); + token2.ShouldBeNull(); } [Fact] @@ -295,9 +295,9 @@ public async Task RemoveReferenceTokenAsync_by_sub_and_client_should_remove_gran await _referenceTokens.RemoveReferenceTokensAsync("123", "client"); var token2 = await _referenceTokens.GetReferenceTokenAsync(handle1); - token2.Should().BeNull(); + token2.ShouldBeNull(); token2 = await _referenceTokens.GetReferenceTokenAsync(handle2); - token2.Should().BeNull(); + token2.ShouldBeNull(); } [Fact] @@ -314,9 +314,9 @@ public async Task StoreUserConsentAsync_should_persist_grant() await _userConsent.StoreUserConsentAsync(consent1); var consent2 = await _userConsent.GetUserConsentAsync("123", "client"); - consent2.ClientId.Should().Be(consent1.ClientId); - consent2.SubjectId.Should().Be(consent1.SubjectId); - consent2.Scopes.Should().BeEquivalentTo(new string[] { "bar", "foo" }); + consent2.ClientId.ShouldBe(consent1.ClientId); + consent2.SubjectId.ShouldBe(consent1.SubjectId); + consent2.Scopes.ShouldBeEquivalentTo(new string[] { "bar", "foo" }); } [Fact] @@ -333,7 +333,7 @@ public async Task RemoveUserConsentAsync_should_remove_grant() await _userConsent.StoreUserConsentAsync(consent1); await _userConsent.RemoveUserConsentAsync("123", "client"); var consent2 = await _userConsent.GetUserConsentAsync("123", "client"); - consent2.Should().BeNull(); + consent2.ShouldBeNull(); } [Fact] @@ -377,8 +377,8 @@ await _codes.StoreAuthorizationCodeAsync(new AuthorizationCode() }); // the -1 is needed because internally we append a version/suffix the handle for encoding - (await _codes.GetAuthorizationCodeAsync("key-1")).Lifetime.Should().Be(30); - (await _refreshTokens.GetRefreshTokenAsync("key-1")).Lifetime.Should().Be(20); - (await _referenceTokens.GetReferenceTokenAsync("key-1")).Lifetime.Should().Be(10); + (await _codes.GetAuthorizationCodeAsync("key-1")).Lifetime.ShouldBe(30); + (await _refreshTokens.GetRefreshTokenAsync("key-1")).Lifetime.ShouldBe(20); + (await _referenceTokens.GetReferenceTokenAsync("key-1")).Lifetime.ShouldBe(10); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Stores/Default/DistributedCacheAuthorizationParametersMessageStoreTests.cs b/identity-server/test/IdentityServer.UnitTests/Stores/Default/DistributedCacheAuthorizationParametersMessageStoreTests.cs index ae368402d..9bf2dbe15 100644 --- a/identity-server/test/IdentityServer.UnitTests/Stores/Default/DistributedCacheAuthorizationParametersMessageStoreTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Stores/Default/DistributedCacheAuthorizationParametersMessageStoreTests.cs @@ -7,7 +7,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores.Default; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Xunit; @@ -25,15 +25,15 @@ public DistributedCacheAuthorizationParametersMessageStoreTests() [Fact] public async Task DeleteAsync_should_remove_item() { - _mockCache.Items.Count.Should().Be(0); + _mockCache.Items.Count.ShouldBe(0); var msg = new Message>(new Dictionary()); var id = await _subject.WriteAsync(msg); - _mockCache.Items.Count.Should().Be(1); + _mockCache.Items.Count.ShouldBe(1); await _subject.DeleteAsync(id); - _mockCache.Items.Count.Should().Be(0); + _mockCache.Items.Count.ShouldBe(0); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryClientStoreTests.cs b/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryClientStoreTests.cs index fa57b20ab..53e9038d7 100644 --- a/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryClientStoreTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryClientStoreTests.cs @@ -7,7 +7,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; using Xunit; -using FluentAssertions; +using Shouldly; namespace UnitTests.Stores; @@ -24,7 +24,7 @@ public void InMemoryClient_should_throw_if_contain_duplicate_client_ids() }; Action act = () => new InMemoryClientStore(clients); - act.Should().Throw(); + act.ShouldThrow(); } [Fact] diff --git a/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryDeviceFlowStoreTests.cs b/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryDeviceFlowStoreTests.cs index 4ade2e85c..e0fb9a3ce 100644 --- a/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryDeviceFlowStoreTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryDeviceFlowStoreTests.cs @@ -8,7 +8,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; -using FluentAssertions; +using Shouldly; using Xunit; namespace UnitTests.Stores; @@ -36,13 +36,13 @@ public async Task StoreDeviceAuthorizationAsync_should_persist_data_by_user_code await _store.StoreDeviceAuthorizationAsync(deviceCode, userCode, data); var foundData = await _store.FindByUserCodeAsync(userCode); - foundData.ClientId.Should().Be(data.ClientId); - foundData.CreationTime.Should().Be(data.CreationTime); - foundData.Lifetime.Should().Be(data.Lifetime); - foundData.IsAuthorized.Should().Be(data.IsAuthorized); - foundData.IsOpenId.Should().Be(data.IsOpenId); - foundData.Subject.Should().Be(data.Subject); - foundData.RequestedScopes.Should().BeEquivalentTo(data.RequestedScopes); + foundData.ClientId.ShouldBe(data.ClientId); + foundData.CreationTime.ShouldBe(data.CreationTime); + foundData.Lifetime.ShouldBe(data.Lifetime); + foundData.IsAuthorized.ShouldBe(data.IsAuthorized); + foundData.IsOpenId.ShouldBe(data.IsOpenId); + foundData.Subject.ShouldBe(data.Subject); + foundData.RequestedScopes.ShouldBeEquivalentTo(data.RequestedScopes); } [Fact] @@ -64,13 +64,13 @@ public async Task StoreDeviceAuthorizationAsync_should_persist_data_by_device_co await _store.StoreDeviceAuthorizationAsync(deviceCode, userCode, data); var foundData = await _store.FindByDeviceCodeAsync(deviceCode); - foundData.ClientId.Should().Be(data.ClientId); - foundData.CreationTime.Should().Be(data.CreationTime); - foundData.Lifetime.Should().Be(data.Lifetime); - foundData.IsAuthorized.Should().Be(data.IsAuthorized); - foundData.IsOpenId.Should().Be(data.IsOpenId); - foundData.Subject.Should().Be(data.Subject); - foundData.RequestedScopes.Should().BeEquivalentTo(data.RequestedScopes); + foundData.ClientId.ShouldBe(data.ClientId); + foundData.CreationTime.ShouldBe(data.CreationTime); + foundData.Lifetime.ShouldBe(data.Lifetime); + foundData.IsAuthorized.ShouldBe(data.IsAuthorized); + foundData.IsOpenId.ShouldBe(data.IsOpenId); + foundData.Subject.ShouldBe(data.Subject); + foundData.RequestedScopes.ShouldBeEquivalentTo(data.RequestedScopes); } [Fact] @@ -106,13 +106,13 @@ public async Task UpdateByUserCodeAsync_should_update_data() var foundData = await _store.FindByUserCodeAsync(userCode); - foundData.ClientId.Should().Be(updatedData.ClientId); - foundData.CreationTime.Should().Be(updatedData.CreationTime); - foundData.Lifetime.Should().Be(updatedData.Lifetime); - foundData.IsAuthorized.Should().Be(updatedData.IsAuthorized); - foundData.IsOpenId.Should().Be(updatedData.IsOpenId); - foundData.Subject.Should().BeEquivalentTo(updatedData.Subject); - foundData.RequestedScopes.Should().BeEquivalentTo(updatedData.RequestedScopes); + foundData.ClientId.ShouldBe(updatedData.ClientId); + foundData.CreationTime.ShouldBe(updatedData.CreationTime); + foundData.Lifetime.ShouldBe(updatedData.Lifetime); + foundData.IsAuthorized.ShouldBe(updatedData.IsAuthorized); + foundData.IsOpenId.ShouldBe(updatedData.IsOpenId); + foundData.Subject.ShouldBeEquivalentTo(updatedData.Subject); + foundData.RequestedScopes.ShouldBeEquivalentTo(updatedData.RequestedScopes); } [Fact] @@ -135,6 +135,6 @@ public async Task RemoveByDeviceCodeAsync_should_update_data() await _store.RemoveByDeviceCodeAsync(deviceCode); var foundData = await _store.FindByUserCodeAsync(userCode); - foundData.Should().BeNull(); + foundData.ShouldBeNull(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryPersistedGrantStoreTests.cs b/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryPersistedGrantStoreTests.cs index 940050953..4da7bac03 100644 --- a/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryPersistedGrantStoreTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryPersistedGrantStoreTests.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; -using FluentAssertions; +using Shouldly; namespace UnitTests.Stores; @@ -25,14 +25,14 @@ public async Task Store_should_persist_value() { { var item = await _subject.GetAsync("key1"); - item.Should().BeNull(); + item.ShouldBeNull(); } await _subject.StoreAsync(new PersistedGrant() { Key = "key1" }); { var item = await _subject.GetAsync("key1"); - item.Should().NotBeNull(); + item.ShouldNotBeNull(); } } @@ -54,75 +54,75 @@ public async Task GetAll_should_filter() { SubjectId = "sub1" })) - .Select(x => x.Key).Should().BeEquivalentTo(new[] { "key1", "key2", "key3", "key4", "key5", "key6" }); + .Select(x => x.Key).ShouldBeEquivalentTo(new[] { "key1", "key2", "key3", "key4", "key5", "key6" }); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub2" })) - .Select(x => x.Key).Should().BeEquivalentTo(new[] { "key7" }); + .Select(x => x.Key).ShouldBeEquivalentTo(new[] { "key7" }); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub3" })) - .Select(x => x.Key).Should().BeEmpty(); + .Select(x => x.Key).ShouldBeEmpty(); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "client1" })) - .Select(x => x.Key).Should().BeEquivalentTo(new[] { "key1", "key3" }); + .Select(x => x.Key).ShouldBeEquivalentTo(new[] { "key1", "key3" }); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "client2" })) - .Select(x => x.Key).Should().BeEquivalentTo(new[] { "key2" }); + .Select(x => x.Key).ShouldBeEquivalentTo(new[] { "key2" }); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "client3" })) - .Select(x => x.Key).Should().BeEquivalentTo(new[] { "key4" }); + .Select(x => x.Key).ShouldBeEquivalentTo(new[] { "key4" }); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "client4" })) - .Select(x => x.Key).Should().BeEquivalentTo(new[] { "key5", "key6" }); + .Select(x => x.Key).ShouldBeEquivalentTo(new[] { "key5", "key6" }); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub1", ClientId = "client5" })) - .Select(x => x.Key).Should().BeEmpty(); + .Select(x => x.Key).ShouldBeEmpty(); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub2", ClientId = "client1" })) - .Select(x => x.Key).Should().BeEmpty(); + .Select(x => x.Key).ShouldBeEmpty(); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub2", ClientId = "client4" })) - .Select(x => x.Key).Should().BeEquivalentTo(new[] { "key7" }); + .Select(x => x.Key).ShouldBeEquivalentTo(new[] { "key7" }); (await _subject.GetAllAsync(new PersistedGrantFilter { SubjectId = "sub3", ClientId = "client1" })) - .Select(x => x.Key).Should().BeEmpty(); + .Select(x => x.Key).ShouldBeEmpty(); (await _subject.GetAllAsync(new PersistedGrantFilter { @@ -130,7 +130,7 @@ public async Task GetAll_should_filter() ClientId = "client1", SessionId = "session1" })) - .Select(x => x.Key).Should().BeEquivalentTo(new[] { "key1" }); + .Select(x => x.Key).ShouldBeEquivalentTo(new[] { "key1" }); (await _subject.GetAllAsync(new PersistedGrantFilter { @@ -138,7 +138,7 @@ public async Task GetAll_should_filter() ClientId = "client1", SessionId = "session2" })) - .Select(x => x.Key).Should().BeEquivalentTo(new[] { "key3" }); + .Select(x => x.Key).ShouldBeEquivalentTo(new[] { "key3" }); (await _subject.GetAllAsync(new PersistedGrantFilter { @@ -146,7 +146,7 @@ public async Task GetAll_should_filter() ClientId = "client1", SessionId = "session3" })) - .Select(x => x.Key).Should().BeEmpty(); + .Select(x => x.Key).ShouldBeEmpty(); (await _subject.GetAllAsync(new PersistedGrantFilter { @@ -154,7 +154,7 @@ public async Task GetAll_should_filter() ClientId = "client2", SessionId = "session1" })) - .Select(x => x.Key).Should().BeEquivalentTo(new[] { "key2" }); + .Select(x => x.Key).ShouldBeEquivalentTo(new[] { "key2" }); (await _subject.GetAllAsync(new PersistedGrantFilter { @@ -162,7 +162,7 @@ public async Task GetAll_should_filter() ClientId = "client2", SessionId = "session2" })) - .Select(x => x.Key).Should().BeEmpty(); + .Select(x => x.Key).ShouldBeEmpty(); (await _subject.GetAllAsync(new PersistedGrantFilter { @@ -170,7 +170,7 @@ public async Task GetAll_should_filter() ClientId = "client4", SessionId = "session4" })) - .Select(x => x.Key).Should().BeEquivalentTo(new[] { "key6" }); + .Select(x => x.Key).ShouldBeEquivalentTo(new[] { "key6" }); (await _subject.GetAllAsync(new PersistedGrantFilter { @@ -178,7 +178,7 @@ public async Task GetAll_should_filter() ClientId = "client4", SessionId = "session4" })) - .Select(x => x.Key).Should().BeEquivalentTo(new[] { "key7" }); + .Select(x => x.Key).ShouldBeEquivalentTo(new[] { "key7" }); (await _subject.GetAllAsync(new PersistedGrantFilter { @@ -186,7 +186,7 @@ public async Task GetAll_should_filter() ClientId = "client4", SessionId = "session1" })) - .Select(x => x.Key).Should().BeEmpty(); + .Select(x => x.Key).ShouldBeEmpty(); (await _subject.GetAllAsync(new PersistedGrantFilter { @@ -194,7 +194,7 @@ public async Task GetAll_should_filter() ClientId = "client4", SessionId = "session5" })) - .Select(x => x.Key).Should().BeEmpty(); + .Select(x => x.Key).ShouldBeEmpty(); } [Fact] @@ -206,13 +206,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter { SubjectId = "sub1" }); - (await _subject.GetAsync("key1")).Should().BeNull(); - (await _subject.GetAsync("key2")).Should().BeNull(); - (await _subject.GetAsync("key3")).Should().BeNull(); - (await _subject.GetAsync("key4")).Should().BeNull(); - (await _subject.GetAsync("key5")).Should().BeNull(); - (await _subject.GetAsync("key6")).Should().BeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldBeNull(); + (await _subject.GetAsync("key2")).ShouldBeNull(); + (await _subject.GetAsync("key3")).ShouldBeNull(); + (await _subject.GetAsync("key4")).ShouldBeNull(); + (await _subject.GetAsync("key5")).ShouldBeNull(); + (await _subject.GetAsync("key6")).ShouldBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -220,13 +220,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter { SubjectId = "sub2" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().NotBeNull(); - (await _subject.GetAsync("key7")).Should().BeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldNotBeNull(); + (await _subject.GetAsync("key7")).ShouldBeNull(); } { await Populate(); @@ -234,13 +234,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter { SubjectId = "sub3" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().NotBeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldNotBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -249,13 +249,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter SubjectId = "sub1", ClientId = "client1" }); - (await _subject.GetAsync("key1")).Should().BeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().BeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().NotBeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldNotBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -264,13 +264,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter SubjectId = "sub1", ClientId = "client2" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().BeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().NotBeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldNotBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -279,13 +279,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter SubjectId = "sub1", ClientId = "client3" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().BeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().NotBeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldNotBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -294,13 +294,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter SubjectId = "sub1", ClientId = "client4" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().BeNull(); - (await _subject.GetAsync("key6")).Should().BeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldBeNull(); + (await _subject.GetAsync("key6")).ShouldBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -309,13 +309,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter SubjectId = "sub1", ClientId = "client5" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().NotBeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldNotBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -324,13 +324,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter SubjectId = "sub2", ClientId = "client1" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().NotBeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldNotBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -339,13 +339,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter SubjectId = "sub1", ClientId = "client4" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().BeNull(); - (await _subject.GetAsync("key6")).Should().BeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldBeNull(); + (await _subject.GetAsync("key6")).ShouldBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -354,13 +354,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter SubjectId = "sub3", ClientId = "client1" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().NotBeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldNotBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -370,13 +370,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter ClientId = "client1", SessionId = "session1" }); - (await _subject.GetAsync("key1")).Should().BeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().NotBeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldNotBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -386,13 +386,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter ClientId = "client1", SessionId = "session2" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().BeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().NotBeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldNotBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -402,13 +402,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter ClientId = "client1", SessionId = "session3" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().NotBeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldNotBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -418,13 +418,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter ClientId = "client2", SessionId = "session1" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().BeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().NotBeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldNotBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -434,13 +434,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter ClientId = "client2", SessionId = "session2" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().NotBeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldNotBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -450,13 +450,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter ClientId = "client4", SessionId = "session4" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().BeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -466,13 +466,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter ClientId = "client4", SessionId = "session4" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().NotBeNull(); - (await _subject.GetAsync("key7")).Should().BeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldNotBeNull(); + (await _subject.GetAsync("key7")).ShouldBeNull(); } { await Populate(); @@ -482,13 +482,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter ClientId = "client4", SessionId = "session1" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().NotBeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldNotBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -498,13 +498,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter ClientId = "client4", SessionId = "session5" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().NotBeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldNotBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } { await Populate(); @@ -514,13 +514,13 @@ await _subject.RemoveAllAsync(new PersistedGrantFilter ClientId = "client1", SessionId = "session1" }); - (await _subject.GetAsync("key1")).Should().NotBeNull(); - (await _subject.GetAsync("key2")).Should().NotBeNull(); - (await _subject.GetAsync("key3")).Should().NotBeNull(); - (await _subject.GetAsync("key4")).Should().NotBeNull(); - (await _subject.GetAsync("key5")).Should().NotBeNull(); - (await _subject.GetAsync("key6")).Should().NotBeNull(); - (await _subject.GetAsync("key7")).Should().NotBeNull(); + (await _subject.GetAsync("key1")).ShouldNotBeNull(); + (await _subject.GetAsync("key2")).ShouldNotBeNull(); + (await _subject.GetAsync("key3")).ShouldNotBeNull(); + (await _subject.GetAsync("key4")).ShouldNotBeNull(); + (await _subject.GetAsync("key5")).ShouldNotBeNull(); + (await _subject.GetAsync("key6")).ShouldNotBeNull(); + (await _subject.GetAsync("key7")).ShouldNotBeNull(); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryResourcesStoreTests.cs b/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryResourcesStoreTests.cs index d6949496f..d3e794105 100644 --- a/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryResourcesStoreTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Stores/InMemoryResourcesStoreTests.cs @@ -7,7 +7,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; using Xunit; -using FluentAssertions; +using Shouldly; namespace UnitTests.Stores; @@ -38,13 +38,13 @@ public void InMemoryResourcesStore_should_throw_if_contains_duplicate_names() }; Action act = () => new InMemoryResourcesStore(identityResources, null, null); - act.Should().Throw(); + act.ShouldThrow(); act = () => new InMemoryResourcesStore(null, apiResources, null); - act.Should().Throw(); + act.ShouldThrow(); act = () => new InMemoryResourcesStore(null, null, scopes); - act.Should().Throw(); + act.ShouldThrow(); } [Fact] diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AccessTokenValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AccessTokenValidation.cs index f5b4c1bda..b83abcb1d 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AccessTokenValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AccessTokenValidation.cs @@ -9,7 +9,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using UnitTests.Validation.Setup; @@ -58,19 +58,19 @@ public async Task Valid_Reference_Token() var result = await validator.ValidateAccessTokenAsync(handle); - result.IsError.Should().BeFalse(); - result.Claims.Count().Should().Be(9); - result.Claims.First(c => c.Type == JwtClaimTypes.ClientId).Value.Should().Be("roclient"); + result.IsError.ShouldBeFalse(); + result.Claims.Count().ShouldBe(9); + result.Claims.First(c => c.Type == JwtClaimTypes.ClientId).Value.ShouldBe("roclient"); var claimTypes = result.Claims.Select(c => c.Type).ToList(); - claimTypes.Should().Contain("iss"); - claimTypes.Should().Contain("aud"); - claimTypes.Should().Contain("iat"); - claimTypes.Should().Contain("nbf"); - claimTypes.Should().Contain("exp"); - claimTypes.Should().Contain("client_id"); - claimTypes.Should().Contain("sub"); - claimTypes.Should().Contain("scope"); + claimTypes.ShouldContain("iss"); + claimTypes.ShouldContain("aud"); + claimTypes.ShouldContain("iat"); + claimTypes.ShouldContain("nbf"); + claimTypes.ShouldContain("exp"); + claimTypes.ShouldContain("client_id"); + claimTypes.ShouldContain("sub"); + claimTypes.ShouldContain("scope"); } [Fact] @@ -86,7 +86,7 @@ public async Task Valid_Reference_Token_with_required_Scope() var result = await validator.ValidateAccessTokenAsync(handle, "read"); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -102,8 +102,8 @@ public async Task Valid_Reference_Token_with_missing_Scope() var result = await validator.ValidateAccessTokenAsync(handle, "missing"); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.ProtectedResourceErrors.InsufficientScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InsufficientScope); } [Fact] @@ -114,8 +114,8 @@ public async Task Unknown_Reference_Token() var result = await validator.ValidateAccessTokenAsync("unknown"); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.ProtectedResourceErrors.InvalidToken); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); } [Fact] @@ -128,8 +128,8 @@ public async Task Reference_Token_Too_Long() var longToken = "x".Repeat(options.InputLengthRestrictions.TokenHandle + 1); var result = await validator.ValidateAccessTokenAsync(longToken); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.ProtectedResourceErrors.InvalidToken); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); } [Fact] @@ -150,8 +150,8 @@ public async Task Expired_Reference_Token() var result = await validator.ValidateAccessTokenAsync(handle); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.ProtectedResourceErrors.ExpiredToken); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.ExpiredToken); } [Fact] @@ -162,8 +162,8 @@ public async Task Malformed_JWT_Token() var result = await validator.ValidateAccessTokenAsync("unk.nown"); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.ProtectedResourceErrors.InvalidToken); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); } [Fact] @@ -176,7 +176,7 @@ public async Task Valid_JWT_Token() var validator = Factory.CreateTokenValidator(null); var result = await validator.ValidateAccessTokenAsync(jwt); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Theory] @@ -194,15 +194,15 @@ public async Task JWT_Token_with_scopes_have_expected_claims(bool flag) var validator = Factory.CreateTokenValidator(null); var result = await validator.ValidateAccessTokenAsync(jwt); - result.IsError.Should().BeFalse(); - result.Jwt.Should().NotBeNullOrEmpty(); - result.Client.ClientId.Should().Be("roclient"); + result.IsError.ShouldBeFalse(); + result.Jwt.ShouldNotBeNullOrEmpty(); + result.Client.ClientId.ShouldBe("roclient"); - result.Claims.Count().Should().Be(9); + result.Claims.Count().ShouldBe(9); var scopes = result.Claims.Where(c => c.Type == "scope").Select(c => c.Value).ToArray(); - scopes.Length.Should().Be(2); - scopes[0].Should().Be("read"); - scopes[1].Should().Be("write"); + scopes.Length.ShouldBe(2); + scopes[0].ShouldBe("read"); + scopes[1].ShouldBe("write"); } [Fact] @@ -217,8 +217,8 @@ public async Task JWT_Token_invalid_Issuer() var validator = Factory.CreateTokenValidator(null); var result = await validator.ValidateAccessTokenAsync(jwt); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.ProtectedResourceErrors.InvalidToken); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); } [Fact] @@ -231,8 +231,8 @@ public async Task JWT_Token_Too_Long() var validator = Factory.CreateTokenValidator(null); var result = await validator.ValidateAccessTokenAsync(jwt); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.ProtectedResourceErrors.InvalidToken); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); } [Fact] @@ -248,6 +248,6 @@ public async Task Valid_AccessToken_but_Client_not_active() var result = await validator.ValidateAccessTokenAsync(handle); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Code.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Code.cs index 710509493..9f8177bdf 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Code.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Code.cs @@ -5,7 +5,7 @@ using System.Collections.Specialized; using System.Threading.Tasks; using Duende.IdentityServer.Configuration; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using UnitTests.Validation.Setup; @@ -30,8 +30,8 @@ public async Task Code_Request_Unknown_Scope() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); } [Fact] @@ -47,8 +47,8 @@ public async Task OpenId_Code_Request_Invalid_RedirectUri() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Fact] @@ -65,8 +65,8 @@ public async Task OpenId_Code_Request_Invalid_IdToken_ResponseType() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.UnauthorizedClient); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnauthorizedClient); } [Fact] @@ -83,8 +83,8 @@ public async Task OpenId_Code_Request_Invalid_IdTokenToken_ResponseType() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.UnauthorizedClient); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnauthorizedClient); } [Fact] @@ -100,8 +100,8 @@ public async Task OpenId_Code_Request_With_Unknown_Client() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.UnauthorizedClient); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnauthorizedClient); } [Fact] @@ -117,7 +117,7 @@ public async Task OpenId_Code_Request_With_Restricted_Scope() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_IdToken.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_IdToken.cs index 38a28c2b1..293d77f27 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_IdToken.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_IdToken.cs @@ -5,7 +5,7 @@ using System.Collections.Specialized; using System.Threading.Tasks; using Duende.IdentityServer.Configuration; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using UnitTests.Validation.Setup; @@ -31,7 +31,7 @@ public async Task Mixed_IdToken_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Invalid.cs index 51b0db4c1..e1e78e8b6 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Invalid.cs @@ -5,7 +5,7 @@ using System.Collections.Specialized; using System.Threading.Tasks; using Duende.IdentityServer.Configuration; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using UnitTests.Validation.Setup; @@ -32,7 +32,7 @@ public async Task Invalid_Protocol_Client() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.UnauthorizedClient); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnauthorizedClient); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Token.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Token.cs index 0e1787455..10bde2853 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Token.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Token.cs @@ -5,7 +5,7 @@ using System.Collections.Specialized; using System.Threading.Tasks; using Duende.IdentityServer.Configuration; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using UnitTests.Validation.Setup; @@ -32,8 +32,8 @@ public async Task Mixed_Token_Request_Without_OpenId_Scope() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); } [Fact] @@ -50,8 +50,8 @@ public async Task IdTokenToken_Request_with_no_AAVB() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } @@ -69,7 +69,7 @@ public async Task CodeIdTokenToken_Request_with_no_AAVB() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Valid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Valid.cs index 4c0302e2e..8f47ec2b0 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Valid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ClientValidation_Valid.cs @@ -5,7 +5,7 @@ using System.Collections.Specialized; using System.Threading.Tasks; using Duende.IdentityServer.Configuration; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using UnitTests.Validation.Setup; @@ -32,7 +32,7 @@ public async Task Valid_OpenId_Code_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -48,7 +48,7 @@ public async Task Valid_Resource_Code_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -64,7 +64,7 @@ public async Task Valid_Mixed_Code_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -80,7 +80,7 @@ public async Task Valid_Mixed_Code_Request_Multiple_Scopes() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -97,7 +97,7 @@ public async Task Valid_OpenId_CodeIdToken_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -114,7 +114,7 @@ public async Task Valid_OpenId_CodeIdTokenToken_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -131,7 +131,7 @@ public async Task Valid_Mixed_CodeIdToken_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -148,7 +148,7 @@ public async Task Valid_Mixed_CodeIdTokenToken_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -165,7 +165,7 @@ public async Task Valid_OpenId_IdTokenToken_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -182,7 +182,7 @@ public async Task Valid_Mixed_IdTokenToken_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -199,7 +199,7 @@ public async Task Valid_Mixed_IdTokenToken_Request_Multiple_Scopes() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -215,7 +215,7 @@ public async Task Valid_Resource_Token_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -232,6 +232,6 @@ public async Task Valid_OpenId_TokenIdToken_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_CustomValidator.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_CustomValidator.cs index 89ba890a2..480af9b84 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_CustomValidator.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_CustomValidator.cs @@ -6,7 +6,7 @@ using System.Collections.Specialized; using System.Threading.Tasks; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Validation.Setup; using Xunit; @@ -37,7 +37,7 @@ public async Task should_call_custom_validator() var result = await _subject.ValidateAsync(parameters); - _stubAuthorizeRequestValidator.WasCalled.Should().BeTrue(); + _stubAuthorizeRequestValidator.WasCalled.ShouldBeTrue(); } [Fact] @@ -56,9 +56,9 @@ public async Task should_return_error_info_from_custom_validator() }; var result = await _subject.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("foo"); - result.ErrorDescription.Should().Be("bar"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("foo"); + result.ErrorDescription.ShouldBe("bar"); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Invalid.cs index eb25fbeea..2d7eb60f5 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Invalid.cs @@ -6,7 +6,7 @@ using System.Collections.Specialized; using System.Threading.Tasks; using Duende.IdentityServer; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Validation.Setup; using Xunit; @@ -25,7 +25,7 @@ public async Task Null_Parameter() Func act = () => validator.ValidateAsync(null); - await act.Should().ThrowAsync(); + await act.ShouldThrowAsync(); } [Fact] @@ -35,8 +35,8 @@ public async Task Empty_Parameters() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(new NameValueCollection()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } // fails because openid scope is requested, but no response type that indicates an identity token @@ -53,8 +53,8 @@ public async Task OpenId_Token_Only_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); } [Fact] @@ -71,8 +71,8 @@ public async Task Resource_Only_IdToken_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Fact] @@ -88,8 +88,8 @@ public async Task Mixed_Token_Only_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); } [Fact] @@ -105,8 +105,8 @@ public async Task OpenId_IdToken_Request_Nonce_Missing() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Fact] @@ -121,8 +121,8 @@ public async Task Missing_ClientId() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Fact] @@ -137,8 +137,8 @@ public async Task Missing_Scope() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Fact] @@ -153,8 +153,8 @@ public async Task Missing_RedirectUri() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Theory] @@ -172,8 +172,8 @@ public async Task Malformed_RedirectUri(string redirectUri) var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Fact] @@ -189,8 +189,8 @@ public async Task Malformed_RedirectUri_Triple_Slash() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Fact] @@ -205,8 +205,8 @@ public async Task Missing_ResponseType() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Fact] @@ -222,8 +222,8 @@ public async Task Unknown_ResponseType() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.UnsupportedResponseType); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnsupportedResponseType); } [Fact] @@ -240,8 +240,8 @@ public async Task Invalid_ResponseMode_For_IdToken_ResponseType() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Fact] @@ -258,8 +258,8 @@ public async Task Invalid_ResponseMode_For_IdTokenToken_ResponseType() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Fact] @@ -276,8 +276,8 @@ public async Task Invalid_ResponseMode_For_CodeToken_ResponseType() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Fact] @@ -294,8 +294,8 @@ public async Task Invalid_ResponseMode_For_CodeIdToken_ResponseType() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Fact] @@ -312,8 +312,8 @@ public async Task Invalid_ResponseMode_For_CodeIdTokenToken_ResponseType() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Fact] @@ -330,8 +330,8 @@ public async Task Malformed_MaxAge() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Fact] @@ -348,8 +348,8 @@ public async Task Negative_MaxAge() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Fact] @@ -366,8 +366,8 @@ public async Task Invalid_ResponseMode_For_TokenIdToken_ResponseType() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Fact] @@ -384,8 +384,8 @@ public async Task Invalid_ResponseMode_For_IdTokenCodeToken_ResponseType() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Fact] @@ -403,7 +403,7 @@ public async Task prompt_none_and_other_values_should_fail() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_PAR.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_PAR.cs index 5b4f3bee0..868a5bd15 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_PAR.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_PAR.cs @@ -10,7 +10,7 @@ using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using UnitTests.Validation.Setup; @@ -45,9 +45,9 @@ public void par_should_bind_client_to_pushed_request() var validator = Factory.CreateRequestObjectValidator(); var result = validator.ValidatePushedAuthorizationBindingToClient(par, request); - result.Should().NotBeNull(); - result.IsError.Should().Be(true); - result.ErrorDescription.Should().Be("invalid client for pushed authorization request"); + result.ShouldNotBeNull(); + result.IsError.ShouldBe(true); + result.ErrorDescription.ShouldBe("invalid client for pushed authorization request"); } [Fact] @@ -65,8 +65,8 @@ public void expired_par_requests_should_fail() var validator = Factory.CreateRequestObjectValidator(); var result = validator.ValidatePushedAuthorizationExpiration(par, authorizeRequest); - result.Should().NotBeNull(); - result.IsError.Should().Be(true); - result.ErrorDescription.Should().Be("expired pushed authorization request"); + result.ShouldNotBeNull(); + result.IsError.ShouldBe(true); + result.ErrorDescription.ShouldBe("expired pushed authorization request"); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_PKCE.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_PKCE.cs index 8b419d235..3b67c77ad 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_PKCE.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_PKCE.cs @@ -5,7 +5,7 @@ using System.Collections.Specialized; using System.Threading.Tasks; using Duende.IdentityServer.Configuration; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using UnitTests.Validation.Setup; @@ -36,8 +36,8 @@ public async Task valid_openid_code_request_with_challenge_and_plain_method_shou var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().Be(true); - result.ErrorDescription.Should().Be("Transform algorithm not supported"); + result.IsError.ShouldBe(true); + result.ErrorDescription.ShouldBe("Transform algorithm not supported"); } [Theory] @@ -57,7 +57,7 @@ public async Task valid_openid_code_request_with_challenge_and_sh256_method_shou var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().Be(false); + result.IsError.ShouldBe(false); } [Theory] @@ -76,7 +76,7 @@ public async Task valid_openid_code_request_with_challenge_and_missing_method_sh var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().Be(false); + result.IsError.ShouldBe(false); } [Theory] @@ -95,8 +95,8 @@ public async Task valid_openid_code_request_with_challenge_and_missing_method_sh var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().Be(true); - result.ErrorDescription.Should().Be("Transform algorithm not supported"); + result.IsError.ShouldBe(true); + result.ErrorDescription.ShouldBe("Transform algorithm not supported"); } @@ -113,9 +113,9 @@ public async Task openid_code_request_missing_challenge_should_be_rejected() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().Be(true); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); - result.ErrorDescription.Should().Be("code challenge required"); + result.IsError.ShouldBe(true); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); + result.ErrorDescription.ShouldBe("code challenge required"); } [Fact] @@ -131,9 +131,9 @@ public async Task openid_hybrid_request_missing_challenge_should_be_rejected() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().Be(true); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); - result.ErrorDescription.Should().Be("code challenge required"); + result.IsError.ShouldBe(true); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); + result.ErrorDescription.ShouldBe("code challenge required"); } [Theory] @@ -155,9 +155,9 @@ public async Task openid_code_request_with_challenge_and_invalid_method_should_b var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().Be(true); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); - result.ErrorDescription.Should().Be("Transform algorithm not supported"); + result.IsError.ShouldBe(true); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); + result.ErrorDescription.ShouldBe("Transform algorithm not supported"); } [Theory] @@ -179,8 +179,8 @@ public async Task openid_code_request_with_too_short_challenge_should_be_rejecte var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().Be(true); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBe(true); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } [Theory] @@ -202,7 +202,7 @@ public async Task openid_code_request_with_too_long_challenge_should_be_rejected var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().Be(true); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidRequest); + result.IsError.ShouldBe(true); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidRequest); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Resources.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Resources.cs index d2bcc206a..d84052992 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Resources.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Resources.cs @@ -9,7 +9,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using Duende.IdentityServer.Licensing.V2; using Microsoft.Extensions.Logging.Abstractions; @@ -74,8 +74,8 @@ public async Task no_resourceindicators_should_succeed() var result = await _subject.ValidateAsync(parameters); - result.IsError.Should().Be(false); - result.ValidatedRequest.RequestedResourceIndicators.Should().BeEmpty(); + result.IsError.ShouldBe(false); + result.ValidatedRequest.RequestedResourceIndicators.ShouldBeEmpty(); } [Fact] @@ -91,8 +91,8 @@ public async Task invalid_uri_resourceindicator_should_fail() var result = await _subject.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } [Fact] @@ -108,7 +108,7 @@ public async Task valid_uri_resourceindicator_should_succeed() var result = await _subject.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -124,8 +124,8 @@ public async Task implicit_request_with_resourceindicator_should_fail() var result = await _subject.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } [Fact] @@ -141,8 +141,8 @@ public async Task resourceindicator_too_long_should_fail() var result = await _subject.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } [Fact] @@ -158,8 +158,8 @@ public async Task fragment_in_resourceindicator_should_fail() var result = await _subject.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } [Fact] @@ -177,9 +177,9 @@ public async Task multiple_uri_resourceindicators_should_succeed() var result = await _subject.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); - result.ValidatedRequest.RequestedResourceIndicators.Should() - .BeEquivalentTo(new[] { "urn:test1", "http://resource1", "http://resource2" }); + result.IsError.ShouldBeFalse(); + result.ValidatedRequest.RequestedResourceIndicators + .ShouldBeEquivalentTo(new[] { "urn:test1", "http://resource1", "http://resource2" }); } [Fact] @@ -200,8 +200,8 @@ public async Task failed_resource_validation_should_fail() }; var result = await _subject.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_scope"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_scope"); } { @@ -211,8 +211,8 @@ public async Task failed_resource_validation_should_fail() }; var result = await _subject.ValidateAsync(parameters); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Valid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Valid.cs index f061a6fb7..a2c558d4b 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Valid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/AuthorizeRequest Validation/Authorize_ProtocolValidation_Valid.cs @@ -6,7 +6,7 @@ using System.Linq; using System.Threading.Tasks; using Duende.IdentityServer; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Validation.Setup; using Xunit; @@ -30,7 +30,7 @@ public async Task Valid_OpenId_Code_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().Be(false); + result.IsError.ShouldBe(false); } [Fact] @@ -46,7 +46,7 @@ public async Task Valid_Resource_Code_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -62,7 +62,7 @@ public async Task Valid_Mixed_Code_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -78,7 +78,7 @@ public async Task Valid_Resource_Token_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -95,7 +95,7 @@ public async Task Valid_OpenId_IdToken_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -112,7 +112,7 @@ public async Task Valid_Mixed_IdTokenToken_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -130,7 +130,7 @@ public async Task Valid_OpenId_IdToken_With_FormPost_ResponseMode_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -148,7 +148,7 @@ public async Task Valid_OpenId_IdToken_Token_With_FormPost_ResponseMode_Request( var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -164,7 +164,7 @@ public async Task Valid_OpenId_Code_Token_Request() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -181,7 +181,7 @@ public async Task Valid_ResponseMode_For_Code_ResponseType() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -199,7 +199,7 @@ public async Task anonymous_user_should_produce_session_state_value() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.ValidatedRequest.SessionId.Should().NotBeNull(); + result.ValidatedRequest.SessionId.ShouldNotBeNull(); } [Fact] @@ -217,9 +217,9 @@ public async Task multiple_prompt_values_should_be_accepted() var validator = Factory.CreateAuthorizeRequestValidator(); var result = await validator.ValidateAsync(parameters); - result.ValidatedRequest.PromptModes.Count().Should().Be(2); - result.ValidatedRequest.PromptModes.Should().Contain(OidcConstants.PromptModes.Login); - result.ValidatedRequest.PromptModes.Should().Contain(OidcConstants.PromptModes.Consent); + result.ValidatedRequest.PromptModes.Count().ShouldBe(2); + result.ValidatedRequest.PromptModes.ShouldContain(OidcConstants.PromptModes.Login); + result.ValidatedRequest.PromptModes.ShouldContain(OidcConstants.PromptModes.Consent); } [Fact] @@ -238,23 +238,23 @@ public async Task processed_prompt_values_should_overwrite_original_values() { parameters[OidcConstants.AuthorizeRequest.Prompt] = "consent login"; var result = await validator.ValidateAsync(parameters); - result.ValidatedRequest.PromptModes.Should().BeEquivalentTo(new[] { OidcConstants.PromptModes.Consent, OidcConstants.PromptModes.Login }); + result.ValidatedRequest.PromptModes.ShouldBeEquivalentTo(new[] { OidcConstants.PromptModes.Consent, OidcConstants.PromptModes.Login }); } { parameters[OidcConstants.AuthorizeRequest.Prompt] = "consent login"; parameters[Constants.ProcessedPrompt] = "login"; var result = await validator.ValidateAsync(parameters); - result.ValidatedRequest.PromptModes.Should().BeEquivalentTo(new[] { OidcConstants.PromptModes.Consent }); - result.ValidatedRequest.OriginalPromptModes.Should().BeEquivalentTo(new[] { OidcConstants.PromptModes.Consent, OidcConstants.PromptModes.Login }); - result.ValidatedRequest.ProcessedPromptModes.Should().BeEquivalentTo(new[] { OidcConstants.PromptModes.Login }); + result.ValidatedRequest.PromptModes.ShouldBeEquivalentTo(new[] { OidcConstants.PromptModes.Consent }); + result.ValidatedRequest.OriginalPromptModes.ShouldBeEquivalentTo(new[] { OidcConstants.PromptModes.Consent, OidcConstants.PromptModes.Login }); + result.ValidatedRequest.ProcessedPromptModes.ShouldBeEquivalentTo(new[] { OidcConstants.PromptModes.Login }); } { parameters[OidcConstants.AuthorizeRequest.Prompt] = "consent login"; parameters[Constants.ProcessedPrompt] = "login consent"; var result = await validator.ValidateAsync(parameters); - result.ValidatedRequest.PromptModes.Should().BeEmpty(); - result.ValidatedRequest.OriginalPromptModes.Should().BeEquivalentTo(new[] { OidcConstants.PromptModes.Consent, OidcConstants.PromptModes.Login }); - result.ValidatedRequest.ProcessedPromptModes.Should().BeEquivalentTo(new[] { OidcConstants.PromptModes.Consent, OidcConstants.PromptModes.Login }); + result.ValidatedRequest.PromptModes.ShouldBeEmpty(); + result.ValidatedRequest.OriginalPromptModes.ShouldBeEquivalentTo(new[] { OidcConstants.PromptModes.Consent, OidcConstants.PromptModes.Login }); + result.ValidatedRequest.ProcessedPromptModes.ShouldBeEquivalentTo(new[] { OidcConstants.PromptModes.Consent, OidcConstants.PromptModes.Login }); } } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/BearerTokenUsageValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/BearerTokenUsageValidation.cs index b5ee9799b..8085f28d0 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/BearerTokenUsageValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/BearerTokenUsageValidation.cs @@ -6,7 +6,7 @@ using System.Text; using System.Threading.Tasks; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Microsoft.AspNetCore.Http; using Xunit; @@ -27,7 +27,7 @@ public async Task No_Header_no_Body_Get() var validator = new BearerTokenUsageValidator(TestLogger.Create< BearerTokenUsageValidator>()); var result = await validator.ValidateAsync(ctx); - result.TokenFound.Should().BeFalse(); + result.TokenFound.ShouldBeFalse(); } [Fact] @@ -40,7 +40,7 @@ public async Task No_Header_no_Body_Post() var validator = new BearerTokenUsageValidator(TestLogger.Create()); var result = await validator.ValidateAsync(ctx); - result.TokenFound.Should().BeFalse(); + result.TokenFound.ShouldBeFalse(); } [Fact] @@ -54,7 +54,7 @@ public async Task Non_Bearer_Scheme_Header() var validator = new BearerTokenUsageValidator(TestLogger.Create()); var result = await validator.ValidateAsync(ctx); - result.TokenFound.Should().BeFalse(); + result.TokenFound.ShouldBeFalse(); } [Fact] @@ -68,7 +68,7 @@ public async Task Empty_Bearer_Scheme_Header() var validator = new BearerTokenUsageValidator(TestLogger.Create()); var result = await validator.ValidateAsync(ctx); - result.TokenFound.Should().BeFalse(); + result.TokenFound.ShouldBeFalse(); } [Fact] @@ -82,7 +82,7 @@ public async Task Whitespaces_Bearer_Scheme_Header() var validator = new BearerTokenUsageValidator(TestLogger.Create()); var result = await validator.ValidateAsync(ctx); - result.TokenFound.Should().BeFalse(); + result.TokenFound.ShouldBeFalse(); } [Fact] @@ -96,9 +96,9 @@ public async Task Valid_Bearer_Scheme_Header() var validator = new BearerTokenUsageValidator(TestLogger.Create()); var result = await validator.ValidateAsync(ctx); - result.TokenFound.Should().BeTrue(); - result.Token.Should().Be("token"); - result.UsageType.Should().Be(BearerTokenUsageType.AuthorizationHeader); + result.TokenFound.ShouldBeTrue(); + result.Token.ShouldBe("token"); + result.UsageType.ShouldBe(BearerTokenUsageType.AuthorizationHeader); } [Fact] @@ -114,9 +114,9 @@ public async Task Valid_Body_Post() var validator = new BearerTokenUsageValidator(TestLogger.Create()); var result = await validator.ValidateAsync(ctx); - result.TokenFound.Should().BeTrue(); - result.Token.Should().Be("token"); - result.UsageType.Should().Be(BearerTokenUsageType.PostBody); + result.TokenFound.ShouldBeTrue(); + result.Token.ShouldBe("token"); + result.UsageType.ShouldBe(BearerTokenUsageType.PostBody); } [Fact] @@ -132,7 +132,7 @@ public async Task Body_Post_empty_Token() var validator = new BearerTokenUsageValidator(TestLogger.Create()); var result = await validator.ValidateAsync(ctx); - result.TokenFound.Should().BeFalse(); + result.TokenFound.ShouldBeFalse(); } [Fact] @@ -148,7 +148,7 @@ public async Task Body_Post_Whitespace_Token() var validator = new BearerTokenUsageValidator(TestLogger.Create()); var result = await validator.ValidateAsync(ctx); - result.TokenFound.Should().BeFalse(); + result.TokenFound.ShouldBeFalse(); } [Fact] @@ -164,6 +164,6 @@ public async Task Body_Post_no_Token() var validator = new BearerTokenUsageValidator(TestLogger.Create()); var result = await validator.ValidateAsync(ctx); - result.TokenFound.Should().BeFalse(); + result.TokenFound.ShouldBeFalse(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/ClientConfigurationValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/ClientConfigurationValidation.cs index 5301e9538..7be1c81a9 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/ClientConfigurationValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/ClientConfigurationValidation.cs @@ -7,7 +7,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Models; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Validation.Setup; using Xunit; @@ -199,7 +199,7 @@ public async Task Not_required_client_secret_for_hybrid_should_succeed() }; var context = await ValidateAsync(client); - context.IsValid.Should().BeTrue(); + context.IsValid.ShouldBeTrue(); } [Fact] @@ -215,7 +215,7 @@ public async Task Missing_client_secret_for_implicit_should_succeed() }; var context = await ValidateAsync(client); - context.IsValid.Should().BeTrue(); + context.IsValid.ShouldBeTrue(); } [Fact] @@ -248,7 +248,7 @@ public async Task null_redirect_uris_collection_should_succeed() }; var context = await ValidateAsync(client); - context.IsValid.Should().BeTrue(); + context.IsValid.ShouldBeTrue(); } [Fact] @@ -265,7 +265,7 @@ public async Task null_post_logout_redirect_uris_collection_should_succeed() }; var context = await ValidateAsync(client); - context.IsValid.Should().BeTrue(); + context.IsValid.ShouldBeTrue(); } [Fact] [Trait("Category", Category)] @@ -281,7 +281,7 @@ public async Task null_redirect_uris_should_succeed() }; var context = await ValidateAsync(client); - context.IsValid.Should().BeTrue(); + context.IsValid.ShouldBeTrue(); } [Fact] [Trait("Category", Category)] @@ -297,7 +297,7 @@ public async Task null_post_logout_redirect_uris_should_succeed() }; var context = await ValidateAsync(client); - context.IsValid.Should().BeTrue(); + context.IsValid.ShouldBeTrue(); } [Fact] [Trait("Category", Category)] @@ -313,7 +313,7 @@ public async Task empty_redirect_uris_collection_should_succeed() }; var context = await ValidateAsync(client); - context.IsValid.Should().BeTrue(); + context.IsValid.ShouldBeTrue(); } [Fact] [Trait("Category", Category)] @@ -329,7 +329,7 @@ public async Task empty_post_logout_redirect_uris_collection_should_succeed() }; var context = await ValidateAsync(client); - context.IsValid.Should().BeTrue(); + context.IsValid.ShouldBeTrue(); } [Fact] @@ -362,7 +362,7 @@ public async Task ValidateUriSchemesAsync_for_null_redirecturi_scheme_should_suc }; var result = await ValidateAsync(client); - result.IsValid.Should().BeTrue(); + result.IsValid.ShouldBeTrue(); } [Fact] @@ -378,7 +378,7 @@ public async Task ValidateUriSchemesAsync_for_valid_redirect_uri_scheme_should_s }; var result = await ValidateAsync(client); - result.IsValid.Should().BeTrue(); + result.IsValid.ShouldBeTrue(); } [Fact] @@ -413,7 +413,7 @@ public async Task ValidateUriSchemesAsync_for_valid_post_logout_redirect_uri_sch }; var result = await ValidateAsync(client); - result.IsValid.Should().BeTrue(); + result.IsValid.ShouldBeTrue(); } [Theory] @@ -444,15 +444,15 @@ public async Task ValidateAllowedCorsOriginsAsync_should_report_invalid_URL_form }; var result = await ValidateAsync(client); - result.IsValid.Should().BeFalse(); - result.ErrorMessage.Should().Contain("invalid origin"); + result.IsValid.ShouldBeFalse(); + result.ErrorMessage.ShouldContain("invalid origin"); if (!String.IsNullOrWhiteSpace(origin)) { - result.ErrorMessage.Should().Contain(origin); + result.ErrorMessage.ShouldContain(origin); } else { - result.ErrorMessage.Should().Contain("empty value"); + result.ErrorMessage.ShouldContain("empty value"); } } @@ -477,7 +477,7 @@ public async Task ValidateAllowedCorsOriginsAsync_should_allow_valid_formats(str }; var result = await ValidateAsync(client); - result.IsValid.Should().BeTrue(); + result.IsValid.ShouldBeTrue(); } @@ -493,7 +493,7 @@ private async Task ShouldFailAsync(Client client, string expectedError) { var context = await ValidateAsync(client); - context.IsValid.Should().BeFalse(); - context.ErrorMessage.Should().Be(expectedError); + context.IsValid.ShouldBeFalse(); + context.ErrorMessage.ShouldBe(expectedError); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/DPoPProofValidatorTests.cs b/identity-server/test/IdentityServer.UnitTests/Validation/DPoPProofValidatorTests.cs index 1161b1fa2..e9ccf5fc1 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/DPoPProofValidatorTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/DPoPProofValidatorTests.cs @@ -14,7 +14,7 @@ using Duende.IdentityServer.Extensions; using Duende.IdentityServer.Models; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Logging; @@ -136,8 +136,8 @@ public async Task valid_dpop_jwt_should_pass_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeFalse(); - result.JsonWebKeyThumbprint.Should().Be(_JKT); + result.IsError.ShouldBeFalse(); + result.JsonWebKeyThumbprint.ShouldBe(_JKT); } [Fact] @@ -153,9 +153,9 @@ public async Task ath_with_valid_access_token_should_pass_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeFalse(); - result.JsonWebKeyThumbprint.Should().Be(_JKT); - result.AccessTokenHash.Should().Be(accessTokenHash); + result.IsError.ShouldBeFalse(); + result.JsonWebKeyThumbprint.ShouldBe(_JKT); + result.AccessTokenHash.ShouldBe(accessTokenHash); } private Claim CnfClaim(string jwkString = null ) @@ -185,9 +185,9 @@ public async Task missing_ath_should_fail() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidDPoPProof); - result.ErrorDescription.Should().Be("Invalid 'ath' value."); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidDPoPProof); + result.ErrorDescription.ShouldBe("Invalid 'ath' value."); } [Fact] @@ -202,9 +202,9 @@ public async Task invalid_ath_should_fail() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.ErrorDescription.Should().Be("Invalid 'ath' value."); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidDPoPProof); + result.IsError.ShouldBeTrue(); + result.ErrorDescription.ShouldBe("Invalid 'ath' value."); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidDPoPProof); } [Fact] @@ -213,17 +213,16 @@ public async Task missing_cnf_should_fail() { _context.ValidateAccessToken = true; _context.AccessToken = "access_token"; - _context.AccessTokenClaims.Should() - .NotContain(c => c.Type == JwtClaimTypes.Confirmation); + _context.AccessTokenClaims.ShouldNotContain(c => c.Type == JwtClaimTypes.Confirmation); var accessTokenHash = HashAccessToken(); _payload["ath"] = accessTokenHash; _context.ProofToken = CreateDPoPProofToken(); var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidDPoPProof); - result.ErrorDescription.Should().Be("Missing 'cnf' value."); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidDPoPProof); + result.ErrorDescription.ShouldBe("Missing 'cnf' value."); } [Fact] @@ -240,9 +239,9 @@ public async Task empty_cnf_should_fail() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidDPoPProof); - result.ErrorDescription.Should().Be("Missing 'cnf' value."); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidDPoPProof); + result.ErrorDescription.ShouldBe("Missing 'cnf' value."); } [Fact] @@ -258,9 +257,9 @@ public async Task malformed_cnf_should_fail() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidDPoPProof); - result.ErrorDescription.Should().Be("Invalid 'cnf' value."); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidDPoPProof); + result.ErrorDescription.ShouldBe("Invalid 'cnf' value."); } [Fact] @@ -276,9 +275,9 @@ public async Task null_cnf_values_should_fail() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidDPoPProof); - result.ErrorDescription.Should().Be("Missing 'cnf' value."); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidDPoPProof); + result.ErrorDescription.ShouldBe("Missing 'cnf' value."); } [Fact] @@ -298,9 +297,9 @@ public async Task cnf_missing_jkt_should_fail() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidDPoPProof); - result.ErrorDescription.Should().Be("Invalid 'cnf' value."); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidDPoPProof); + result.ErrorDescription.ShouldBe("Invalid 'cnf' value."); } [Fact] @@ -316,9 +315,9 @@ public async Task mismatched_jkt_should_fail() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidDPoPProof); - result.ErrorDescription.Should().Be("Invalid 'cnf' value."); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidDPoPProof); + result.ErrorDescription.ShouldBe("Invalid 'cnf' value."); } private static string GenerateJwk() @@ -346,7 +345,7 @@ public async Task server_clock_skew_should_allow_tokens_outside_normal_duration( _now = _now.AddMinutes(5); var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } { @@ -357,7 +356,7 @@ public async Task server_clock_skew_should_allow_tokens_outside_normal_duration( _now = _now.AddMinutes(-5); var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } } @@ -379,11 +378,11 @@ public async Task server_clock_skew_should_extend_replay_cache() { var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } { var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); } } @@ -396,11 +395,11 @@ public async Task server_clock_skew_should_extend_replay_cache() { var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } { var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); } } } @@ -420,7 +419,7 @@ public async Task client_clock_skew_should_allow_tokens_outside_normal_duration( _now = _now.AddMinutes(5); var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } { @@ -430,7 +429,7 @@ public async Task client_clock_skew_should_allow_tokens_outside_normal_duration( _now = _now.AddMinutes(-5); var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } } @@ -450,11 +449,11 @@ public async Task client_clock_skew_should_extend_replay_cache() { var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } { var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); } } @@ -466,11 +465,11 @@ public async Task client_clock_skew_should_extend_replay_cache() { var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } { var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); } } } @@ -486,11 +485,11 @@ public async Task replayed_valid_dpop_jwt_should_fail_validation() { var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } { var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); } } @@ -501,8 +500,8 @@ public async Task empty_string_should_fail_validation() _context.ProofToken = ""; var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -513,8 +512,8 @@ public async Task malformed_dpop_jwt_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -527,8 +526,8 @@ public async Task invalid_typ_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -543,8 +542,8 @@ public async Task invalid_alg_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -558,8 +557,8 @@ public async Task private_key_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -572,8 +571,8 @@ public async Task malformed_typ_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -586,8 +585,8 @@ public async Task missing_jwk_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -600,8 +599,8 @@ public async Task jwk_with_malformed_key_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -616,8 +615,8 @@ public async Task mismatched_key_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -630,8 +629,8 @@ public async Task missing_jti_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -644,8 +643,8 @@ public async Task missing_htm_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -658,8 +657,8 @@ public async Task missing_htu_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -672,8 +671,8 @@ public async Task invalid_htu_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -686,8 +685,8 @@ public async Task missing_iat_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -700,8 +699,8 @@ public async Task malformed_iat_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -714,8 +713,8 @@ public async Task too_old_iat_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -728,8 +727,8 @@ public async Task too_new_iat_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -743,7 +742,7 @@ public async Task too_old_but_within_clock_skew_iat_should_succeed() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -758,8 +757,8 @@ public async Task too_old_past_clock_skew_iat_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -774,7 +773,7 @@ public async Task too_new_but_within_clock_skew_iat_should_succeed() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -789,8 +788,8 @@ public async Task too_new_past_clock_skew_iat_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } [Fact] @@ -804,8 +803,8 @@ public async Task missing_iat_but_nonce_provided_should_still_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); } // nonce validation @@ -818,9 +817,9 @@ public async Task missing_nonce_when_required_should_fail_validation_and_issue_n var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("use_dpop_nonce"); - result.ServerIssuedNonce.Should().NotBeNullOrEmpty(); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("use_dpop_nonce"); + result.ServerIssuedNonce.ShouldNotBeNullOrEmpty(); } [Fact] @@ -832,7 +831,7 @@ public async Task nonce_provided_when_required_should_succeed() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); _payload["nonce"] = result.ServerIssuedNonce; @@ -840,8 +839,8 @@ public async Task nonce_provided_when_required_should_succeed() result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeFalse(); - result.JsonWebKeyThumbprint.Should().Be(_JKT); + result.IsError.ShouldBeFalse(); + result.JsonWebKeyThumbprint.ShouldBe(_JKT); } [Fact] @@ -853,7 +852,7 @@ public async Task invalid_nonce_provided_when_required_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); _payload["nonce"] = result.ServerIssuedNonce + "invalid_stuff"; @@ -861,9 +860,9 @@ public async Task invalid_nonce_provided_when_required_should_fail_validation() result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); - result.ServerIssuedNonce.Should().NotBeNullOrEmpty(); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); + result.ServerIssuedNonce.ShouldNotBeNullOrEmpty(); } [Fact] @@ -875,7 +874,7 @@ public async Task expired_nonce_provided_when_required_should_fail_validation() var result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); _payload["nonce"] = result.ServerIssuedNonce; // too late @@ -885,9 +884,9 @@ public async Task expired_nonce_provided_when_required_should_fail_validation() result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); - result.ServerIssuedNonce.Should().NotBeNullOrEmpty(); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); + result.ServerIssuedNonce.ShouldNotBeNullOrEmpty(); _payload["nonce"] = result.ServerIssuedNonce; @@ -898,8 +897,8 @@ public async Task expired_nonce_provided_when_required_should_fail_validation() result = await _subject.ValidateAsync(_context); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_dpop_proof"); - result.ServerIssuedNonce.Should().NotBeNullOrEmpty(); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_dpop_proof"); + result.ServerIssuedNonce.ShouldNotBeNullOrEmpty(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/DeviceAuthorizationRequestValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/DeviceAuthorizationRequestValidation.cs index bb824e03a..04766a1c9 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/DeviceAuthorizationRequestValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/DeviceAuthorizationRequestValidation.cs @@ -9,7 +9,7 @@ using Duende.IdentityServer; using Duende.IdentityServer.Models; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Validation.Setup; using Xunit; @@ -37,7 +37,7 @@ public async Task Null_Parameter() Func act = () => validator.ValidateAsync(null, null); - await act.Should().ThrowAsync(); + await act.ShouldThrowAsync(); } [Fact] @@ -49,8 +49,8 @@ public async Task Invalid_Protocol_Client() var validator = Factory.CreateDeviceAuthorizationRequestValidator(); var result = await validator.ValidateAsync(testParameters, new ClientSecretValidationResult {Client = testClient}); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.UnauthorizedClient); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnauthorizedClient); } [Fact] @@ -62,8 +62,8 @@ public async Task Invalid_Grant_Type() var validator = Factory.CreateDeviceAuthorizationRequestValidator(); var result = await validator.ValidateAsync(testParameters, new ClientSecretValidationResult {Client = testClient}); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.UnauthorizedClient); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.UnauthorizedClient); } [Fact] @@ -75,8 +75,8 @@ public async Task Unauthorized_Scope() var validator = Factory.CreateDeviceAuthorizationRequestValidator(); var result = await validator.ValidateAsync(parameters, new ClientSecretValidationResult {Client = testClient}); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); } [Fact] @@ -88,8 +88,8 @@ public async Task Unknown_Scope() var validator = Factory.CreateDeviceAuthorizationRequestValidator(); var result = await validator.ValidateAsync(parameters, new ClientSecretValidationResult {Client = testClient}); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); } [Fact] @@ -101,17 +101,17 @@ public async Task Valid_OpenId_Request() var validator = Factory.CreateDeviceAuthorizationRequestValidator(); var result = await validator.ValidateAsync(parameters, new ClientSecretValidationResult {Client = testClient}); - result.IsError.Should().BeFalse(); - result.ValidatedRequest.IsOpenIdRequest.Should().BeTrue(); - result.ValidatedRequest.RequestedScopes.Should().Contain("openid"); + result.IsError.ShouldBeFalse(); + result.ValidatedRequest.IsOpenIdRequest.ShouldBeTrue(); + result.ValidatedRequest.RequestedScopes.ShouldContain("openid"); - result.ValidatedRequest.ValidatedResources.Resources.IdentityResources.Should().Contain(x => x.Name == "openid"); - result.ValidatedRequest.ValidatedResources.Resources.ApiResources.Should().BeEmpty(); - result.ValidatedRequest.ValidatedResources.Resources.OfflineAccess.Should().BeFalse(); + result.ValidatedRequest.ValidatedResources.Resources.IdentityResources.ShouldContain(x => x.Name == "openid"); + result.ValidatedRequest.ValidatedResources.Resources.ApiResources.ShouldBeEmpty(); + result.ValidatedRequest.ValidatedResources.Resources.OfflineAccess.ShouldBeFalse(); - result.ValidatedRequest.ValidatedResources.Resources.IdentityResources.Any().Should().BeTrue(); - result.ValidatedRequest.ValidatedResources.Resources.ApiResources.Any().Should().BeFalse(); - result.ValidatedRequest.ValidatedResources.Resources.OfflineAccess.Should().BeFalse(); + result.ValidatedRequest.ValidatedResources.Resources.IdentityResources.Any().ShouldBeTrue(); + result.ValidatedRequest.ValidatedResources.Resources.ApiResources.Any().ShouldBeFalse(); + result.ValidatedRequest.ValidatedResources.Resources.OfflineAccess.ShouldBeFalse(); } [Fact] @@ -123,19 +123,19 @@ public async Task Valid_Resource_Request() var validator = Factory.CreateDeviceAuthorizationRequestValidator(); var result = await validator.ValidateAsync(parameters, new ClientSecretValidationResult { Client = testClient }); - result.IsError.Should().BeFalse(); - result.ValidatedRequest.IsOpenIdRequest.Should().BeFalse(); - result.ValidatedRequest.RequestedScopes.Should().Contain("resource"); + result.IsError.ShouldBeFalse(); + result.ValidatedRequest.IsOpenIdRequest.ShouldBeFalse(); + result.ValidatedRequest.RequestedScopes.ShouldContain("resource"); - result.ValidatedRequest.ValidatedResources.Resources.IdentityResources.Should().BeEmpty(); - result.ValidatedRequest.ValidatedResources.Resources.ApiResources.Should().Contain(x => x.Name == "api"); - result.ValidatedRequest.ValidatedResources.Resources.ApiScopes.Should().Contain(x => x.Name == "resource"); - result.ValidatedRequest.ValidatedResources.Resources.OfflineAccess.Should().BeFalse(); + result.ValidatedRequest.ValidatedResources.Resources.IdentityResources.ShouldBeEmpty(); + result.ValidatedRequest.ValidatedResources.Resources.ApiResources.ShouldContain(x => x.Name == "api"); + result.ValidatedRequest.ValidatedResources.Resources.ApiScopes.ShouldContain(x => x.Name == "resource"); + result.ValidatedRequest.ValidatedResources.Resources.OfflineAccess.ShouldBeFalse(); - result.ValidatedRequest.ValidatedResources.Resources.IdentityResources.Any().Should().BeFalse(); - result.ValidatedRequest.ValidatedResources.Resources.ApiResources.Any().Should().BeTrue(); - result.ValidatedRequest.ValidatedResources.Resources.ApiScopes.Any().Should().BeTrue(); - result.ValidatedRequest.ValidatedResources.Resources.OfflineAccess.Should().BeFalse(); + result.ValidatedRequest.ValidatedResources.Resources.IdentityResources.Any().ShouldBeFalse(); + result.ValidatedRequest.ValidatedResources.Resources.ApiResources.Any().ShouldBeTrue(); + result.ValidatedRequest.ValidatedResources.Resources.ApiScopes.Any().ShouldBeTrue(); + result.ValidatedRequest.ValidatedResources.Resources.OfflineAccess.ShouldBeFalse(); } [Fact] @@ -147,21 +147,21 @@ public async Task Valid_Mixed_Request() var validator = Factory.CreateDeviceAuthorizationRequestValidator(); var result = await validator.ValidateAsync(parameters, new ClientSecretValidationResult { Client = testClient }); - result.IsError.Should().BeFalse(); - result.ValidatedRequest.IsOpenIdRequest.Should().BeTrue(); - result.ValidatedRequest.RequestedScopes.Should().Contain("openid"); - result.ValidatedRequest.RequestedScopes.Should().Contain("resource"); - result.ValidatedRequest.RequestedScopes.Should().Contain("offline_access"); - - result.ValidatedRequest.ValidatedResources.Resources.IdentityResources.Should().Contain(x => x.Name == "openid"); - result.ValidatedRequest.ValidatedResources.Resources.ApiResources.Should().Contain(x => x.Name == "api"); - result.ValidatedRequest.ValidatedResources.Resources.ApiScopes.Should().Contain(x => x.Name == "resource"); - result.ValidatedRequest.ValidatedResources.Resources.OfflineAccess.Should().BeTrue(); - - result.ValidatedRequest.ValidatedResources.Resources.IdentityResources.Any().Should().BeTrue(); - result.ValidatedRequest.ValidatedResources.Resources.ApiResources.Any().Should().BeTrue(); - result.ValidatedRequest.ValidatedResources.Resources.ApiScopes.Any().Should().BeTrue(); - result.ValidatedRequest.ValidatedResources.Resources.OfflineAccess.Should().BeTrue(); + result.IsError.ShouldBeFalse(); + result.ValidatedRequest.IsOpenIdRequest.ShouldBeTrue(); + result.ValidatedRequest.RequestedScopes.ShouldContain("openid"); + result.ValidatedRequest.RequestedScopes.ShouldContain("resource"); + result.ValidatedRequest.RequestedScopes.ShouldContain("offline_access"); + + result.ValidatedRequest.ValidatedResources.Resources.IdentityResources.ShouldContain(x => x.Name == "openid"); + result.ValidatedRequest.ValidatedResources.Resources.ApiResources.ShouldContain(x => x.Name == "api"); + result.ValidatedRequest.ValidatedResources.Resources.ApiScopes.ShouldContain(x => x.Name == "resource"); + result.ValidatedRequest.ValidatedResources.Resources.OfflineAccess.ShouldBeTrue(); + + result.ValidatedRequest.ValidatedResources.Resources.IdentityResources.Any().ShouldBeTrue(); + result.ValidatedRequest.ValidatedResources.Resources.ApiResources.Any().ShouldBeTrue(); + result.ValidatedRequest.ValidatedResources.Resources.ApiScopes.Any().ShouldBeTrue(); + result.ValidatedRequest.ValidatedResources.Resources.OfflineAccess.ShouldBeTrue(); } @@ -175,8 +175,8 @@ public async Task Missing_Scopes_Expect_Client_Scopes() new NameValueCollection(), new ClientSecretValidationResult { Client = testClient }); - result.IsError.Should().BeFalse(); - result.ValidatedRequest.RequestedScopes.Should().Contain(testClient.AllowedScopes); + result.IsError.ShouldBeFalse(); + result.ValidatedRequest.RequestedScopes.ShouldContain(testClient.AllowedScopes); } [Fact] @@ -190,7 +190,7 @@ public async Task Missing_Scopes_And_Client_Scopes_Empty() new NameValueCollection(), new ClientSecretValidationResult { Client = testClient }); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.AuthorizeErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.AuthorizeErrors.InvalidScope); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/DeviceCodeValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/DeviceCodeValidation.cs index f63d2ac13..d5c4e3f65 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/DeviceCodeValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/DeviceCodeValidation.cs @@ -9,7 +9,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Validation.Setup; using Xunit; @@ -49,8 +49,8 @@ public async Task DeviceCode_Missing() await validator.ValidateAsync(context); - context.Result.IsError.Should().BeTrue(); - context.Result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + context.Result.IsError.ShouldBeTrue(); + context.Result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -71,8 +71,8 @@ public async Task DeviceCode_From_Different_Client() await validator.ValidateAsync(context); - context.Result.IsError.Should().BeTrue(); - context.Result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + context.Result.IsError.ShouldBeTrue(); + context.Result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -96,8 +96,8 @@ public async Task Expired_DeviceCode() await validator.ValidateAsync(context); - context.Result.IsError.Should().BeTrue(); - context.Result.Error.Should().Be(OidcConstants.TokenErrors.ExpiredToken); + context.Result.IsError.ShouldBeTrue(); + context.Result.Error.ShouldBe(OidcConstants.TokenErrors.ExpiredToken); } [Fact] @@ -120,8 +120,8 @@ public async Task Access_Denied() await validator.ValidateAsync(context); - context.Result.IsError.Should().BeTrue(); - context.Result.Error.Should().Be(OidcConstants.TokenErrors.AccessDenied); + context.Result.IsError.ShouldBeTrue(); + context.Result.Error.ShouldBe(OidcConstants.TokenErrors.AccessDenied); } [Fact] @@ -144,8 +144,8 @@ public async Task DeviceCode_Not_Yet_Authorized() await validator.ValidateAsync(context); - context.Result.IsError.Should().BeTrue(); - context.Result.Error.Should().Be(OidcConstants.TokenErrors.AuthorizationPending); + context.Result.IsError.ShouldBeTrue(); + context.Result.Error.ShouldBe(OidcConstants.TokenErrors.AuthorizationPending); } [Fact] @@ -168,8 +168,8 @@ public async Task DeviceCode_Missing_Subject() await validator.ValidateAsync(context); - context.Result.IsError.Should().BeTrue(); - context.Result.Error.Should().Be(OidcConstants.TokenErrors.AuthorizationPending); + context.Result.IsError.ShouldBeTrue(); + context.Result.Error.ShouldBe(OidcConstants.TokenErrors.AuthorizationPending); } @@ -191,8 +191,8 @@ public async Task User_Disabled() await validator.ValidateAsync(context); - context.Result.IsError.Should().BeTrue(); - context.Result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + context.Result.IsError.ShouldBeTrue(); + context.Result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -213,8 +213,8 @@ public async Task DeviceCode_Polling_Too_Fast() await validator.ValidateAsync(context); - context.Result.IsError.Should().BeTrue(); - context.Result.Error.Should().Be(OidcConstants.TokenErrors.SlowDown); + context.Result.IsError.ShouldBeTrue(); + context.Result.Error.ShouldBe(OidcConstants.TokenErrors.SlowDown); } [Fact] @@ -235,6 +235,6 @@ public async Task Valid_DeviceCode() await validator.ValidateAsync(context); - context.Result.IsError.Should().BeFalse(); + context.Result.IsError.ShouldBeFalse(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/EndSessionRequestValidatorTests.cs b/identity-server/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/EndSessionRequestValidatorTests.cs index 5cfe9d9d9..8cce473ac 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/EndSessionRequestValidatorTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/EndSessionRequestValidation/EndSessionRequestValidatorTests.cs @@ -11,7 +11,7 @@ using Duende.IdentityServer.Extensions; using Duende.IdentityServer.Models; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Xunit; @@ -51,13 +51,13 @@ public async Task anonymous_user_when_options_require_authenticated_user_should_ var parameters = new NameValueCollection(); var result = await _subject.ValidateAsync(parameters, null); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); result = await _subject.ValidateAsync(parameters, new ClaimsPrincipal()); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); result = await _subject.ValidateAsync(parameters, new ClaimsPrincipal(new ClaimsIdentity())); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); } [Fact] @@ -78,12 +78,12 @@ public async Task valid_params_should_return_success() parameters.Add("state", "foo"); var result = await _subject.ValidateAsync(parameters, _user); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); - result.ValidatedRequest.Client.ClientId.Should().Be("client"); - result.ValidatedRequest.PostLogOutUri.Should().Be("http://client/signout-cb"); - result.ValidatedRequest.State.Should().Be("foo"); - result.ValidatedRequest.Subject.GetSubjectId().Should().Be(_user.GetSubjectId()); + result.ValidatedRequest.Client.ClientId.ShouldBe("client"); + result.ValidatedRequest.PostLogOutUri.ShouldBe("http://client/signout-cb"); + result.ValidatedRequest.State.ShouldBe("foo"); + result.ValidatedRequest.Subject.GetSubjectId().ShouldBe(_user.GetSubjectId()); } [Fact] @@ -101,8 +101,8 @@ public async Task no_post_logout_redirect_uri_should_not_use_single_registered_u parameters.Add("id_token_hint", "id_token"); var result = await _subject.ValidateAsync(parameters, _user); - result.IsError.Should().BeFalse(); - result.ValidatedRequest.PostLogOutUri.Should().BeNull(); + result.IsError.ShouldBeFalse(); + result.ValidatedRequest.PostLogOutUri.ShouldBeNull(); } [Fact] @@ -120,8 +120,8 @@ public async Task no_post_logout_redirect_uri_should_not_use_multiple_registered parameters.Add("id_token_hint", "id_token"); var result = await _subject.ValidateAsync(parameters, _user); - result.IsError.Should().BeFalse(); - result.ValidatedRequest.PostLogOutUri.Should().BeNull(); + result.IsError.ShouldBeFalse(); + result.ValidatedRequest.PostLogOutUri.ShouldBeNull(); } [Fact] @@ -142,13 +142,13 @@ public async Task post_logout_uri_fails_validation_should_not_honor_logout_uri() parameters.Add("state", "foo"); var result = await _subject.ValidateAsync(parameters, _user); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); - result.ValidatedRequest.Client.ClientId.Should().Be("client"); - result.ValidatedRequest.Subject.GetSubjectId().Should().Be(_user.GetSubjectId()); + result.ValidatedRequest.Client.ClientId.ShouldBe("client"); + result.ValidatedRequest.Subject.GetSubjectId().ShouldBe(_user.GetSubjectId()); - result.ValidatedRequest.State.Should().BeNull(); - result.ValidatedRequest.PostLogOutUri.Should().BeNull(); + result.ValidatedRequest.State.ShouldBeNull(); + result.ValidatedRequest.PostLogOutUri.ShouldBeNull(); } [Fact] @@ -169,7 +169,7 @@ public async Task subject_mismatch_should_return_error() parameters.Add("state", "foo"); var result = await _subject.ValidateAsync(parameters, _user); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); } [Fact] @@ -178,7 +178,7 @@ public async Task successful_request_should_return_inputs() var parameters = new NameValueCollection(); var result = await _subject.ValidateAsync(parameters, _user); - result.IsError.Should().BeFalse(); - result.ValidatedRequest.Raw.Should().BeSameAs(parameters); + result.IsError.ShouldBeFalse(); + result.ValidatedRequest.Raw.ShouldBeSameAs(parameters); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/GrantTypesValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/GrantTypesValidation.cs index 07a8680e1..e5e54415e 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/GrantTypesValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/GrantTypesValidation.cs @@ -5,7 +5,7 @@ using System; using System.Collections.Generic; using Duende.IdentityServer.Models; -using FluentAssertions; +using Shouldly; using Xunit; namespace UnitTests.Validation; @@ -57,7 +57,7 @@ public void forbidden_grant_type_combinations_should_throw(string type1, string Action act = () => client.AllowedGrantTypes = new[] { type1, type2 }; - act.Should().Throw(); + act.ShouldThrow(); } [Theory] @@ -71,7 +71,7 @@ public void custom_and_forbidden_grant_type_combinations_should_throw(string typ Action act = () => client.AllowedGrantTypes = new[] { "custom1", type2, "custom2", type1 }; - act.Should().Throw(); + act.ShouldThrow(); } [Fact] @@ -81,7 +81,7 @@ public void duplicate_values_should_throw() Action act = () => client.AllowedGrantTypes = new[] { "custom1", "custom2", "custom1" }; - act.Should().Throw(); + act.ShouldThrow(); } [Fact] @@ -91,7 +91,7 @@ public void null_grant_type_list_should_throw_single() Action act = () => client.AllowedGrantTypes = null; - act.Should().Throw(); + act.ShouldThrow(); } [Fact] @@ -101,7 +101,7 @@ public void grant_type_with_space_should_throw_single() Action act = () => client.AllowedGrantTypes = new[] { "custo m2" }; - act.Should().Throw(); + act.ShouldThrow(); } [Fact] @@ -111,7 +111,7 @@ public void grant_type_with_space_should_throw_multiple() Action act = () => client.AllowedGrantTypes = new[] { "custom1", "custo m2", "custom1" }; - act.Should().Throw(); + act.ShouldThrow(); } [Fact] @@ -124,7 +124,7 @@ public void adding_invalid_value_to_collection_should_throw() Action act = () => client.AllowedGrantTypes.Add("authorization_code"); - act.Should().Throw(); + act.ShouldThrow(); } [Fact] @@ -137,6 +137,6 @@ public void adding_valid_value_to_collection_should_succeed() client.AllowedGrantTypes.Add("custom"); - client.AllowedGrantTypes.Count.Should().Be(2); + client.AllowedGrantTypes.Count.ShouldBe(2); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/IdentityProviderConfigurationValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/IdentityProviderConfigurationValidation.cs index f52791e02..b84bb346d 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/IdentityProviderConfigurationValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/IdentityProviderConfigurationValidation.cs @@ -6,7 +6,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Models; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Xunit; @@ -43,7 +43,7 @@ public async Task correctly_populated_idp_should_succeed() var ctx = new IdentityProviderConfigurationValidationContext(idp); await _validator.ValidateAsync(ctx); - ctx.IsValid.Should().BeTrue(); + ctx.IsValid.ShouldBeTrue(); } [Fact] @@ -58,8 +58,8 @@ public async Task missing_type_registration_should_fail() var ctx = new IdentityProviderConfigurationValidationContext(idp); await _validator.ValidateAsync(ctx); - ctx.IsValid.Should().BeFalse(); - ctx.ErrorMessage.Should().Contain("registered"); + ctx.IsValid.ShouldBeFalse(); + ctx.ErrorMessage.ShouldContain("registered"); } [Fact] @@ -76,7 +76,7 @@ public async Task custom_type_registration_should_succeed() var ctx = new IdentityProviderConfigurationValidationContext(idp); await _validator.ValidateAsync(ctx); - ctx.IsValid.Should().BeTrue(); + ctx.IsValid.ShouldBeTrue(); } [Fact] @@ -96,8 +96,8 @@ public async Task missing_scheme_should_fail() var ctx = new IdentityProviderConfigurationValidationContext(idp); await _validator.ValidateAsync(ctx); - ctx.IsValid.Should().BeFalse(); - ctx.ErrorMessage.ToLowerInvariant().Should().Contain("scheme"); + ctx.IsValid.ShouldBeFalse(); + ctx.ErrorMessage.ToLowerInvariant().ShouldContain("scheme"); } [Fact] @@ -117,8 +117,8 @@ public async Task missing_clientid_should_fail() var ctx = new IdentityProviderConfigurationValidationContext(idp); await _validator.ValidateAsync(ctx); - ctx.IsValid.Should().BeFalse(); - ctx.ErrorMessage.ToLowerInvariant().Should().Contain("clientid"); + ctx.IsValid.ShouldBeFalse(); + ctx.ErrorMessage.ToLowerInvariant().ShouldContain("clientid"); } [Fact] @@ -139,7 +139,7 @@ public async Task missing_secret_should_be_allowed() var ctx = new IdentityProviderConfigurationValidationContext(idp); await _validator.ValidateAsync(ctx); - ctx.IsValid.Should().BeTrue(); + ctx.IsValid.ShouldBeTrue(); } [Fact] @@ -159,8 +159,8 @@ public async Task missing_authority_should_fail() var ctx = new IdentityProviderConfigurationValidationContext(idp); await _validator.ValidateAsync(ctx); - ctx.IsValid.Should().BeFalse(); - ctx.ErrorMessage.ToLowerInvariant().Should().Contain("authority"); + ctx.IsValid.ShouldBeFalse(); + ctx.ErrorMessage.ToLowerInvariant().ShouldContain("authority"); } [Fact] @@ -180,8 +180,8 @@ public async Task missing_responsetype_should_fail() var ctx = new IdentityProviderConfigurationValidationContext(idp); await _validator.ValidateAsync(ctx); - ctx.IsValid.Should().BeFalse(); - ctx.ErrorMessage.ToLowerInvariant().Should().Contain("responsetype"); + ctx.IsValid.ShouldBeFalse(); + ctx.ErrorMessage.ToLowerInvariant().ShouldContain("responsetype"); } [Fact] @@ -201,8 +201,8 @@ public async Task missing_scope_should_fail() var ctx = new IdentityProviderConfigurationValidationContext(idp); await _validator.ValidateAsync(ctx); - ctx.IsValid.Should().BeFalse(); - ctx.ErrorMessage.ToLowerInvariant().Should().Contain("scope"); + ctx.IsValid.ShouldBeFalse(); + ctx.ErrorMessage.ToLowerInvariant().ShouldContain("scope"); } [Fact] @@ -222,6 +222,6 @@ public async Task when_implicit_flow_missing_clientid_should_succeed() var ctx = new IdentityProviderConfigurationValidationContext(idp); await _validator.ValidateAsync(ctx); - ctx.IsValid.Should().BeTrue(); + ctx.IsValid.ShouldBeTrue(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/IdentityTokenValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/IdentityTokenValidation.cs index 14cd2ffce..954170a2d 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/IdentityTokenValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/IdentityTokenValidation.cs @@ -7,7 +7,7 @@ using System.Text; using System.Text.Json; using System.Threading.Tasks; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Validation.Setup; using Xunit; @@ -34,7 +34,7 @@ public async Task Valid_IdentityToken_DefaultKeyType() var validator = Factory.CreateTokenValidator(); var result = await validator.ValidateIdentityTokenAsync(jwt, "roclient"); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -46,7 +46,7 @@ public async Task Valid_IdentityToken_DefaultKeyType_no_ClientId_supplied() var validator = Factory.CreateTokenValidator(); var result = await validator.ValidateIdentityTokenAsync(jwt, "roclient"); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -58,7 +58,7 @@ public async Task Valid_IdentityToken_no_ClientId_supplied() var validator = Factory.CreateTokenValidator(); var result = await validator.ValidateIdentityTokenAsync(jwt); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -70,8 +70,8 @@ public async Task IdentityToken_InvalidClientId() var validator = Factory.CreateTokenValidator(); var result = await validator.ValidateIdentityTokenAsync(jwt, "invalid"); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.ProtectedResourceErrors.InvalidToken); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); } [Fact] @@ -83,8 +83,8 @@ public async Task IdentityToken_Too_Long() var validator = Factory.CreateTokenValidator(); var result = await validator.ValidateIdentityTokenAsync(jwt, "roclient"); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.ProtectedResourceErrors.InvalidToken); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); } [Fact] @@ -102,6 +102,6 @@ public async Task claims_that_collide_with_token_validation_should_be_ignored() var payload = jwt.Split('.')[1]; var json = Encoding.UTF8.GetString(Base64Url.Decode(payload)); var values = JsonSerializer.Deserialize>(json); - values["aud"].GetString().Should().Be("roclient"); + values["aud"].GetString().ShouldBe("roclient"); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/IntrospectionRequestValidatorTests.cs b/identity-server/test/IdentityServer.UnitTests/Validation/IntrospectionRequestValidatorTests.cs index e8a9040a7..d4cd1039d 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/IntrospectionRequestValidatorTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/IntrospectionRequestValidatorTests.cs @@ -11,7 +11,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using UnitTests.Validation.Setup; using Xunit; @@ -64,17 +64,17 @@ public async Task valid_token_should_successfully_validate() } ); - result.IsError.Should().Be(false); - result.IsActive.Should().Be(true); - result.Claims.Count().Should().Be(6); - result.Token.Should().Be(handle); + result.IsError.ShouldBe(false); + result.IsActive.ShouldBe(true); + result.Claims.Count().ShouldBe(6); + result.Token.ShouldBe(handle); var claimTypes = result.Claims.Select(c => c.Type).ToList(); - claimTypes.Should().Contain("iss"); - claimTypes.Should().Contain("scope"); - claimTypes.Should().Contain("iat"); - claimTypes.Should().Contain("nbf"); - claimTypes.Should().Contain("exp"); + claimTypes.ShouldContain("iss"); + claimTypes.ShouldContain("scope"); + claimTypes.ShouldContain("iat"); + claimTypes.ShouldContain("nbf"); + claimTypes.ShouldContain("exp"); } @@ -90,11 +90,11 @@ public async Task missing_token_should_error() Api = new ApiResource("api") }); - result.IsError.Should().Be(true); - result.Error.Should().Be("missing_token"); - result.IsActive.Should().Be(false); - result.Claims.Should().BeNull(); - result.Token.Should().BeNull(); + result.IsError.ShouldBe(true); + result.Error.ShouldBe("missing_token"); + result.IsActive.ShouldBe(false); + result.Claims.ShouldBeNull(); + result.Token.ShouldBeNull(); } [Fact] @@ -112,10 +112,10 @@ public async Task invalid_token_should_return_inactive() Api = new ApiResource("api") }); - result.IsError.Should().Be(false); - result.IsActive.Should().Be(false); - result.Claims.Should().BeNull(); - result.Token.Should().Be("invalid"); + result.IsError.ShouldBe(false); + result.IsActive.ShouldBe(false); + result.Claims.ShouldBeNull(); + result.Token.ShouldBe("invalid"); } [Theory] @@ -152,11 +152,9 @@ public async Task protocol_claims_should_not_be_duplicated( } ); - result.Claims.Where(c => c.Type == claimType) - .Should() - .HaveCount(1) - .And - .Contain(c => c.Value == expectedValueSelector(token)); + var claims = result.Claims.Where(c => c.Type == claimType).ToArray(); + claims.Length.ShouldBe(1); + claims.ShouldContain(c => c.Value == expectedValueSelector(token)); } public static IEnumerable DuplicateClaimTestCases() diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/IsLocalUrlTests.cs b/identity-server/test/IdentityServer.UnitTests/Validation/IsLocalUrlTests.cs index c135b3584..e87a5e5fd 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/IsLocalUrlTests.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/IsLocalUrlTests.cs @@ -4,7 +4,7 @@ using Duende.IdentityServer.Extensions; using Duende.IdentityServer.Services; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Microsoft.Extensions.Logging; using UnitTests.Common; using UnitTests.Endpoints.Authorize; @@ -69,11 +69,11 @@ public async Task GetAuthorizationContextAsync(string returnUrl, bool expected) var actual = await interactionService.GetAuthorizationContextAsync(returnUrl); if (expected) { - actual.Should().NotBeNull(); + actual.ShouldNotBeNull(); } else { - actual.Should().BeNull(); + actual.ShouldBeNull(); } } @@ -81,7 +81,7 @@ public async Task GetAuthorizationContextAsync(string returnUrl, bool expected) [MemberData(nameof(TestCases))] public void IsLocalUrl(string returnUrl, bool expected) { - returnUrl.IsLocalUrl().Should().Be(expected); + returnUrl.IsLocalUrl().ShouldBe(expected); } [Theory] @@ -96,11 +96,11 @@ public void GetIdentityServerRelativeUrl(string returnUrl, bool expected) var actual = serverUrls.GetIdentityServerRelativeUrl(returnUrl); if (expected) { - actual.Should().NotBeNull(); + actual.ShouldNotBeNull(); } else { - actual.Should().BeNull(); + actual.ShouldBeNull(); } } @@ -112,11 +112,11 @@ public async Task OidcReturnUrlParser_ParseAsync(string returnUrl, bool expected var actual = await oidcParser.ParseAsync(returnUrl); if (expected) { - actual.Should().NotBeNull(); + actual.ShouldNotBeNull(); } else { - actual.Should().BeNull(); + actual.ShouldBeNull(); } } @@ -125,7 +125,7 @@ public async Task OidcReturnUrlParser_ParseAsync(string returnUrl, bool expected public void OidcReturnUrlParser_IsValidReturnUrl(string returnUrl, bool expected) { var oidcParser = GetOidcReturnUrlParser(); - oidcParser.IsValidReturnUrl(returnUrl).Should().Be(expected); + oidcParser.IsValidReturnUrl(returnUrl).ShouldBe(expected); } @@ -134,7 +134,7 @@ public void OidcReturnUrlParser_IsValidReturnUrl(string returnUrl, bool expected public void ReturnUrlParser_IsValidReturnUrl(string returnUrl, bool expected) { var parser = GetReturnUrlParser(); - parser.IsValidReturnUrl(returnUrl).Should().Be(expected); + parser.IsValidReturnUrl(returnUrl).ShouldBe(expected); } [Theory] @@ -145,11 +145,11 @@ public async Task ReturnUrlParser_ParseAsync(string returnUrl, bool expected) var actual = await parser.ParseAsync(returnUrl); if (expected) { - actual.Should().NotBeNull(); + actual.ShouldNotBeNull(); } else { - actual.Should().BeNull(); + actual.ShouldBeNull(); } } diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/ResourceValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/ResourceValidation.cs index 170e6f43d..fac7c34fb 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/ResourceValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/ResourceValidation.cs @@ -8,7 +8,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Validation.Setup; using Xunit; @@ -127,8 +127,8 @@ public async Task Only_Offline_Access_Requested() Scopes = new[] { "offline_access" } }); - result.Succeeded.Should().BeFalse(); - result.InvalidScopes.Should().Contain("offline_access"); + result.Succeeded.ShouldBeFalse(); + result.InvalidScopes.ShouldContain("offline_access"); } [Fact] @@ -142,8 +142,8 @@ public async Task All_Scopes_Valid() Scopes = new[] { "openid", "scope1" } }); - result.Succeeded.Should().BeTrue(); - result.InvalidScopes.Should().BeEmpty(); + result.Succeeded.ShouldBeTrue(); + result.InvalidScopes.ShouldBeEmpty(); } [Fact] @@ -158,9 +158,9 @@ public async Task Invalid_Scope() Scopes = new[] { "openid", "email", "scope1", "unknown" } }); - result.Succeeded.Should().BeFalse(); - result.InvalidScopes.Should().Contain("unknown"); - result.InvalidScopes.Should().Contain("email"); + result.Succeeded.ShouldBeFalse(); + result.InvalidScopes.ShouldContain("unknown"); + result.InvalidScopes.ShouldContain("email"); } { var validator = Factory.CreateResourceValidator(_subject); @@ -170,8 +170,8 @@ public async Task Invalid_Scope() Scopes = new[] { "openid", "scope1", "scope2" } }); - result.Succeeded.Should().BeFalse(); - result.InvalidScopes.Should().Contain("scope2"); + result.Succeeded.ShouldBeFalse(); + result.InvalidScopes.ShouldContain("scope2"); } { var validator = Factory.CreateResourceValidator(_subject); @@ -181,8 +181,8 @@ public async Task Invalid_Scope() Scopes = new[] { "openid", "email", "scope1" } }); - result.Succeeded.Should().BeFalse(); - result.InvalidScopes.Should().Contain("email"); + result.Succeeded.ShouldBeFalse(); + result.InvalidScopes.ShouldContain("email"); } } @@ -197,8 +197,8 @@ public async Task Disabled_Scope() Scopes = new[] { "openid", "scope1", "disabled_scope" } }); - result.Succeeded.Should().BeFalse(); - result.InvalidScopes.Should().Contain("disabled_scope"); + result.Succeeded.ShouldBeFalse(); + result.InvalidScopes.ShouldContain("disabled_scope"); } [Fact] @@ -212,8 +212,8 @@ public async Task All_Scopes_Allowed_For_Restricted_Client() Scopes = new[] { "openid", "scope1" } }); - result.Succeeded.Should().BeTrue(); - result.InvalidScopes.Should().BeEmpty(); + result.Succeeded.ShouldBeTrue(); + result.InvalidScopes.ShouldBeEmpty(); } [Fact] @@ -227,9 +227,9 @@ public async Task Restricted_Scopes() Scopes = new[] { "openid", "email", "scope1", "scope2" } }); - result.Succeeded.Should().BeFalse(); - result.InvalidScopes.Should().Contain("email"); - result.InvalidScopes.Should().Contain("scope2"); + result.Succeeded.ShouldBeFalse(); + result.InvalidScopes.ShouldContain("email"); + result.InvalidScopes.ShouldContain("scope2"); } [Fact] @@ -243,10 +243,10 @@ public async Task Contains_Resource_and_Identity_Scopes() Scopes = new[] { "openid", "scope1" } }); - result.Succeeded.Should().BeTrue(); - result.Resources.IdentityResources.Select(x => x.Name).Should().BeEquivalentTo(new[] { "openid" }); - result.Resources.ApiScopes.Select(x => x.Name).Should().BeEquivalentTo(new[] { "scope1" }); - result.Resources.ApiResources.Select(x => x.Name).Should().BeEquivalentTo(new[] { "resource1" }); + result.Succeeded.ShouldBeTrue(); + result.Resources.IdentityResources.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "openid" }); + result.Resources.ApiScopes.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "scope1" }); + result.Resources.ApiResources.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "resource1" }); } [Fact] @@ -260,10 +260,10 @@ public async Task Contains_Resource_Scopes_Only() Scopes = new[] { "scope1" } }); - result.Succeeded.Should().BeTrue(); - result.Resources.IdentityResources.Should().BeEmpty(); - result.Resources.ApiScopes.Select(x => x.Name).Should().Contain("scope1"); - result.Resources.ApiResources.Select(x => x.Name).Should().BeEquivalentTo(new[] { "resource1" }); + result.Succeeded.ShouldBeTrue(); + result.Resources.IdentityResources.ShouldBeEmpty(); + result.Resources.ApiScopes.Select(x => x.Name).ShouldContain("scope1"); + result.Resources.ApiResources.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "resource1" }); } [Fact] @@ -277,10 +277,10 @@ public async Task Contains_Identity_Scopes_Only() Scopes = new[] { "openid" } }); - result.Succeeded.Should().BeTrue(); - result.Resources.IdentityResources.SelectMany(x => x.Name).Should().Contain("openid"); - result.Resources.ApiResources.Should().BeEmpty(); - result.Resources.ApiResources.Should().BeEmpty(); + result.Succeeded.ShouldBeTrue(); + result.Resources.IdentityResources.Select(x => x.Name).ShouldContain("openid"); + result.Resources.ApiResources.ShouldBeEmpty(); + result.Resources.ApiResources.ShouldBeEmpty(); } [Fact] @@ -301,11 +301,11 @@ public async Task Scope_matches_multipls_apis_should_succeed() Scopes = new[] { "s" } }); - result.Succeeded.Should().BeTrue(); - result.Resources.ApiResources.Count.Should().Be(2); - result.Resources.ApiResources.Select(x => x.Name).Should().BeEquivalentTo(new[] { "r1", "r2" }); - result.RawScopeValues.Count().Should().Be(1); - result.RawScopeValues.Should().BeEquivalentTo(new[] { "s" }); + result.Succeeded.ShouldBeTrue(); + result.Resources.ApiResources.Count.ShouldBe(2); + result.Resources.ApiResources.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "r1", "r2" }); + result.RawScopeValues.Count().ShouldBe(1); + result.RawScopeValues.ShouldBeEquivalentTo(new[] { "s" }); } // resource indicators @@ -322,10 +322,10 @@ public async Task should_include_all_resources_that_match_scope() ResourceIndicators = new[] { "isolated1" }, }); - result.Succeeded.Should().BeTrue(); - result.Resources.ApiResources.Select(x => x.Name).Should().BeEquivalentTo(new[] { "resource1", "isolated1" }); - result.Resources.ApiScopes.Select(x => x.Name).Should().BeEquivalentTo(new[] { "scope1" }); - result.Resources.OfflineAccess.Should().BeTrue(); + result.Succeeded.ShouldBeTrue(); + result.Resources.ApiResources.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "resource1", "isolated1" }); + result.Resources.ApiScopes.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "scope1" }); + result.Resources.OfflineAccess.ShouldBeTrue(); } [Fact] @@ -339,9 +339,9 @@ public async Task no_resource_indicator_should_exclude_apis_marked_as_isolated() Scopes = new[] { "scope1" }, }); - result.Succeeded.Should().BeTrue(); - result.Resources.ApiResources.Select(x => x.Name).Should().BeEquivalentTo(new[] { "resource1" }); - result.Resources.ApiScopes.Select(x => x.Name).Should().BeEquivalentTo(new[] { "scope1" }); + result.Succeeded.ShouldBeTrue(); + result.Resources.ApiResources.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "resource1" }); + result.Resources.ApiScopes.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "scope1" }); } [Fact] @@ -356,9 +356,9 @@ public async Task invalid_resource_should_fail() ResourceIndicators = new[] { "invalid" } }); - result.Succeeded.Should().BeFalse(); - result.InvalidScopes.Should().BeEmpty(); - result.InvalidResourceIndicators.Should().BeEquivalentTo(new[] { "invalid" }); + result.Succeeded.ShouldBeFalse(); + result.InvalidScopes.ShouldBeEmpty(); + result.InvalidResourceIndicators.ShouldBeEquivalentTo(new[] { "invalid" }); } [Fact] @@ -373,9 +373,9 @@ public async Task resource_without_matching_scope_in_request_should_fail() ResourceIndicators = new[] { "resource3" } }); - result.Succeeded.Should().BeFalse(); - result.InvalidScopes.Should().BeEmpty(); - result.InvalidResourceIndicators.Should().BeEquivalentTo(new[] { "resource3" }); + result.Succeeded.ShouldBeFalse(); + result.InvalidScopes.ShouldBeEmpty(); + result.InvalidResourceIndicators.ShouldBeEquivalentTo(new[] { "resource3" }); } @@ -408,36 +408,36 @@ public void FilterByResourceIndicator_should_filter_properly() { var result = subject.FilterByResourceIndicator(null); - result.Resources.ApiResources.Select(x => x.Name).Should().BeEquivalentTo(new[] { "resource1", "resource2" }); - result.Resources.ApiScopes.Select(x => x.Name).Should().BeEquivalentTo(new[] { "scope1", "scope2", "scope3" }); - result.Resources.OfflineAccess.Should().BeFalse(); + result.Resources.ApiResources.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "resource1", "resource2" }); + result.Resources.ApiScopes.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "scope1", "scope2", "scope3" }); + result.Resources.OfflineAccess.ShouldBeFalse(); } { resources.OfflineAccess = true; var result = subject.FilterByResourceIndicator(null); - result.Resources.ApiResources.Select(x => x.Name).Should().BeEquivalentTo(new[] { "resource1", "resource2" }); - result.Resources.ApiScopes.Select(x => x.Name).Should().BeEquivalentTo(new[] { "scope1", "scope2", "scope3" }); - result.Resources.OfflineAccess.Should().BeTrue(); + result.Resources.ApiResources.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "resource1", "resource2" }); + result.Resources.ApiScopes.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "scope1", "scope2", "scope3" }); + result.Resources.OfflineAccess.ShouldBeTrue(); } { var result = subject.FilterByResourceIndicator("resource1"); - result.Resources.ApiResources.Select(x => x.Name).Should().BeEquivalentTo(new[] { "resource1" }); - result.Resources.ApiScopes.Select(x => x.Name).Should().BeEquivalentTo(new[] { "scope1", "scope2" }); + result.Resources.ApiResources.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "resource1" }); + result.Resources.ApiScopes.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "scope1", "scope2" }); } { var result = subject.FilterByResourceIndicator("resource2"); - result.Resources.ApiResources.Select(x => x.Name).Should().BeEquivalentTo(new[] { "resource2" }); - result.Resources.ApiScopes.Select(x => x.Name).Should().BeEquivalentTo(new[] { "scope1" }); + result.Resources.ApiResources.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "resource2" }); + result.Resources.ApiScopes.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "scope1" }); } { var result = subject.FilterByResourceIndicator("isolated1"); - result.Resources.ApiResources.Select(x => x.Name).Should().BeEquivalentTo(new[] { "isolated1" }); - result.Resources.ApiScopes.Select(x => x.Name).Should().BeEquivalentTo(new[] { "scope2", "scope3" }); + result.Resources.ApiResources.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "isolated1" }); + result.Resources.ApiScopes.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "scope2", "scope3" }); } { var result = subject.FilterByResourceIndicator("isolated2"); - result.Resources.ApiResources.Select(x => x.Name).Should().BeEquivalentTo(new[] { "isolated2" }); - result.Resources.ApiScopes.Select(x => x.Name).Should().BeEquivalentTo(new[] { "scope3" }); + result.Resources.ApiResources.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "isolated2" }); + result.Resources.ApiScopes.Select(x => x.Name).ShouldBeEquivalentTo(new[] { "scope3" }); } } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/ResponseTypeEqualityComparison.cs b/identity-server/test/IdentityServer.UnitTests/Validation/ResponseTypeEqualityComparison.cs index 4648100a6..ee077fdb1 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/ResponseTypeEqualityComparison.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/ResponseTypeEqualityComparison.cs @@ -3,7 +3,7 @@ using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Xunit; namespace UnitTests.Validation; @@ -33,7 +33,7 @@ public void Both_null() string y = null; var result = comparer.Equals(x, y); var expected = (x == y); - result.Should().Be(expected); + result.ShouldBe(expected); } [Fact] @@ -44,7 +44,7 @@ public void Left_null_other_not() string y = string.Empty; var result = comparer.Equals(x, y); var expected = (x == y); - result.Should().Be(expected); + result.ShouldBe(expected); } [Fact] @@ -55,7 +55,7 @@ public void Right_null_other_not() string y = null; var result = comparer.Equals(x, y); var expected = (x == y); - result.Should().Be(expected); + result.ShouldBe(expected); } [Fact] @@ -66,7 +66,7 @@ public void token_token() string y = "token"; var result = comparer.Equals(x, y); var expected = (x == y); - result.Should().Be(expected); + result.ShouldBe(expected); } [Fact] @@ -77,7 +77,7 @@ public void id_token_id_token() string y = "id_token"; var result = comparer.Equals(x, y); var expected = (x == y); - result.Should().Be(expected); + result.ShouldBe(expected); } [Fact] @@ -88,7 +88,7 @@ public void id_token_token() string y = "token"; var result = comparer.Equals(x, y); var expected = (x == y); - result.Should().Be(expected); + result.ShouldBe(expected); } } @@ -106,7 +106,7 @@ public void id_token_token_both_ways() string x = "id_token token"; string y = "token id_token"; var result = comparer.Equals(x, y); - result.Should().BeTrue(); + result.ShouldBeTrue(); } [Fact] @@ -116,7 +116,7 @@ public void code_id_token_both_ways() string x = "code id_token"; string y = "id_token code"; var result = comparer.Equals(x, y); - result.Should().BeTrue(); + result.ShouldBeTrue(); } [Fact] @@ -126,7 +126,7 @@ public void code_token_both_ways() string x = "code token"; string y = "token code"; var result = comparer.Equals(x, y); - result.Should().BeTrue(); + result.ShouldBeTrue(); } [Fact] @@ -136,7 +136,7 @@ public void code_id_token_token_combo1() string x = "code id_token token"; string y = "id_token code token"; var result = comparer.Equals(x, y); - result.Should().BeTrue(); + result.ShouldBeTrue(); } [Fact] @@ -146,7 +146,7 @@ public void code_id_token_token_combo2() string x = "code id_token token"; string y = "token id_token code"; var result = comparer.Equals(x, y); - result.Should().BeTrue(); + result.ShouldBeTrue(); } [Fact] @@ -156,7 +156,7 @@ public void code_id_token_token_missing_code() string x = "code id_token token"; string y = "id_token token"; var result = comparer.Equals(x, y); - result.Should().BeFalse(); + result.ShouldBeFalse(); } [Fact] @@ -166,7 +166,7 @@ public void code_id_token_token_missing_code_and_token() string x = "code id_token token"; string y = "id_token"; var result = comparer.Equals(x, y); - result.Should().BeFalse(); + result.ShouldBeFalse(); } [Fact] @@ -176,7 +176,7 @@ public void Totally_different_words() string x = "blerg smoo"; string y = "token code"; var result = comparer.Equals(x, y); - result.Should().BeFalse(); + result.ShouldBeFalse(); } [Fact] @@ -186,7 +186,7 @@ public void Same_length_different_count() string x = "code id_token token"; string y = "tokenizer bleegerfi"; var result = comparer.Equals(x, y); - result.Should().BeFalse(); + result.ShouldBeFalse(); } } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/RevocationRequestValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/RevocationRequestValidation.cs index c51967588..fd8bd78d6 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/RevocationRequestValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/RevocationRequestValidation.cs @@ -8,7 +8,7 @@ using Duende.IdentityServer; using Duende.IdentityServer.Models; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using Xunit; @@ -56,8 +56,8 @@ public async Task Empty_Parameters() var result = await _validator.ValidateRequestAsync(parameters, _client); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidRequest); } [Fact] @@ -71,8 +71,8 @@ public async Task Missing_Token_Valid_Hint() var result = await _validator.ValidateRequestAsync(parameters, _client); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidRequest); } [Fact] @@ -87,9 +87,9 @@ public async Task Valid_Token_And_AccessTokenHint() var result = await _validator.ValidateRequestAsync(parameters, _client); - result.IsError.Should().BeFalse(); - result.Token.Should().Be("foo"); - result.TokenTypeHint.Should().Be("access_token"); + result.IsError.ShouldBeFalse(); + result.Token.ShouldBe("foo"); + result.TokenTypeHint.ShouldBe("access_token"); } [Fact] @@ -104,9 +104,9 @@ public async Task Valid_Token_and_RefreshTokenHint() var result = await _validator.ValidateRequestAsync(parameters, _client); - result.IsError.Should().BeFalse(); - result.Token.Should().Be("foo"); - result.TokenTypeHint.Should().Be("refresh_token"); + result.IsError.ShouldBeFalse(); + result.Token.ShouldBe("foo"); + result.TokenTypeHint.ShouldBe("refresh_token"); } [Fact] @@ -120,9 +120,9 @@ public async Task Valid_Token_And_Missing_Hint() var result = await _validator.ValidateRequestAsync(parameters, _client); - result.IsError.Should().BeFalse(); - result.Token.Should().Be("foo"); - result.TokenTypeHint.Should().BeNull(); + result.IsError.ShouldBeFalse(); + result.Token.ShouldBe("foo"); + result.TokenTypeHint.ShouldBeNull(); } [Fact] @@ -137,7 +137,7 @@ public async Task Valid_Token_And_Invalid_Hint() var result = await _validator.ValidateRequestAsync(parameters, _client); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(Constants.RevocationErrors.UnsupportedTokenType); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(Constants.RevocationErrors.UnsupportedTokenType); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/BasicAuthenticationCredentialParsing.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/BasicAuthenticationCredentialParsing.cs index b78f30ca2..4c08005bd 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/BasicAuthenticationCredentialParsing.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/BasicAuthenticationCredentialParsing.cs @@ -10,7 +10,7 @@ using Duende.IdentityServer; using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; @@ -39,7 +39,7 @@ public async Task EmptyContext() var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } [Fact] @@ -55,9 +55,9 @@ public async Task Valid_BasicAuthentication_Request() var secret = await _parser.ParseAsync(context); - secret.Type.Should().Be(IdentityServerConstants.ParsedSecretTypes.SharedSecret); - secret.Id.Should().Be("client"); - secret.Credential.Should().Be("secret"); + secret.Type.ShouldBe(IdentityServerConstants.ParsedSecretTypes.SharedSecret); + secret.Id.ShouldBe("client"); + secret.Credential.ShouldBe("secret"); } [Theory] @@ -82,9 +82,9 @@ public async Task Valid_BasicAuthentication_Request_in_various_Formats_Manual(st var secret = await _parser.ParseAsync(context); - secret.Type.Should().Be(IdentityServerConstants.ParsedSecretTypes.SharedSecret); - secret.Id.Should().Be(userName); - secret.Credential.Should().Be(password); + secret.Type.ShouldBe(IdentityServerConstants.ParsedSecretTypes.SharedSecret); + secret.Id.ShouldBe(userName); + secret.Credential.ShouldBe(password); } [Theory] @@ -107,9 +107,9 @@ public async Task Valid_BasicAuthentication_Request_in_various_Formats_IdentityM var secret = await _parser.ParseAsync(context); - secret.Type.Should().Be(IdentityServerConstants.ParsedSecretTypes.SharedSecret); - secret.Id.Should().Be(userName); - secret.Credential.Should().Be(password); + secret.Type.ShouldBe(IdentityServerConstants.ParsedSecretTypes.SharedSecret); + secret.Id.ShouldBe(userName); + secret.Credential.ShouldBe(password); } [Fact] @@ -124,9 +124,9 @@ public async Task Valid_BasicAuthentication_Request_With_UserName_Only_And_Colon var secret = await _parser.ParseAsync(context); - secret.Type.Should().Be(IdentityServerConstants.ParsedSecretTypes.NoSecret); - secret.Id.Should().Be("client"); - secret.Credential.Should().BeNull(); + secret.Type.ShouldBe(IdentityServerConstants.ParsedSecretTypes.NoSecret); + secret.Id.ShouldBe("client"); + secret.Credential.ShouldBeNull(); } [Fact] @@ -139,7 +139,7 @@ public async Task BasicAuthentication_Request_With_Empty_Basic_Header() var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } [Fact] @@ -156,7 +156,7 @@ public async Task Valid_BasicAuthentication_Request_ClientId_Too_Long() context.Request.Headers.Append("Authorization", new StringValues(headerValue)); var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } [Fact] @@ -173,7 +173,7 @@ public async Task Valid_BasicAuthentication_Request_ClientSecret_Too_Long() context.Request.Headers.Append("Authorization", new StringValues(headerValue)); var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } [Theory] @@ -202,8 +202,8 @@ public async Task Valid_BasicAuthentication_Request_Maximum_Url_Encoded_Values_S context.Request.Headers.Append("Authorization", new StringValues(headerValue)); var secret = await parser.ParseAsync(context); - secret.Id.Should().Be(clientId); - secret.Credential.Should().Be(clientSecret); + secret.Id.ShouldBe(clientId); + secret.Credential.ShouldBe(clientSecret); } private static BasicAuthenticationSecretParser CreateParser(int maxLength) @@ -246,7 +246,7 @@ public async Task Valid_BasicAuthentication_Request_Authorization_Header_Too_Lon context.Request.Headers.Append("Authorization", new StringValues(headerValue)); var secret = await parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } [Fact] @@ -259,7 +259,7 @@ public async Task BasicAuthentication_Request_With_Empty_Basic_Header_Variation( var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } [Fact] @@ -272,7 +272,7 @@ public async Task BasicAuthentication_Request_With_Unknown_Scheme() var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } [Fact] @@ -285,7 +285,7 @@ public async Task BasicAuthentication_Request_With_Malformed_Credentials_NoBase6 var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } [Fact] @@ -300,6 +300,6 @@ public async Task BasicAuthentication_Request_With_Malformed_Credentials_Base64_ var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/ClientAssertionSecretParsing.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/ClientAssertionSecretParsing.cs index fe6bf184c..b98321901 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/ClientAssertionSecretParsing.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/ClientAssertionSecretParsing.cs @@ -10,7 +10,7 @@ using Duende.IdentityServer; using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; @@ -38,7 +38,7 @@ public async Task EmptyContext() var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } [Fact] @@ -56,10 +56,10 @@ public async Task Valid_ClientAssertion() var secret = await _parser.ParseAsync(context); - secret.Should().NotBeNull(); - secret.Type.Should().Be(IdentityServerConstants.ParsedSecretTypes.JwtBearer); - secret.Id.Should().Be("client"); - secret.Credential.Should().Be(tokenString); + secret.ShouldNotBeNull(); + secret.Type.ShouldBe(IdentityServerConstants.ParsedSecretTypes.JwtBearer); + secret.Id.ShouldBe("client"); + secret.Credential.ShouldBe(tokenString); } [Fact] @@ -74,7 +74,7 @@ public async Task Missing_ClientAssertionType() var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } [Fact] @@ -89,7 +89,7 @@ public async Task Missing_ClientAssertion() var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } [Fact] @@ -103,7 +103,7 @@ public async Task Malformed_PostBody() var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } [Fact] @@ -119,7 +119,7 @@ public async Task ClientId_TooLong() var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } [Fact] @@ -135,6 +135,6 @@ public async Task ClientAssertion_TooLong() var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/ClientSecretValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/ClientSecretValidation.cs index 16eb5882e..40c3f7961 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/ClientSecretValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/ClientSecretValidation.cs @@ -5,7 +5,7 @@ using System.IO; using System.Text; using System.Threading.Tasks; -using FluentAssertions; +using Shouldly; using UnitTests.Validation.Setup; using Microsoft.AspNetCore.Http; using Xunit; @@ -30,8 +30,8 @@ public async Task confidential_client_with_correct_secret_should_be_able_to_requ var result = await validator.ValidateAsync(context); - result.IsError.Should().BeFalse(); - result.Client.ClientId.Should().Be("roclient"); + result.IsError.ShouldBeFalse(); + result.Client.ClientId.ShouldBe("roclient"); } [Fact] @@ -48,7 +48,7 @@ public async Task confidential_client_with_incorrect_secret_should_not_be_able_t var result = await validator.ValidateAsync(context); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); } [Fact] @@ -65,9 +65,9 @@ public async Task public_client_without_secret_should_be_able_to_request_token() var result = await validator.ValidateAsync(context); - result.IsError.Should().BeFalse(); - result.Client.ClientId.Should().Be("roclient.public"); - result.Client.RequireClientSecret.Should().BeFalse(); + result.IsError.ShouldBeFalse(); + result.Client.ClientId.ShouldBe("roclient.public"); + result.Client.RequireClientSecret.ShouldBeFalse(); } [Fact] @@ -84,8 +84,8 @@ public async Task implicit_client_without_secret_should_be_able_to_authenticate( var result = await validator.ValidateAsync(context); - result.IsError.Should().BeFalse(); - result.Client.ClientId.Should().Be("client.implicit"); + result.IsError.ShouldBeFalse(); + result.Client.ClientId.ShouldBe("client.implicit"); } [Fact] @@ -102,6 +102,6 @@ public async Task implicit_client_and_client_creds_without_secret_should_not_be_ var result = await validator.ValidateAsync(context); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/FormPostCredentialParsing.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/FormPostCredentialParsing.cs index b8e6ced23..f4cda4703 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/FormPostCredentialParsing.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/FormPostCredentialParsing.cs @@ -8,7 +8,7 @@ using Duende.IdentityServer; using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; @@ -38,7 +38,7 @@ public async Task EmptyContext() var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } [Fact] @@ -54,9 +54,9 @@ public async Task Valid_PostBody() var secret = await _parser.ParseAsync(context); - secret.Type.Should().Be(IdentityServerConstants.ParsedSecretTypes.SharedSecret); - secret.Id.Should().Be("client"); - secret.Credential.Should().Be("secret"); + secret.Type.ShouldBe(IdentityServerConstants.ParsedSecretTypes.SharedSecret); + secret.Id.ShouldBe("client"); + secret.Credential.ShouldBe("secret"); } [Fact] @@ -73,7 +73,7 @@ public async Task ClientId_Too_Long() var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } [Fact] @@ -90,7 +90,7 @@ public async Task ClientSecret_Too_Long() var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } [Fact] @@ -106,7 +106,7 @@ public async Task Missing_ClientId() var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } [Fact] @@ -122,8 +122,8 @@ public async Task Missing_ClientSecret() var secret = await _parser.ParseAsync(context); - secret.Should().NotBeNull(); - secret.Type.Should().Be(IdentityServerConstants.ParsedSecretTypes.NoSecret); + secret.ShouldNotBeNull(); + secret.Type.ShouldBe(IdentityServerConstants.ParsedSecretTypes.NoSecret); } [Fact] @@ -139,6 +139,6 @@ public async Task Malformed_PostBody() var secret = await _parser.ParseAsync(context); - secret.Should().BeNull(); + secret.ShouldBeNull(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/HashedSharedSecretValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/HashedSharedSecretValidation.cs index 700b149cf..ee4b37853 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/HashedSharedSecretValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/HashedSharedSecretValidation.cs @@ -7,7 +7,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Validation.Setup; using Microsoft.Extensions.Logging; using Xunit; @@ -37,7 +37,7 @@ public async Task Valid_Single_Secret() var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); } [Fact] @@ -56,7 +56,7 @@ public async Task Invalid_Credential_Type() var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -74,19 +74,19 @@ public async Task Valid_Multiple_Secrets() }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); secret.Credential = "foobar"; result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); secret.Credential = "quux"; result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); secret.Credential = "notexpired"; result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); } [Fact] @@ -105,7 +105,7 @@ public async Task Invalid_Single_Secret() var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -123,7 +123,7 @@ public async Task Invalid_Multiple_Secrets() }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -140,7 +140,7 @@ public async Task Client_with_no_Secret_Should_Fail() }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -158,6 +158,6 @@ public async Task Client_with_null_Secret_Should_Fail() }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/MutualTlsSecretValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/MutualTlsSecretValidation.cs index e0275ef2d..16c8c93b8 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/MutualTlsSecretValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/MutualTlsSecretValidation.cs @@ -8,7 +8,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using UnitTests.Validation.Setup; using Microsoft.Extensions.Logging; @@ -44,7 +44,7 @@ public async Task Thumbprint_invalid_secret_type_should_not_match() var result = await validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -64,7 +64,7 @@ public async Task Thumbprint_missing_cert_should_throw() }; Func act = async () => await validator.ValidateAsync(client.ClientSecrets, secret); - await act.Should().ThrowAsync(); + await act.ShouldThrowAsync(); } [Fact] @@ -85,7 +85,7 @@ public async Task Thumbprint_invalid_secret_should_not_match() var result = await validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -106,7 +106,7 @@ public async Task Thumbprint_valid_secret_should_match() var result = await validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); } /////////////////// @@ -131,7 +131,7 @@ public async Task Name_invalid_secret_type_should_not_match() var result = await validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -151,7 +151,7 @@ public async Task Name_missing_cert_should_throw() }; Func act = async () => await validator.ValidateAsync(client.ClientSecrets, secret); - await act.Should().ThrowAsync(); + await act.ShouldThrowAsync(); } [Fact] @@ -172,7 +172,7 @@ public async Task Name_invalid_secret_should_not_match() var result = await validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -193,6 +193,6 @@ public async Task Name_valid_secret_should_match() var result = await validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/PlainTextClientSecretValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/PlainTextClientSecretValidation.cs index 7067293ee..67a09b7a7 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/PlainTextClientSecretValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/PlainTextClientSecretValidation.cs @@ -7,7 +7,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Validation.Setup; using Microsoft.Extensions.Logging; using Xunit; @@ -37,7 +37,7 @@ public async Task Valid_Single_Secret() var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); } [Fact] @@ -56,7 +56,7 @@ public async Task Invalid_Credential_Type() var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -74,19 +74,19 @@ public async Task Valid_Multiple_Secrets_No_Protection() }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); secret.Credential = "foobar"; result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); secret.Credential = "quux"; result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); secret.Credential = "notexpired"; result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); } [Fact] @@ -105,7 +105,7 @@ public async Task Invalid_Single_Secret() var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -123,7 +123,7 @@ public async Task Invalid_Multiple_Secrets() }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -140,7 +140,7 @@ public async Task Client_with_no_Secret_Should_Fail() }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -158,6 +158,6 @@ public async Task Client_with_null_Secret_Should_Fail() }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/PrivateKeyJwtSecretValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/PrivateKeyJwtSecretValidation.cs index 327f9f437..11d75672a 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/PrivateKeyJwtSecretValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/PrivateKeyJwtSecretValidation.cs @@ -14,7 +14,7 @@ using Duende.IdentityServer.Services; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using UnitTests.Services.Default; @@ -97,7 +97,7 @@ public async Task Invalid_Certificate_X5t_Only_Requires_Full_Certificate() var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -115,7 +115,7 @@ public async Task Invalid_Certificate_Thumbprint() var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -133,7 +133,7 @@ public async Task Valid_Certificate_Base64() var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); } [Theory] @@ -156,7 +156,7 @@ public async Task Valid_legacy_aud(string aud) var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); } [Theory] @@ -246,10 +246,10 @@ public async Task Invalid_Replay() }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -267,7 +267,7 @@ public async Task Invalid_Certificate_Base64() var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -288,7 +288,7 @@ public async Task Invalid_Issuer() var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -309,7 +309,7 @@ public async Task Invalid_Subject() var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -328,7 +328,7 @@ public async Task Invalid_Expired_Token() var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -349,6 +349,6 @@ public async Task Invalid_Unsigned_Token() var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/SecretValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/SecretValidation.cs index 8f3b5f8cd..8c790529d 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/SecretValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/Secrets/SecretValidation.cs @@ -8,7 +8,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using UnitTests.Validation.Setup; using Microsoft.Extensions.Logging; @@ -49,7 +49,7 @@ public async Task Valid_Single_Secret() var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); } [Fact] @@ -68,7 +68,7 @@ public async Task Invalid_Credential_Type() var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -86,19 +86,19 @@ public async Task Valid_Multiple_Secrets() }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); secret.Credential = "foobar"; result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); secret.Credential = "quux"; result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); secret.Credential = "notexpired"; result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeTrue(); + result.Success.ShouldBeTrue(); } [Fact] @@ -117,7 +117,7 @@ public async Task Invalid_Single_Secret() var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -135,7 +135,7 @@ public async Task Expired_Secret() }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -153,7 +153,7 @@ public async Task Invalid_Multiple_Secrets() }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } [Fact] @@ -170,6 +170,6 @@ public async Task Client_with_no_Secret_Should_Fail() }; var result = await _validator.ValidateAsync(client.ClientSecrets, secret); - result.Success.Should().BeFalse(); + result.Success.ShouldBeFalse(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/StrictRedirectUriValidatorAppAuthValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/StrictRedirectUriValidatorAppAuthValidation.cs index 0ee0f9ada..7e9611ca7 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/StrictRedirectUriValidatorAppAuthValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/StrictRedirectUriValidatorAppAuthValidation.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Models; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Xunit; namespace UnitTests.Validation; @@ -53,7 +53,7 @@ public async Task Loopback_Redirect_URIs_Should_Be_AllowedAsync(string requested RequestedUri = requestedUri, Client = clientWithValidLoopbackRedirectUri }); - result.Should().BeTrue(); + result.ShouldBeTrue(); } [Theory] @@ -84,7 +84,7 @@ public async Task Loopback_Redirect_URIs_Should_Not_Be_AllowedAsync(string reque RequestedUri = requestedUri, Client = clientWithValidLoopbackRedirectUri }); - result.Should().BeFalse(); + result.ShouldBeFalse(); } [Fact] @@ -98,6 +98,6 @@ public async Task failed_match_should_not_be_allowed() RequestedUri = "http://127.0.0.1", Client = clientWithNoRedirectUris, }); - result.Should().BeFalse(); + result.ShouldBeFalse(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ClientCredentials_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ClientCredentials_Invalid.cs index 43f4d1bec..90724e4a7 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ClientCredentials_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ClientCredentials_Invalid.cs @@ -6,7 +6,7 @@ using System.Linq; using System.Threading.Tasks; using Duende.IdentityServer.Stores; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Validation.Setup; using Xunit; @@ -32,8 +32,8 @@ public async Task Invalid_GrantType_For_Client() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.UnauthorizedClient); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.UnauthorizedClient); } [Fact] @@ -50,9 +50,9 @@ public async Task Request_should_succeed_even_with_allowed_identity_scopes_becau var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); - result.ValidatedRequest.ValidatedResources.Resources.ApiResources.Select(x=>x.Name).Should().BeEquivalentTo(new[] { "api", "urn:api1", "urn:api2", "urn:api3" }); - result.ValidatedRequest.ValidatedResources.Resources.ApiScopes.Select(x=>x.Name).Should().BeEquivalentTo(new[] { "resource", "resource2", "scope1" }); + result.IsError.ShouldBeFalse(); + result.ValidatedRequest.ValidatedResources.Resources.ApiResources.Select(x=>x.Name).ShouldBeEquivalentTo(new[] { "api", "urn:api1", "urn:api2", "urn:api3" }); + result.ValidatedRequest.ValidatedResources.Resources.ApiScopes.Select(x=>x.Name).ShouldBeEquivalentTo(new[] { "resource", "resource2", "scope1" }); } [Fact] @@ -68,8 +68,8 @@ public async Task Unknown_Scope() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); } [Fact] @@ -85,8 +85,8 @@ public async Task Unknown_Scope_Multiple() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); } [Fact] @@ -102,8 +102,8 @@ public async Task Restricted_Scope() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); } [Fact] @@ -119,8 +119,8 @@ public async Task Restricted_Scope_Multiple() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); } [Fact] @@ -138,8 +138,8 @@ public async Task Identity_scope_is_not_allowed_for_client_credentials_when_spec var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); } [Fact] @@ -155,8 +155,8 @@ public async Task Resource_and_Refresh_Token() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); } @@ -175,23 +175,23 @@ public async Task Invalid_resource_indicator() parameters[OidcConstants.TokenRequest.Resource] = "urn:api1" + new string('x', 512); var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidTarget); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidTarget); } { parameters[OidcConstants.TokenRequest.Resource] = "api"; var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } { parameters[OidcConstants.TokenRequest.Resource] = "urn:api1"; parameters.Add(OidcConstants.TokenRequest.Resource, "urn:api2"); var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Code_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Code_Invalid.cs index dc540bb81..bf4d4fd39 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Code_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Code_Invalid.cs @@ -12,7 +12,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using UnitTests.Validation.Setup; @@ -55,8 +55,8 @@ public async Task Missing_AuthorizationCode() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -88,8 +88,8 @@ public async Task Invalid_AuthorizationCode() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -123,8 +123,8 @@ public async Task AuthorizationCodeTooLong() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -156,8 +156,8 @@ public async Task No_Scopes_for_AuthorizationCode() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - OidcConstants.TokenErrors.InvalidRequest.Should().Be(result.Error); + result.IsError.ShouldBeTrue(); + OidcConstants.TokenErrors.InvalidRequest.ShouldBe(result.Error); } [Fact] @@ -189,8 +189,8 @@ public async Task Client_Not_Authorized_For_AuthorizationCode_Flow() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.UnauthorizedClient); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.UnauthorizedClient); } [Fact] @@ -223,8 +223,8 @@ public async Task Client_Trying_To_Request_Token_Using_Another_Clients_Code() var result = await validator.ValidateRequestAsync(parameters, client2.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -255,8 +255,8 @@ public async Task Missing_RedirectUri() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.UnauthorizedClient); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.UnauthorizedClient); } [Fact] @@ -288,8 +288,8 @@ public async Task Different_RedirectUri_Between_Authorize_And_Token_Request() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -321,8 +321,8 @@ public async Task Expired_AuthorizationCode() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -359,7 +359,7 @@ public async Task Reused_AuthorizationCode() // request first time var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); // request second time validator = Factory.CreateTokenRequestValidator( @@ -367,8 +367,8 @@ public async Task Reused_AuthorizationCode() result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -404,8 +404,8 @@ public async Task Code_Request_with_disabled_User() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -443,30 +443,30 @@ public async Task Invalid_resource_indicator() { var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } { parameters[OidcConstants.TokenRequest.Resource] = "api"; var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } { parameters[OidcConstants.TokenRequest.Resource] = "urn:api3"; var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } { parameters[OidcConstants.TokenRequest.Resource] = "urn:api1"; parameters.Add(OidcConstants.TokenRequest.Resource, "urn:api2"); var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } } @@ -508,8 +508,8 @@ public async Task failed_resource_validation_should_fail() }; var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_scope"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_scope"); } { @@ -542,8 +542,8 @@ public async Task failed_resource_validation_should_fail() }; var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_DeviceCode_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_DeviceCode_Invalid.cs index 0c67b0152..65e101062 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_DeviceCode_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_DeviceCode_Invalid.cs @@ -9,7 +9,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using UnitTests.Validation.Setup; @@ -48,8 +48,8 @@ public async Task Missing_DeviceCode() }; var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidRequest); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidRequest); } [Fact] @@ -69,8 +69,8 @@ public async Task DeviceCode_Too_Long() }; var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -88,8 +88,8 @@ public async Task Invalid_Grant_For_Client() }; var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.UnauthorizedClient); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.UnauthorizedClient); } [Fact] @@ -107,8 +107,8 @@ public async Task DeviceCodeValidator_Failure() }; var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().NotBeNull(); + result.IsError.ShouldBeTrue(); + result.Error.ShouldNotBeNull(); } [Fact] @@ -127,8 +127,8 @@ public async Task Invalid_resource_indicator() }; var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } [Fact] @@ -147,7 +147,7 @@ public async Task resource_indicator_should_not_be_allowed() }; var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ExtensionGrants_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ExtensionGrants_Invalid.cs index bbb440f39..39919436f 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ExtensionGrants_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ExtensionGrants_Invalid.cs @@ -5,7 +5,7 @@ using System.Collections.Specialized; using System.Threading.Tasks; using Duende.IdentityServer.Stores; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Validation.Setup; using Xunit; @@ -33,8 +33,8 @@ public async Task Invalid_Extension_Grant_Type_For_Client_Credentials_Client() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.UnsupportedGrantType); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.UnsupportedGrantType); } [Fact] @@ -53,8 +53,8 @@ public async Task Restricted_Extension_Grant_Type() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.UnsupportedGrantType); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.UnsupportedGrantType); } [Fact] @@ -73,9 +73,9 @@ public async Task Customer_Error_and_Description_Extension_Grant_Type() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); - result.ErrorDescription.Should().Be("custom error description"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); + result.ErrorDescription.ShouldBe("custom error description"); } [Fact] @@ -97,6 +97,6 @@ public async Task inactive_user_should_fail() parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_General_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_General_Invalid.cs index 0fea7a15b..295b806b8 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_General_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_General_Invalid.cs @@ -9,7 +9,7 @@ using Duende.IdentityServer; using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Validation.Setup; using Xunit; @@ -31,7 +31,7 @@ public async Task Parameters_Null() Func act = () => validator.ValidateRequestAsync(null, null); - await act.Should().ThrowAsync(); + await act.ShouldThrowAsync(); } [Fact] @@ -47,7 +47,7 @@ public async Task Client_Null() Func act = () => validator.ValidateRequestAsync(parameters, null); - await act.Should().ThrowAsync(); + await act.ShouldThrowAsync(); } [Fact] @@ -79,8 +79,8 @@ public async Task Unknown_Grant_Type() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.UnsupportedGrantType); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.UnsupportedGrantType); } [Fact] @@ -98,8 +98,8 @@ public async Task Invalid_Protocol_Type() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidClient); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidClient); } [Fact] @@ -130,7 +130,7 @@ public async Task Missing_Grant_Type() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.UnsupportedGrantType); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.UnsupportedGrantType); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_PKCE.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_PKCE.cs index de4e3cdfc..57613970a 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_PKCE.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_PKCE.cs @@ -11,7 +11,7 @@ using Duende.IdentityServer.Configuration; using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using UnitTests.Validation.Setup; @@ -65,7 +65,7 @@ public async Task valid_pkce_token_request_with_plain_method_should_succeed(stri var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -105,7 +105,7 @@ public async Task valid_pkce_token_request_with_plain_method_should_succeed_hybr var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Theory] @@ -149,7 +149,7 @@ public async Task valid_pkce_token_request_with_sha256_method_should_succeed(str var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Theory] @@ -185,8 +185,8 @@ public async Task token_request_with_missing_code_challenge_and_verifier_should_ var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Theory] @@ -225,8 +225,8 @@ public async Task token_request_with_missing_code_challenge_should_fail(string c var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Theory] @@ -268,8 +268,8 @@ public async Task token_request_with_invalid_verifier_plain_method_should_fail(s var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Theory] @@ -313,8 +313,8 @@ public async Task token_request_with_invalid_verifier_sha256_method_should_fail( var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } private static string VerifierToSha256CodeChallenge(string codeVerifier) diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_RefreshToken_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_RefreshToken_Invalid.cs index 564afe67d..53201663d 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_RefreshToken_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_RefreshToken_Invalid.cs @@ -11,7 +11,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using UnitTests.Validation.Setup; @@ -39,8 +39,8 @@ public async Task Non_existing_RefreshToken() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -59,8 +59,8 @@ public async Task RefreshTokenTooLong() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -87,8 +87,8 @@ public async Task Expired_RefreshToken() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -114,8 +114,8 @@ public async Task Wrong_Client_Binding_RefreshToken_Request() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -143,8 +143,8 @@ public async Task Client_has_no_OfflineAccess_Scope_anymore_at_RefreshToken_Requ var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -176,8 +176,8 @@ public async Task RefreshToken_Request_with_disabled_User() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -208,23 +208,23 @@ public async Task invalid_resource_indicator() parameters[OidcConstants.TokenRequest.Resource] = "urn:api1" + new string('x', 512); var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidTarget); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidTarget); } { parameters[OidcConstants.TokenRequest.Resource] = "api"; var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } { parameters[OidcConstants.TokenRequest.Resource] = "urn:api1"; parameters.Add(OidcConstants.TokenRequest.Resource, "urn:api2"); var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } } @@ -260,8 +260,8 @@ public async Task failed_resource_validation_should_fail() }; var result = await validator.ValidateRequestAsync(parameters, client); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_scope"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_scope"); } { @@ -286,8 +286,8 @@ public async Task failed_resource_validation_should_fail() }; var result = await validator.ValidateRequestAsync(parameters, client); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } } @@ -318,7 +318,7 @@ public async Task resource_indicator_requested_not_in_original_request_should_fa var result = await validator.ValidateRequestAsync(parameters, client); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ResourceOwner_Invalid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ResourceOwner_Invalid.cs index 75a69d6fd..0b981f9ec 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ResourceOwner_Invalid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_ResourceOwner_Invalid.cs @@ -7,7 +7,7 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Common; using UnitTests.Validation.Setup; @@ -34,8 +34,8 @@ public async Task Invalid_GrantType_For_Client() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.UnauthorizedClient); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.UnauthorizedClient); } [Fact] @@ -53,8 +53,8 @@ public async Task Unknown_Scope() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); } [Fact] @@ -72,8 +72,8 @@ public async Task Unknown_Scope_Multiple() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); } [Fact] @@ -91,8 +91,8 @@ public async Task Restricted_Scope() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); } [Fact] @@ -110,8 +110,8 @@ public async Task Restricted_Scope_Multiple() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidScope); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidScope); } [Fact] @@ -127,8 +127,8 @@ public async Task No_ResourceOwnerCredentials() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -145,8 +145,8 @@ public async Task Missing_ResourceOwner_UserName() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -164,9 +164,9 @@ public async Task Invalid_ResourceOwner_Credentials() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); - result.ErrorDescription.Should().Be("invalid_username_or_password"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); + result.ErrorDescription.ShouldBe("invalid_username_or_password"); } [Fact] @@ -183,7 +183,7 @@ public async Task Missing_ResourceOwner_password_for_user_with_password_should_f var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); + result.IsError.ShouldBeTrue(); } [Fact] @@ -201,9 +201,9 @@ public async Task Password_GrantType_Not_Supported() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.UnsupportedGrantType); - result.ErrorDescription.Should().BeNull(); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.UnsupportedGrantType); + result.ErrorDescription.ShouldBeNull(); } [Fact] @@ -221,8 +221,8 @@ public async Task Inactive_ResourceOwner() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); } [Fact] @@ -240,9 +240,9 @@ public async Task Password_GrantType_With_Custom_ErrorDescription() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.TokenErrors.InvalidGrant); - result.ErrorDescription.Should().Be("custom error description"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.TokenErrors.InvalidGrant); + result.ErrorDescription.ShouldBe("custom error description"); } [Fact] @@ -267,8 +267,8 @@ public async Task failed_resource_validation_should_fail() }; var result = await validator.ValidateRequestAsync(parameters, client); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_scope"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_scope"); } { @@ -278,8 +278,8 @@ public async Task failed_resource_validation_should_fail() }; var result = await validator.ValidateRequestAsync(parameters, client); - result.IsError.Should().BeTrue(); - result.Error.Should().Be("invalid_target"); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe("invalid_target"); } } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Valid.cs b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Valid.cs index 9b2bfcb34..f150a2120 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Valid.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/TokenRequest Validation/TokenRequestValidation_Valid.cs @@ -11,7 +11,7 @@ using Duende.IdentityServer; using Duende.IdentityServer.Models; using Duende.IdentityServer.Stores; -using FluentAssertions; +using Shouldly; using Duende.IdentityModel; using UnitTests.Validation.Setup; using Xunit; @@ -39,8 +39,8 @@ public async Task Missing_ResourceOwner_password_for_user_with_no_password_shoul var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); - result.ValidatedRequest.UserName.Should().Be("bob_no_password"); + result.IsError.ShouldBeFalse(); + result.ValidatedRequest.UserName.ShouldBe("bob_no_password"); } [Fact] @@ -75,7 +75,7 @@ public async Task Valid_code_request_should_succeed() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -111,7 +111,7 @@ public async Task Valid_code_request_with_refresh_token_should_succeed() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -128,7 +128,7 @@ public async Task Valid_client_credentials_request_should_succeed() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -145,7 +145,7 @@ public async Task Valid_client_credentials_request_with_default_scopes_should_su var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -162,7 +162,7 @@ public async Task Valid_client_credentials_request_for_implicit_and_client_crede var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -179,7 +179,7 @@ public async Task Valid_client_credentials_request_restricted_client_should_succ var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -198,7 +198,7 @@ public async Task Valid_resource_owner_request_should_succeed() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -217,7 +217,7 @@ public async Task Valid_resource_wwner_request_with_refresh_token_should_succeed var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -236,7 +236,7 @@ public async Task Valid_resource_owner_request_restricted_client_should_succeed( var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -253,7 +253,7 @@ public async Task valid_extension_grant_request_should_succeed() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -290,7 +290,7 @@ public async Task Valid_refresh_token_request_should_succeed() var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -322,7 +322,7 @@ public async Task Valid_refresh_token_request_using_restricted_client_should_suc var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -352,6 +352,6 @@ public async Task Valid_device_code_request_should_succeed() }; var result = await validator.ValidateRequestAsync(parameters, client.ToValidationResult()); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } } \ No newline at end of file diff --git a/identity-server/test/IdentityServer.UnitTests/Validation/UserInfoRequestValidation.cs b/identity-server/test/IdentityServer.UnitTests/Validation/UserInfoRequestValidation.cs index 2b2152bf6..61cfa893b 100644 --- a/identity-server/test/IdentityServer.UnitTests/Validation/UserInfoRequestValidation.cs +++ b/identity-server/test/IdentityServer.UnitTests/Validation/UserInfoRequestValidation.cs @@ -9,7 +9,7 @@ using System.Threading.Tasks; using Duende.IdentityServer.Stores; using Duende.IdentityServer.Validation; -using FluentAssertions; +using Shouldly; using UnitTests.Common; using Xunit; @@ -38,8 +38,8 @@ public async Task token_without_sub_should_fail() var result = await validator.ValidateRequestAsync("token"); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.ProtectedResourceErrors.InvalidToken); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); } [Fact] @@ -63,7 +63,7 @@ public async Task active_user_should_succeed() var result = await validator.ValidateRequestAsync("token"); - result.IsError.Should().BeFalse(); + result.IsError.ShouldBeFalse(); } [Fact] @@ -87,7 +87,7 @@ public async Task inactive_user_should_fail() var result = await validator.ValidateRequestAsync("token"); - result.IsError.Should().BeTrue(); - result.Error.Should().Be(OidcConstants.ProtectedResourceErrors.InvalidToken); + result.IsError.ShouldBeTrue(); + result.Error.ShouldBe(OidcConstants.ProtectedResourceErrors.InvalidToken); } } \ No newline at end of file diff --git a/shared/ShouldlyExtensions/ShouldlyExtensions.cs b/shared/ShouldlyExtensions/ShouldlyExtensions.cs new file mode 100644 index 000000000..927b644df --- /dev/null +++ b/shared/ShouldlyExtensions/ShouldlyExtensions.cs @@ -0,0 +1,69 @@ +namespace Shouldly; + +public static class ShouldlyExtensions +{ + /// + /// Asserts that the actual object is not equivalent to the expected object. + /// + /// The type of the objects being compared. + /// The actual object. + /// The expected object. + /// A custom error message if the assertion fails. + public static void ShouldNotBeEquivalentTo(this object? actual, object? expected, string? customMessage = null) + { + try + { + // Use ShouldBeEquivalentTo to check equivalence and throw if they are equivalent + actual.ShouldBeEquivalentTo(expected); + } + catch (ShouldAssertException) + { + // They are not equivalent, which is the desired outcome + return; + } + + // If no exception was thrown, the objects are equivalent + var errorMessage = customMessage ?? "Expected objects not to be equivalent, but they were."; + throw new ShouldAssertException(errorMessage); + } + + /// + /// Asserts that the actual DateTime is within the specified TimeSpan of the expected DateTime. + /// + /// The actual DateTime value. + /// The expected DateTime value. + /// The allowed TimeSpan difference. + /// A custom error message if the assertion fails. + public static void ShouldBeCloseTo(this DateTime actual, DateTime expected, TimeSpan tolerance, string? customMessage = null) + { + var difference = (actual - expected).Duration(); + + if (difference <= tolerance) + { + return; + } + var errorMessage = customMessage ?? + $"Expected {actual} to be within {tolerance} of {expected}, but the difference was {difference}."; + throw new ShouldAssertException(errorMessage); + } + + /// + /// Asserts that the actual DateTime is within the specified TimeSpan of the expected DateTime. + /// + /// The actual DateTime value. + /// The expected DateTime value. + /// The allowed TimeSpan difference. + /// A custom error message if the assertion fails. + public static void ShouldBeCloseTo(this DateTimeOffset actual, DateTimeOffset expected, TimeSpan tolerance, string? customMessage = null) + { + var difference = (actual - expected).Duration(); + + if (difference <= tolerance) + { + return; + } + var errorMessage = customMessage ?? + $"Expected {actual} to be within {tolerance} of {expected}, but the difference was {difference}."; + throw new ShouldAssertException(errorMessage); + } +} \ No newline at end of file diff --git a/shared/ShouldlyExtensions/ShouldlyExtensions.csproj b/shared/ShouldlyExtensions/ShouldlyExtensions.csproj new file mode 100644 index 000000000..a948d7ea9 --- /dev/null +++ b/shared/ShouldlyExtensions/ShouldlyExtensions.csproj @@ -0,0 +1,15 @@ + + + + net8.0 + enable + enable + false + Shouldly + + + + + + +