From 032dfc164342099fad3f1b3efad7c0dc377b17db Mon Sep 17 00:00:00 2001 From: Lukas Hanusovsky Date: Thu, 9 Apr 2026 11:23:37 +0200 Subject: [PATCH] [Old Arquillian testsuite] Migrating Assert JUnit4 to Assertions JUnit5 Signed-off-by: Lukas Hanusovsky --- .../integration-arquillian/tests/base/pom.xml | 24 + .../arquillian/AuthServerTestEnricher.java | 4 +- .../arquillian/TestClassProvider.java | 1 + .../testsuite/auth/page/login/OAuthGrant.java | 6 +- .../client/KeycloakTestingClient.java | 6 +- .../keycloak/testsuite/page/AbstractPage.java | 6 +- .../page/AbstractPatternFlyAlert.java | 12 +- .../testsuite/pages/AbstractPage.java | 6 +- .../testsuite/pages/DeleteCredentialPage.java | 4 +- .../testsuite/pages/IdpLinkActionPage.java | 4 +- .../pages/InstalledAppRedirectPage.java | 4 +- .../pages/LanguageComboboxAwarePage.java | 18 +- .../keycloak/testsuite/pages/LoginPage.java | 6 +- .../testsuite/pages/LoginTotpPage.java | 6 +- .../testsuite/pages/LogoutSessionsPage.java | 8 +- .../pages/OAuth2DeviceVerificationPage.java | 18 +- .../testsuite/pages/OAuthGrantPage.java | 6 +- .../testsuite/pages/RegisterPage.java | 10 +- .../pages/SelectOrganizationPage.java | 6 +- .../org/keycloak/testsuite/util/KeyUtils.java | 4 +- .../testsuite/util/KeystoreUtils.java | 2 +- .../keycloak/testsuite/util/MailUtils.java | 2 +- .../keycloak/testsuite/util/SamlClient.java | 6 +- .../keycloak/testsuite/util/TokenUtil.java | 2 +- .../org/keycloak/testsuite/util/UIUtils.java | 4 +- .../testsuite/util/UserInfoClientUtil.java | 16 +- .../keycloak/testsuite/util/WaitUtils.java | 4 +- .../util/saml/HandleArtifactStepBuilder.java | 6 +- .../util/saml/SamlDocumentStepBuilder.java | 6 +- .../webauthn/pages/WebAuthnErrorPage.java | 4 +- .../pages/fragments/AbstractHeader.java | 4 +- .../pages/fragments/ContentAlert.java | 8 +- .../pages/fragments/ContinueCancelModal.java | 8 +- ...stractChangeImportedUserPasswordsTest.java | 3 +- .../testsuite/AbstractClientTest.java | 3 +- .../testsuite/AbstractKeycloakTest.java | 4 +- .../AbstractTestRealmKeycloakTest.java | 3 +- .../java/org/keycloak/testsuite/Assert.java | 23 +- .../org/keycloak/testsuite/AssertEvents.java | 12 +- .../account/AbstractRestServiceTest.java | 4 +- .../account/AccountRestServiceCorsTest.java | 2 +- ...ountRestServiceReadOnlyAttributesTest.java | 16 +- .../account/AccountRestServiceTest.java | 82 +-- ...AccountRestServiceWithUserProfileTest.java | 16 +- .../LinkedAccountsRestServiceTest.java | 10 +- .../account/ResourcesRestServiceTest.java | 30 +- .../account/SessionRestServiceTest.java | 23 +- .../custom/CustomAuthFlowCookieTest.java | 2 +- .../account/custom/CustomAuthFlowOTPTest.java | 8 +- ...ractAppInitiatedActionUpdateEmailTest.java | 18 +- ...AbstractRequiredActionUpdateEmailTest.java | 20 +- ...ppInitiatedActionDeleteCredentialTest.java | 14 +- .../AppInitiatedActionResetPasswordTest.java | 29 +- .../actions/AppInitiatedActionTest.java | 4 +- .../AppInitiatedActionTotpSetupTest.java | 16 +- .../AppInitiatedActionUpdateEmailTest.java | 12 +- ...ActionUpdateEmailWithVerificationTest.java | 20 +- .../AppInitiatedActionUpdateProfileTest.java | 94 +-- .../actions/AppInitiatedRegistrationTest.java | 4 +- .../actions/DeleteAccountActionTest.java | 20 +- .../RequiredActionEmailVerificationTest.java | 108 ++-- .../RequiredActionMultipleActionsTest.java | 8 +- .../actions/RequiredActionPriorityTest.java | 4 +- .../RequiredActionResetPasswordTest.java | 10 +- .../actions/RequiredActionTotpSetupTest.java | 18 +- .../RequiredActionUpdateEmailTest.java | 12 +- ...onUpdateEmailTestWithVerificationTest.java | 44 +- .../RequiredActionUpdateProfileTest.java | 120 ++-- ...ctionUpdateProfileWithUserProfileTest.java | 80 +-- .../actions/TermsAndConditionsTest.java | 50 +- .../adapter/AbstractServletsAdapterTest.java | 16 +- .../SAMLLoginResponseHandlingTest.java | 4 +- .../servlet/SAMLServletAdapterTest.java | 92 +-- .../adapter/servlet/SamlSignatureTest.java | 4 +- .../authz/AbstractResourceServerTest.java | 2 +- .../testsuite/authz/AttributeTest.java | 6 +- .../testsuite/authz/AuthorizationAPITest.java | 16 +- .../testsuite/authz/AuthorizationTest.java | 6 +- .../authz/AuthzClientCredentialsTest.java | 12 +- .../testsuite/authz/AuthzClientTest.java | 4 +- .../authz/ClientScopePolicyTest.java | 8 +- .../authz/ConflictingScopePermissionTest.java | 10 +- .../testsuite/authz/EntitlementAPITest.java | 12 +- .../testsuite/authz/GroupNamePolicyTest.java | 4 +- .../testsuite/authz/GroupPathPolicyTest.java | 4 +- .../testsuite/authz/PermissionClaimTest.java | 8 +- .../testsuite/authz/PermissionEqualsTest.java | 4 +- .../authz/PermissionManagementTest.java | 24 +- .../PolicyEvaluationCompositeRoleTest.java | 4 +- .../testsuite/authz/PolicyEvaluationTest.java | 26 +- .../testsuite/authz/RegexPolicyTest.java | 10 +- .../testsuite/authz/RolePolicyTest.java | 4 +- .../authz/UmaDiscoveryDocumentTest.java | 2 +- .../testsuite/authz/UmaGrantTypeTest.java | 12 +- .../UmaPermissionTicketPushedClaimsTest.java | 6 +- .../UmaResourceTypeRepresentationTest.java | 54 +- .../authz/UserManagedAccessTest.java | 10 +- .../UserManagedPermissionServiceTest.java | 10 +- .../admin/AbstractAuthorizationTest.java | 2 +- .../admin/AbstractPolicyManagementTest.java | 8 +- .../admin/AggregatePolicyManagementTest.java | 4 +- .../AuthorizationDisabledInPreviewTest.java | 4 +- .../authz/admin/AuthorizationTest.java | 18 +- .../admin/ClientPolicyManagementTest.java | 22 +- .../ExportAuthorizationSettingsTest.java | 24 +- .../admin/GenericPolicyManagementTest.java | 10 +- .../admin/GroupPolicyManagementTest.java | 8 +- .../ImportAuthorizationSettingsTest.java | 2 +- .../authz/admin/JSPolicyManagementTest.java | 4 +- .../authz/admin/ResourceManagementTest.java | 12 +- ...ResourceManagementWithAuthzClientTest.java | 4 +- .../ResourcePermissionManagementTest.java | 4 +- .../admin/ResourceServerManagementTest.java | 10 +- .../authz/admin/RolePolicyManagementTest.java | 12 +- .../authz/admin/ScopeManagementTest.java | 4 +- .../admin/ScopePermissionManagementTest.java | 4 +- .../authz/admin/TimePolicyManagementTest.java | 8 +- .../authz/admin/UserPolicyManagementTest.java | 22 +- .../permissions/ExportImportTestFGAPV2.java | 4 +- .../broker/AbstractAdvancedBrokerTest.java | 38 +- .../broker/AbstractBaseBrokerTest.java | 16 +- .../testsuite/broker/AbstractBrokerTest.java | 28 +- .../broker/AbstractDefaultIdpTest.java | 34 +- .../broker/AbstractFirstBrokerLoginTest.java | 210 +++---- .../AbstractKcSamlMetadataBrokerTest.java | 12 +- .../broker/AbstractSamlLoginHintTest.java | 18 +- .../AbstractUsernameTemplateMapperTest.java | 8 +- .../testsuite/broker/AccountLinkTest.java | 20 +- .../broker/BrokerRunOnServerUtil.java | 2 +- .../broker/BrokerWithLegacyIdTest.java | 2 +- .../broker/KcOIDCBrokerWithSignatureTest.java | 20 +- .../broker/KcOidcBrokerAcrParameterTest.java | 21 +- .../broker/KcOidcBrokerEventTest.java | 18 +- .../broker/KcOidcBrokerFrontendUrlTest.java | 2 +- .../broker/KcOidcBrokerHiddenIdpHintTest.java | 8 +- .../broker/KcOidcBrokerIdpHintTest.java | 36 +- .../broker/KcOidcBrokerIdpLinkActionTest.java | 19 +- .../testsuite/broker/KcOidcBrokerJWETest.java | 4 +- .../broker/KcOidcBrokerLdapReadOnlyTest.java | 2 +- .../broker/KcOidcBrokerLdapTest.java | 4 +- .../broker/KcOidcBrokerLoginHintTest.java | 24 +- .../KcOidcBrokerLogoutFrontChannelTest.java | 6 +- .../broker/KcOidcBrokerLogoutTest.java | 8 +- .../broker/KcOidcBrokerNoLoginHintTest.java | 20 +- .../KcOidcBrokerNonceParameterTest.java | 14 +- .../KcOidcBrokerParameterForwardTest.java | 9 +- .../broker/KcOidcBrokerPassMaxAgeTest.java | 24 +- .../KcOidcBrokerPromptNoneRedirectTest.java | 18 +- .../KcOidcBrokerPromptParameterTest.java | 25 +- .../testsuite/broker/KcOidcBrokerTest.java | 34 +- .../broker/KcOidcBrokerTokenExchangeTest.java | 8 +- .../KcOidcBrokerTransientSessionsTest.java | 52 +- .../KcOidcBrokerUiLocalesDisabledTest.java | 9 +- .../KcOidcBrokerUiLocalesEnabledTest.java | 9 +- .../KcOidcBrokerUiLocalesWithIdpHintTest.java | 9 +- .../broker/KcOidcBrokerWithConsentTest.java | 10 +- ...irstBrokerLoginDetectExistingUserTest.java | 16 +- .../KcOidcFirstBrokerLoginNewAuthTest.java | 21 +- .../broker/KcOidcFirstBrokerLoginTest.java | 50 +- .../broker/KcOidcMultipleTabsBrokerTest.java | 50 +- ...amlAttributeConsumingServiceIndexTest.java | 6 +- .../KcSamlBrokerArtifactBindingTest.java | 4 +- ...lBrokerLoginHintWithOptionEnabledTest.java | 10 +- .../KcSamlCustomEntityIdBrokerTest.java | 6 +- .../broker/KcSamlForceAuthnBrokerTest.java | 6 +- .../broker/KcSamlIdPInitiatedSsoTest.java | 18 +- ...lMetadataSignedAndEncryptedBrokerTest.java | 4 +- .../KcSamlMetadataSignedBrokerTest.java | 6 +- .../broker/KcSamlMultipleTabsBrokerTest.java | 22 +- .../broker/KcSamlParseIdPDescriptorTest.java | 28 +- .../broker/KcSamlSpDescriptorTest.java | 34 +- .../KcSamlUsernameTemplateMapperTest.java | 24 +- .../testsuite/broker/OAuth2BrokerTest.java | 30 +- .../testsuite/broker/SocialLoginTest.java | 32 +- .../broker/UsernameTemplateMapperTest.java | 6 +- .../testsuite/cli/AbstractCliTest.java | 6 +- .../cli/admin/AbstractAdmCliTest.java | 56 +- .../testsuite/cli/admin/KcAdmCreateTest.java | 60 +- .../testsuite/cli/admin/KcAdmSessionTest.java | 28 +- .../testsuite/cli/admin/KcAdmTest.java | 216 +++---- .../cli/admin/KcAdmTruststoreTest.java | 18 +- .../testsuite/cli/admin/KcAdmUpdateTest.java | 38 +- .../cli/registration/AbstractRegCliTest.java | 90 ++- .../cli/registration/KcRegConfigTest.java | 22 +- .../cli/registration/KcRegCreateTest.java | 138 ++--- .../testsuite/cli/registration/KcRegTest.java | 224 ++++---- .../cli/registration/KcRegTruststoreTest.java | 18 +- .../cli/registration/KcRegUpdateTest.java | 38 +- .../registration/KcRegUpdateTokenTest.java | 14 +- .../testsuite/client/AbstractFAPI2Test.java | 8 +- .../testsuite/client/AbstractFAPITest.java | 30 +- .../client/AdapterInstallationConfigTest.java | 6 +- .../keycloak/testsuite/client/CIBATest.java | 46 +- .../testsuite/client/ClientRedirectTest.java | 2 +- .../ClientRegistrationPoliciesTest.java | 60 +- .../client/ClientRegistrationTest.java | 15 +- .../client/ClientSecretRotationTest.java | 4 +- .../testsuite/client/ClientTypesTest.java | 44 +- .../client/DefaultClientValidationTest.java | 4 +- .../keycloak/testsuite/client/FAPI1Test.java | 109 ++-- .../testsuite/client/FAPI2DPoPTest.java | 10 +- .../keycloak/testsuite/client/FAPI2Test.java | 36 +- .../testsuite/client/FAPICIBATest.java | 42 +- .../client/InitialAccessTokenTest.java | 20 +- .../testsuite/client/MutualTLSClientTest.java | 10 +- .../OAuth2_1ConfidentialClientTest.java | 12 +- .../client/OAuth2_1PublicClientTest.java | 4 +- ...lientRegistrationDefaultSignatureTest.java | 16 +- ...egistrationResponseTypesAndGrantsTest.java | 24 +- .../client/OIDCClientRegistrationTest.java | 203 +++---- .../OIDCJwksClientRegistrationTest.java | 40 +- .../OIDCPairwiseClientRegistrationTest.java | 89 +-- .../client/RegistrationAccessTokenTest.java | 10 +- .../client/SAMLClientRegistrationTest.java | 14 +- .../policies/AbstractClientPoliciesTest.java | 40 +- .../policies/ClientPoliciesAdminTest.java | 4 +- .../policies/ClientPoliciesConditionTest.java | 10 +- .../policies/ClientPoliciesExecutorTest.java | 28 +- .../ClientPoliciesExtendedEventTest.java | 20 +- .../policies/ClientPoliciesFeatureTest.java | 14 +- .../ClientPoliciesLoadUpdateTest.java | 10 +- .../client/policies/ClientPoliciesTest.java | 18 +- .../SamlClientPoliciesExecutorTest.java | 14 +- ...ecureRedirectUrisEnforcerExecutorTest.java | 18 +- .../cluster/AbstractClusterTest.java | 2 +- .../cluster/AbstractFailoverClusterTest.java | 14 +- .../AbstractInvalidationClusterTest.java | 2 +- .../AuthenticationSessionClusterTest.java | 8 +- ...henticationSessionFailoverClusterTest.java | 14 +- .../ClientInvalidationClusterTest.java | 2 +- .../ClientScopeInvalidationClusterTest.java | 2 +- .../ComponentInvalidationClusterTest.java | 2 +- .../cluster/GroupInvalidationClusterTest.java | 6 +- ...JGroupsCertificateRotationClusterTest.java | 6 +- ...rmissionTicketInvalidationClusterTest.java | 2 +- .../cluster/RealmInvalidationClusterTest.java | 4 +- .../cluster/RoleInvalidationClusterTest.java | 4 +- .../cluster/SessionFailoverClusterTest.java | 2 +- ...UserFederationInvalidationClusterTest.java | 2 +- .../cluster/UserInvalidationClusterTest.java | 2 +- .../composites/CompositeImportRoleTest.java | 58 +- .../composites/CompositeRoleTest.java | 67 +-- .../testsuite/cookies/CookieTest.java | 6 +- .../cookies/DefaultCookieProviderTest.java | 46 +- .../testsuite/docker/DockerClientTest.java | 4 +- .../domainextension/CustomExtensionTest.java | 6 +- .../error/UncaughtErrorPageTest.java | 16 +- .../exportimport/ExportImportTest.java | 59 +- .../exportimport/ExportImportUtil.java | 380 ++++++------- .../UserStorageGracefulDegradationTest.java | 8 +- .../AbstractKerberosSingleRealmTest.java | 38 +- .../kerberos/AbstractKerberosTest.java | 40 +- .../KerberosLdapCrossRealmTrustTest.java | 22 +- ...KerberosLdapMultipleLDAPProvidersTest.java | 6 +- .../federation/kerberos/KerberosLdapTest.java | 30 +- ...KerberosStandaloneCrossRealmTrustTest.java | 10 +- ...rberosStandaloneMultipleProvidersTest.java | 6 +- .../kerberos/KerberosStandaloneTest.java | 43 +- .../federation/ldap/AbstractLDAPTest.java | 4 +- .../ldap/LDAPAccountRestApiTest.java | 54 +- .../federation/ldap/LDAPAdminRestApiTest.java | 22 +- .../ldap/LDAPBinaryAttributesTest.java | 14 +- .../ldap/LDAPExternalChangesTest.java | 6 +- .../ldap/LDAPGroupMapper2WaySyncTest.java | 38 +- .../ldap/LDAPGroupMapperSyncTest.java | 88 +-- ...LDAPGroupMapperSyncWithGroupsPathTest.java | 54 +- .../federation/ldap/LDAPGroupMapperTest.java | 300 +++++----- .../ldap/LDAPHardcodedAttributeTest.java | 8 +- .../federation/ldap/LDAPLegacyImportTest.java | 16 +- .../federation/ldap/LDAPMSADFullNameTest.java | 28 +- .../federation/ldap/LDAPMSADMapperTest.java | 104 ++-- .../ldap/LDAPMultipleAttributesTest.java | 38 +- .../federation/ldap/LDAPNoCacheTest.java | 16 +- .../federation/ldap/LDAPNoMSADTest.java | 18 +- .../ldap/LDAPPasswordModifyExtensionTest.java | 28 +- .../ldap/LDAPProvidersFullNameMapperTest.java | 6 +- .../ldap/LDAPProvidersIntegrationTest.java | 326 +++++------ .../federation/ldap/LDAPReadOnlyTest.java | 30 +- .../federation/ldap/LDAPRoleMapperTest.java | 38 +- .../federation/ldap/LDAPRoleMappingsTest.java | 102 ++-- ...SamlIdPInitiatedVaryingLetterCaseTest.java | 6 +- .../LDAPSearchForUsersPaginationTest.java | 44 +- .../federation/ldap/LDAPSpecialCharsTest.java | 44 +- .../federation/ldap/LDAPSyncTest.java | 62 +- .../federation/ldap/LDAPTestAsserts.java | 28 +- .../federation/ldap/LDAPUserLoginTest.java | 12 +- .../ldap/LDAPUserMultipleCredentialTest.java | 4 +- .../federation/ldap/LDAPUserProfileTest.java | 102 ++-- .../ldap/LDAPUserPropertiesMappingTest.java | 18 +- .../ldap/LdapUsernameAttributeTest.java | 60 +- .../UserFederationLdapConnectionTest.java | 6 +- ...serStorageGracefulDegradationLdapTest.java | 18 +- .../LDAPMultipleAttributesNoImportTest.java | 6 +- .../LDAPProvidersIntegrationNoImportTest.java | 56 +- .../LDAPRoleMappingsNoImportTest.java | 62 +- ...PSearchForUsersPaginationNoImportTest.java | 30 +- ...BackwardsCompatibilityUserStorageTest.java | 19 +- .../storage/BrokenUserStorageTest.java | 10 +- .../federation/storage/ClientStorageTest.java | 64 +-- .../storage/ComponentExportImportTest.java | 36 +- .../FederatedStorageExportImportTest.java | 58 +- .../federation/storage/GroupStorageTest.java | 2 +- .../federation/storage/RoleStorageTest.java | 2 +- .../storage/UserStorageFailureTest.java | 58 +- .../storage/UserStorageOTPTest.java | 19 +- .../federation/storage/UserStorageTest.java | 140 ++--- .../federation/sync/SyncFederationTest.java | 38 +- .../testsuite/forms/AccountConsoleTest.java | 12 +- .../forms/AllowDenyAuthenticatorTest.java | 4 +- .../AltSubflowForCredentialResetTest.java | 10 +- .../forms/AuthenticatorSubflowsTest.java | 4 +- .../forms/AuthenticatorSubflowsTest2.java | 4 +- .../testsuite/forms/BrowserButtonsTest.java | 2 +- .../testsuite/forms/BrowserFlowTest.java | 108 ++-- .../testsuite/forms/BruteForceTest.java | 190 +++---- .../testsuite/forms/CustomFlowTest.java | 12 +- .../forms/CustomRegistrationFlowTest.java | 4 +- .../testsuite/forms/DirectGrantFlowTest.java | 2 +- .../testsuite/forms/FlowOverrideTest.java | 16 +- .../testsuite/forms/HiddenProviderTest.java | 6 +- .../forms/LevelOfAssuranceFlowTest.java | 27 +- .../testsuite/forms/LoginHotpTest.java | 18 +- .../keycloak/testsuite/forms/LoginTest.java | 154 ++--- .../testsuite/forms/LoginTotpTest.java | 36 +- .../forms/MultiFactorAuthenticationTest.java | 32 +- .../forms/MultipleTabsLoginTest.java | 64 +-- .../testsuite/forms/PasswordHashingTest.java | 28 +- .../RPInitiatedFrontChannelLogoutTest.java | 38 +- .../testsuite/forms/ReAuthenticationTest.java | 38 +- .../RecoveryAuthnCodesAuthenticatorTest.java | 38 +- .../testsuite/forms/RegisterTest.java | 26 +- .../forms/RegisterWithUserProfileTest.java | 176 +++--- .../ResetCredentialsAlternativeFlowsTest.java | 34 +- .../testsuite/forms/ResetPasswordTest.java | 34 +- .../testsuite/forms/RestartCookieTest.java | 22 +- .../org/keycloak/testsuite/forms/SSOTest.java | 30 +- .../forms/ScriptAuthenticatorTest.java | 10 +- .../testsuite/forms/ThemeSelectorTest.java | 2 +- .../testsuite/forms/TransientSessionTest.java | 10 +- .../testsuite/forms/VerifyProfileTest.java | 130 ++--- ...onditionalCredentialAuthenticatorTest.java | 8 +- ...ionalSubFlowExecutedAuthenticatorTest.java | 10 +- .../migration/AbstractMigrationTest.java | 134 ++--- ...Import1301MigrationClientPoliciesTest.java | 10 +- .../JsonFileImport1903MigrationTest.java | 2 +- .../migration/MigrationDeniedTest.java | 14 +- .../AbstractClientAuthSignedJWTTest.java | 24 +- ...sTokenDuplicateEmailsNotCleanedUpTest.java | 2 +- .../oauth/AccessTokenDuplicateEmailsTest.java | 2 +- .../oauth/AccessTokenNoEmailLoginTest.java | 2 +- .../oauth/AccessTokenResponseTest.java | 2 +- .../testsuite/oauth/AccessTokenTest.java | 52 +- .../oauth/AuthorizationCodeTest.java | 61 +- .../oauth/BackchannelLogoutTest.java | 6 +- .../oauth/ClientAuthPostMethodTest.java | 4 +- .../oauth/ClientAuthSecretSignedJWTTest.java | 4 +- .../oauth/ClientAuthSignedJWTTest.java | 16 +- .../keycloak/testsuite/oauth/DPoPTest.java | 33 +- .../oauth/LoginStatusIframeEndpointTest.java | 12 +- .../testsuite/oauth/LogoutCorsTest.java | 6 +- .../keycloak/testsuite/oauth/LogoutTest.java | 42 +- .../OAuth2DeviceAuthorizationGrantTest.java | 262 ++++----- .../testsuite/oauth/OAuth2OnlyTest.java | 34 +- .../testsuite/oauth/OAuthGrantTest.java | 68 +-- .../OAuthProofKeyForCodeExchangeTest.java | 70 +-- .../oauth/OAuthRedirectUriStateTest.java | 6 +- .../testsuite/oauth/OAuthRedirectUriTest.java | 68 +-- .../oauth/OAuthScopeInTokenResponseTest.java | 10 +- .../oauth/OIDCProtocolMappersTest.java | 37 +- .../oauth/OfflineTokenMigrationTest.java | 6 +- .../oauth/PreAuthorizedGrantTest.java | 13 +- .../oauth/RPInitiatedLogoutTest.java | 92 +-- ...urceOwnerPasswordCredentialsGrantTest.java | 22 +- .../testsuite/oauth/ServiceAccountTest.java | 40 +- .../oauth/ServiceAccountUserProfileTest.java | 12 +- .../oauth/TokenEndpointCorsTest.java | 6 +- .../oauth/TokenIntrospectionTest.java | 21 +- .../oauth/TokenRevocationCorsTest.java | 8 +- .../testsuite/oauth/TokenRevocationTest.java | 14 +- .../oauth/UserInfoEndpointCorsTest.java | 4 +- .../keycloak/testsuite/oauth/hok/HoKTest.java | 50 +- .../testsuite/oauth/par/ParEndpointTest.java | 14 +- .../keycloak/testsuite/oauth/par/ParTest.java | 22 +- .../testsuite/oauth/par/ParWithDPoPTest.java | 4 +- .../oauth/rar/AbstractRARParserTest.java | 4 +- .../oauth/rar/DynamicScopesRARParseTest.java | 16 +- .../ClientTokenExchangeSAML2Test.java | 122 ++-- .../ExternalInternalTokenExchangeV2Test.java | 5 +- .../StandardTokenExchangeV1Test.java | 131 ++--- .../StandardTokenExchangeV2Test.java | 56 +- ...ExchangeV2WithLegacyTokenExchangeTest.java | 7 +- ...bjectImpersonationTokenExchangeV1Test.java | 88 +-- .../tokenexchange/TokenExchangeTestUtils.java | 2 +- .../JwtCredentialBuilderTest.java | 2 +- .../SdJwtCredentialBuilderTest.java | 38 +- .../JWTVCIssuerWellKnownProviderTest.java | 12 +- .../signing/JwtCredentialSignerTest.java | 30 +- .../signing/LDCredentialSignerTest.java | 20 +- .../signing/OID4VCAttestationProofTest.java | 55 +- ...ID4VCAuthorizationCodeFlowWithPARTest.java | 72 +-- ...uthorizationDetailsTypesSupportedTest.java | 38 +- .../OID4VCCredentialOfferCorsTest.java | 100 ++-- .../OID4VCIssuerEndpointEncryptionTest.java | 88 ++- .../signing/OID4VCIssuerEndpointTest.java | 72 +-- .../OID4VCJWTIssuerEndpointDisabledTest.java | 21 +- ...ID4VCSdJwtIssuingEndpointDisabledTest.java | 16 +- .../OID4VCSdJwtIssuingEndpointTest.java | 282 ++++----- ...4VCSdJwtPreInstalledNaturalPersonTest.java | 6 +- .../oid4vc/issuance/signing/OID4VCTest.java | 10 +- .../signing/SdJwtCredentialSignerTest.java | 33 +- .../testsuite/oidc/AbstractOIDCScopeTest.java | 8 +- .../oidc/AbstractWellKnownProviderTest.java | 33 +- .../testsuite/oidc/AcrAuthFlowTest.java | 14 +- .../keycloak/testsuite/oidc/AudienceTest.java | 6 +- .../AuthenticationMethodReferenceTest.java | 10 +- .../AuthorizationTokenEncryptionTest.java | 14 +- .../AuthorizationTokenResponseModeTest.java | 64 +-- .../testsuite/oidc/IdTokenEncryptionTest.java | 20 +- .../oidc/LightWeightAccessTokenTest.java | 140 ++--- .../NonceBackwardsCompatibleMapperTest.java | 10 +- .../oidc/OIDCAdvancedRequestParamsTest.java | 166 +++--- .../oidc/OIDCBackwardsCompatibilityTest.java | 29 +- .../testsuite/oidc/OIDCPublicClientTest.java | 8 +- .../testsuite/oidc/OIDCScopeTest.java | 83 +-- .../oidc/OIDCWellKnownProviderTest.java | 2 +- .../keycloak/testsuite/oidc/UserInfoTest.java | 71 +-- .../flows/AbstractOIDCResponseTypeTest.java | 64 +-- .../flows/OIDCBasicResponseTypeCodeTest.java | 14 +- .../flows/OIDCBasicResponseTypeNoneTest.java | 10 +- ...ponseTypeCodeIDTokenAsDetachedSigTest.java | 40 +- ...TypeCodeIDTokenAsDetachedSigTokenTest.java | 38 +- ...OIDCHybridResponseTypeCodeIDTokenTest.java | 16 +- ...ybridResponseTypeCodeIDTokenTokenTest.java | 14 +- .../OIDCHybridResponseTypeCodeTokenTest.java | 12 +- .../OIDCImplicitResponseTypeIDTokenTest.java | 14 +- ...CImplicitResponseTypeIDTokenTokenTest.java | 12 +- .../account/OrganizationAccountTest.java | 26 +- .../admin/AbstractOrganizationTest.java | 20 +- .../IdentityProviderThemeConfigTest.java | 6 +- .../admin/OrganizationInvitationLinkTest.java | 42 +- .../OrganizationInvitationManagementTest.java | 2 +- .../organization/admin/OrganizationTest.java | 20 +- .../admin/OrganizationThemeTest.java | 48 +- .../OrganizationAuthenticationTest.java | 54 +- .../AbstractBrokerSelfRegistrationTest.java | 133 ++--- .../OrganizationIdentityProviderTest.java | 38 +- ...izationOIDCBrokerSelfRegistrationTest.java | 2 +- .../exportimport/OrganizationExportTest.java | 6 +- .../OrganizationFederationTest.java | 2 +- ...nizationGroupMembershipSAMLMapperTest.java | 4 +- .../OrganizationGroupOidcIdpMapperTest.java | 16 +- .../OrganizationGroupSamlIdpMapperTest.java | 2 +- .../OrganizationOIDCProtocolMapperTest.java | 38 +- .../OrganizationSAMLProtocolMapperTest.java | 8 +- .../member/OrganizationMemberTest.java | 38 +- .../OrganizationMemberWithLdapTest.java | 2 +- .../policy/PasswordAgePolicyTest.java | 8 +- .../testsuite/policy/PasswordPolicyTest.java | 90 +-- .../providers/ProvidersOverrideTest.java | 4 +- .../saml/AudienceProtocolMappersTest.java | 26 +- .../testsuite/saml/BasicSamlTest.java | 4 +- .../keycloak/testsuite/saml/BrokerTest.java | 6 +- .../saml/LevelOfAssuranceFlowSamlTest.java | 16 +- .../keycloak/testsuite/saml/LogoutTest.java | 10 +- .../testsuite/saml/NameIdMapperTest.java | 2 +- .../testsuite/saml/SamlClientTest.java | 4 +- .../saml/SessionNotOnOrAfterTest.java | 26 +- .../script/DeployedSAMLScriptMapperTest.java | 8 +- .../DeployedScriptAuthenticatorTest.java | 18 +- .../script/DeployedScriptMapperTest.java | 4 +- .../script/DeployedScriptPolicyTest.java | 4 +- ...ndeployedScriptMapperNotAvailableTest.java | 2 +- .../AbstractUserSessionLimitsBrokerTest.java | 4 +- .../sessionlimits/UserSessionLimitsTest.java | 2 +- .../sessionlimits/UserSessionLimitsUtil.java | 2 +- .../org/keycloak/testsuite/ssl/TLSTest.java | 10 +- .../testsuite/ssl/TrustStoreEmailTest.java | 8 +- .../CustomAccountResourceProviderTest.java | 4 +- .../theme/CustomRegistrationTemplateTest.java | 8 +- .../CustomUpdateProfileTemplateTest.java | 8 +- .../theme/DefaultThemeManagerTest.java | 28 +- .../theme/ThemeResourceProviderTest.java | 36 +- .../testsuite/url/HostnameV2Test.java | 6 +- .../user/profile/CustomUserProfileTest.java | 6 +- .../user/profile/UIRealmResourceTest.java | 24 +- .../user/profile/UserProfileTest.java | 66 +-- .../profile/config/UPConfigParserTest.java | 134 ++--- .../profile/config/UPConfigUtilsTest.java | 44 +- .../testsuite/util/AssertAdminEvents.java | 28 +- .../testsuite/util/AttributesAssert.java | 2 +- .../testsuite/util/ClientPoliciesUtil.java | 2 +- .../testsuite/util/JsonTestUtils.java | 4 +- .../keycloak/testsuite/util/MailAssert.java | 10 +- .../testsuite/util/NoCacheAnnotationTest.java | 6 +- .../org/keycloak/testsuite/util/UIAssert.java | 8 +- .../keycloak/testsuite/util/URLAssert.java | 18 +- .../validation/BuiltinValidatorsTest.java | 534 +++++++++--------- .../testsuite/validation/ValidatorTest.java | 4 +- .../testsuite/validation/ValidatorsTest.java | 140 ++--- .../vault/AbstractKeycloakVaultTest.java | 12 +- .../webauthn/AbstractWebAuthnVirtualTest.java | 2 +- .../AppInitiatedActionWebAuthnTest.java | 4 +- .../PasskeysKcOidcFirstBrokerLoginTest.java | 36 +- ...asskeysOrganizationAuthenticationTest.java | 4 +- .../AttestationConveyanceRegisterTest.java | 2 +- .../x509/AbstractX509AuthenticationTest.java | 40 +- .../testsuite/x509/X509BrowserCRLTest.java | 38 +- .../testsuite/x509/X509BrowserLoginTest.java | 98 ++-- .../testsuite/x509/X509DirectGrantTest.java | 36 +- .../x509/X509OCSPResponderFailOpenTest.java | 8 +- .../X509OCSPResponderSpecificCertTest.java | 8 +- .../testsuite/x509/X509OCSPResponderTest.java | 12 +- 512 files changed, 7641 insertions(+), 7608 deletions(-) diff --git a/testsuite/integration-arquillian/tests/base/pom.xml b/testsuite/integration-arquillian/tests/base/pom.xml index b7986edf599f..279dac3b2b15 100644 --- a/testsuite/integration-arquillian/tests/base/pom.xml +++ b/testsuite/integration-arquillian/tests/base/pom.xml @@ -97,6 +97,30 @@ junit compile + + org.junit.platform + junit-platform-engine + 1.10.3 + test + + + org.junit.platform + junit-platform-commons + 1.10.3 + test + + + org.junit.jupiter + junit-jupiter-api + 5.10.3 + compile + + + org.junit.vintage + junit-vintage-engine + 5.10.3 + compile + org.hamcrest hamcrest diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/AuthServerTestEnricher.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/AuthServerTestEnricher.java index 2b0845b7bdc1..5b706ab495bf 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/AuthServerTestEnricher.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/AuthServerTestEnricher.java @@ -81,7 +81,7 @@ import org.jboss.arquillian.test.spi.event.suite.BeforeSuite; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.spec.JavaArchive; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; @@ -664,7 +664,7 @@ private void checkForNoUnexpectedUncaughtError(Stream logStream) { Optional anyUncaughtError = logStream.map(UNEXPECTED_UNCAUGHT_ERROR::matcher).filter(Matcher::find).findAny(); if (anyUncaughtError.isPresent()) { Matcher m = anyUncaughtError.get(); - Assert.fail("Uncaught server error detected: " + m.group(1)); + Assertions.fail("Uncaught server error detected: " + m.group(1)); } } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/TestClassProvider.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/TestClassProvider.java index d77e293d72fa..254c66937abb 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/TestClassProvider.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/TestClassProvider.java @@ -18,6 +18,7 @@ public class TestClassProvider { public static final String[] PERMITTED_PACKAGES = new String[] { "/org/keycloak/testsuite", "/org/junit", + "/org/opentest4j", "/org/hamcrest", "/org/keycloak/admin/client", "/org/jboss/resteasy/client", diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/auth/page/login/OAuthGrant.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/auth/page/login/OAuthGrant.java index 3d44a86d4768..c8c37489b536 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/auth/page/login/OAuthGrant.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/auth/page/login/OAuthGrant.java @@ -29,7 +29,7 @@ import static org.keycloak.testsuite.util.UIUtils.clickLink; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stian Thorgersen @@ -68,7 +68,7 @@ public boolean isCurrent(WebDriver driver1) { public void assertClientScopes(List expectedScopes) { List actualScopes = scopesToApprove.stream().map(WebElement::getText).collect(Collectors.toList()); - assertTrue("Expected and actual Client Scopes to approve don't match", - CollectionUtil.collectionEquals(expectedScopes, actualScopes)); // order of scopes doesn't matter + assertTrue(CollectionUtil.collectionEquals(expectedScopes, actualScopes), + "Expected and actual Client Scopes to approve don't match"); // order of scopes doesn't matter } } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/client/KeycloakTestingClient.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/client/KeycloakTestingClient.java index 0b37f7df013f..8e17dc08efed 100755 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/client/KeycloakTestingClient.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/client/KeycloakTestingClient.java @@ -38,8 +38,8 @@ import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; -import org.junit.Assert; import org.junit.AssumptionViolatedException; +import org.junit.jupiter.api.Assertions; /** * @author Marko Strukelj @@ -98,7 +98,7 @@ public void enableFeature(Profile.Feature feature) { featureString = feature.getKey(); } Set disabledFeatures = testing().enableFeature(featureString); - Assert.assertFalse(disabledFeatures.contains(feature)); + Assertions.assertFalse(disabledFeatures.contains(feature)); ProfileAssume.updateDisabledFeatures(disabledFeatures); } @@ -114,7 +114,7 @@ public void disableFeature(Profile.Feature feature) { featureString = feature.getKey(); } Set disabledFeatures = testing().disableFeature(featureString); - Assert.assertTrue(disabledFeatures.contains(feature)); + Assertions.assertTrue(disabledFeatures.contains(feature)); ProfileAssume.updateDisabledFeatures(disabledFeatures); } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/page/AbstractPage.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/page/AbstractPage.java index c8de5a210e46..ee1274b00052 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/page/AbstractPage.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/page/AbstractPage.java @@ -28,7 +28,7 @@ import org.jboss.arquillian.drone.api.annotation.Drone; import org.jboss.logging.Logger; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebDriver; /** @@ -109,7 +109,7 @@ public boolean isCurrent() { public void assertCurrent() { String name = getClass().getSimpleName(); - Assert.assertTrue("Expected " + name + " but was " + DroneUtils.getCurrentDriver().getTitle() + " (" + DroneUtils.getCurrentDriver().getCurrentUrl() + ")", - isCurrent()); + Assertions.assertTrue(isCurrent(), + "Expected " + name + " but was " + DroneUtils.getCurrentDriver().getTitle() + " (" + DroneUtils.getCurrentDriver().getCurrentUrl() + ")"); } } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/page/AbstractPatternFlyAlert.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/page/AbstractPatternFlyAlert.java index 3f1e6437b34f..46a29d109260 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/page/AbstractPatternFlyAlert.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/page/AbstractPatternFlyAlert.java @@ -35,9 +35,9 @@ import static org.keycloak.testsuite.util.UIUtils.isElementVisible; import static org.keycloak.testsuite.util.WaitUtils.PAGELOAD_TIMEOUT_MILLIS; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @@ -82,11 +82,11 @@ public boolean isSuccess() { } public void assertDisplayed() { - assertTrue("Alert should displayed", isDisplayed()); + assertTrue(isDisplayed(), "Alert should displayed"); } public void assertNotDisplayed() { - assertFalse("Alert shouldn't be displayed", isDisplayed()); + assertFalse(isDisplayed(), "Alert shouldn't be displayed"); } public void assertSuccess() { @@ -95,7 +95,7 @@ public void assertSuccess() { public void assertSuccess(String expectedText) { assertDisplayed(); - assertTrue("Alert type should be success", isSuccess()); + assertTrue(isSuccess(), "Alert type should be success"); if (expectedText != null) assertEquals(expectedText, getText()); } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/AbstractPage.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/AbstractPage.java index 5a3695745b8d..1ee843f53a82 100755 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/AbstractPage.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/AbstractPage.java @@ -20,7 +20,7 @@ import org.keycloak.testsuite.util.oauth.OAuthClient; import org.jboss.arquillian.test.api.ArquillianResource; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebDriver; /** @@ -36,8 +36,8 @@ public abstract class AbstractPage { public void assertCurrent() { String name = getClass().getSimpleName(); - Assert.assertTrue("Expected " + name + " but was " + driver.getTitle() + " (" + driver.getCurrentUrl() + ")", - isCurrent()); + Assertions.assertTrue(isCurrent(), + "Expected " + name + " but was " + driver.getTitle() + " (" + driver.getCurrentUrl() + ")"); } abstract public boolean isCurrent(); diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/DeleteCredentialPage.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/DeleteCredentialPage.java index 6243fbd716bf..95259ced4238 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/DeleteCredentialPage.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/DeleteCredentialPage.java @@ -21,7 +21,7 @@ import org.keycloak.testsuite.util.UIUtils; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; @@ -52,6 +52,6 @@ public void cancel() { } public void assertCredentialInMessage(String expectedLabel) { - Assert.assertEquals("Do you want to delete " + expectedLabel + "?", message.getText()); + Assertions.assertEquals("Do you want to delete " + expectedLabel + "?", message.getText()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/IdpLinkActionPage.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/IdpLinkActionPage.java index 61e0b68deae1..77ba7a1856fe 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/IdpLinkActionPage.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/IdpLinkActionPage.java @@ -21,7 +21,7 @@ import org.keycloak.testsuite.util.UIUtils; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; @@ -52,6 +52,6 @@ public void cancel() { } public void assertIdpInMessage(String expectedIdpDisplayName) { - Assert.assertEquals("Do you want to link your account with " + expectedIdpDisplayName + "?", message.getText()); + Assertions.assertEquals("Do you want to link your account with " + expectedIdpDisplayName + "?", message.getText()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/InstalledAppRedirectPage.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/InstalledAppRedirectPage.java index f10ea30cdf84..83aaa701e6e2 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/InstalledAppRedirectPage.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/InstalledAppRedirectPage.java @@ -26,7 +26,7 @@ import org.keycloak.common.util.KeycloakUriBuilder; import org.keycloak.services.Urls; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; @@ -74,7 +74,7 @@ public boolean isCurrent() { public String getSuccessCode() { - Assert.assertEquals("Success code", getPageTitleText()); + Assertions.assertEquals("Success code", getPageTitleText()); return code.getAttribute("value"); } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LanguageComboboxAwarePage.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LanguageComboboxAwarePage.java index 5490c509e0d7..6e9c315311aa 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LanguageComboboxAwarePage.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LanguageComboboxAwarePage.java @@ -24,7 +24,7 @@ import org.keycloak.testsuite.util.UIUtils; import org.keycloak.testsuite.util.WaitUtils; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; @@ -81,7 +81,7 @@ public void openLanguage(String language){ String url = langLink.getAttribute("href"); DroneUtils.getCurrentDriver().navigate().to(url); } catch (URISyntaxException ex) { - Assert.fail(ex.getMessage()); + Assertions.fail(ex.getMessage()); } WaitUtils.waitForPageToLoad(); } @@ -90,9 +90,9 @@ public void openLanguage(String language){ public void assertTryAnotherWayLinkAvailability(boolean expectedAvailability) { try { driver.findElement(By.id("try-another-way")); - Assert.assertTrue(expectedAvailability); + Assertions.assertTrue(expectedAvailability); } catch (NoSuchElementException nse) { - Assert.assertFalse(expectedAvailability); + Assertions.assertFalse(expectedAvailability); } } @@ -103,9 +103,9 @@ public void clickTryAnotherWayLink() { public void assertAccountLinkAvailability(boolean expectedAvailability) { try { driver.findElement(By.id("account")); - Assert.assertTrue(expectedAvailability); + Assertions.assertTrue(expectedAvailability); } catch (NoSuchElementException nse) { - Assert.assertFalse(expectedAvailability); + Assertions.assertFalse(expectedAvailability); } } @@ -121,11 +121,11 @@ public void assertAttemptedUsernameAvailability(boolean expectedAvailability) { public static void assertAttemptedUsernameAvailability(WebDriver driver, boolean expectedAvailability) { try { driver.findElement(By.id("kc-attempted-username")); - Assert.assertTrue(expectedAvailability); + Assertions.assertTrue(expectedAvailability); // make sure the username field is not shown if the attempted username field is present - Assert.assertTrue(driver.findElements(By.id("username")).isEmpty()); + Assertions.assertTrue(driver.findElements(By.id("username")).isEmpty()); } catch (NoSuchElementException nse) { - Assert.assertFalse(expectedAvailability); + Assertions.assertFalse(expectedAvailability); } } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LoginPage.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LoginPage.java index fe10c2da24d0..b0bd5393fd23 100755 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LoginPage.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LoginPage.java @@ -23,7 +23,7 @@ import org.keycloak.testsuite.util.oauth.OAuthClient; import org.jboss.arquillian.test.api.ArquillianResource; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; @@ -248,8 +248,8 @@ public boolean isCurrent(String realm) { public void assertCurrent(String realm) { String name = getClass().getSimpleName(); - Assert.assertTrue("Expected " + name + " but was " + DroneUtils.getCurrentDriver().getTitle() + " (" + DroneUtils.getCurrentDriver().getCurrentUrl() + ")", - isCurrent(realm)); + Assertions.assertTrue(isCurrent(realm), + "Expected " + name + " but was " + DroneUtils.getCurrentDriver().getTitle() + " (" + DroneUtils.getCurrentDriver().getCurrentUrl() + ")"); } public void clickRegister() { diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LoginTotpPage.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LoginTotpPage.java index df9fcc192c29..ae6167ca189e 100755 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LoginTotpPage.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LoginTotpPage.java @@ -22,7 +22,7 @@ import org.keycloak.common.util.Retry; import org.keycloak.testsuite.util.UIUtils; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; @@ -91,9 +91,9 @@ public boolean isCurrent() { public void assertOtpCredentialSelectorAvailability(boolean expectedAvailability) { try { driver.findElement(By.className("pf-v5-c-tile")); - Assert.assertTrue(expectedAvailability); + Assertions.assertTrue(expectedAvailability); } catch (NoSuchElementException nse) { - Assert.assertFalse(expectedAvailability); + Assertions.assertFalse(expectedAvailability); } } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LogoutSessionsPage.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LogoutSessionsPage.java index 75cb9f8bf18c..046f08c4be95 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LogoutSessionsPage.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/LogoutSessionsPage.java @@ -18,7 +18,7 @@ import org.keycloak.testsuite.util.UIUtils; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; @@ -35,7 +35,7 @@ public abstract class LogoutSessionsPage extends LanguageComboboxAwarePage { @Override public void assertCurrent() { super.assertCurrent(); - Assert.assertTrue("The page doesn't display the logout other sessions checkbox", this.isLogoutSessionDisplayed()); + Assertions.assertTrue(this.isLogoutSessionDisplayed(), "The page doesn't display the logout other sessions checkbox"); } public boolean isLogoutSessionDisplayed() { @@ -47,12 +47,12 @@ public boolean isLogoutSessionsChecked() { } public void checkLogoutSessions() { - Assert.assertFalse("Logout sessions is checked", isLogoutSessionsChecked()); + Assertions.assertFalse(isLogoutSessionsChecked(), "Logout sessions is checked"); UIUtils.switchCheckbox(logoutSessionsCheckbox, true); } public void uncheckLogoutSessions() { - Assert.assertTrue("Logout sessions is not checked", isLogoutSessionsChecked()); + Assertions.assertTrue(isLogoutSessionsChecked(), "Logout sessions is not checked"); UIUtils.switchCheckbox(logoutSessionsCheckbox, false); } } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/OAuth2DeviceVerificationPage.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/OAuth2DeviceVerificationPage.java index cb1d5ef83561..08eb1d5f2dd2 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/OAuth2DeviceVerificationPage.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/OAuth2DeviceVerificationPage.java @@ -16,7 +16,7 @@ */ package org.keycloak.testsuite.pages; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; @@ -63,23 +63,23 @@ public boolean isCurrent() { } public void assertApprovedPage() { - Assert.assertTrue("Expected device approved page but was " + driver.getTitle() + " (" + driver.getCurrentUrl() + ")", - isApprovedPage()); + Assertions.assertTrue(isApprovedPage(), + "Expected device approved page but was " + driver.getTitle() + " (" + driver.getCurrentUrl() + ")"); } public void assertDeniedPage() { - Assert.assertTrue("Expected device denied page but was " + driver.getTitle() + " (" + driver.getCurrentUrl() + ")", - isDeniedPage()); + Assertions.assertTrue(isDeniedPage(), + "Expected device denied page but was " + driver.getTitle() + " (" + driver.getCurrentUrl() + ")"); } public void assertInvalidUserCodePage() { - Assert.assertTrue("Expected invalid user code page but was " + driver.getTitle() + " (" + driver.getCurrentUrl() + ")", - isInvalidUserCodePage()); + Assertions.assertTrue(isInvalidUserCodePage(), + "Expected invalid user code page but was " + driver.getTitle() + " (" + driver.getCurrentUrl() + ")"); } public void assertExpiredUserCodePage() { - Assert.assertTrue("Expected expired user code page but was " + driver.getTitle() + " (" + driver.getCurrentUrl() + ")", - isExpiredUserCodePage()); + Assertions.assertTrue(isExpiredUserCodePage(), + "Expected expired user code page but was " + driver.getTitle() + " (" + driver.getCurrentUrl() + ")"); } private boolean isApprovedPage() { diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/OAuthGrantPage.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/OAuthGrantPage.java index 0ffb989f51b1..2532c87624b5 100755 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/OAuthGrantPage.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/OAuthGrantPage.java @@ -20,7 +20,7 @@ import java.util.Arrays; import java.util.List; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; @@ -73,8 +73,8 @@ public List getDisplayedGrants() { public void assertGrants(String... expectedGrants) { List displayed = getDisplayedGrants(); List expected = Arrays.asList(expectedGrants); - Assert.assertTrue("Not matched grants. Displayed grants: " + displayed + ", expected grants: " + expected, - displayed.containsAll(expected) && expected.containsAll(displayed)); + Assertions.assertTrue(displayed.containsAll(expected) && expected.containsAll(displayed), + "Not matched grants. Displayed grants: " + displayed + ", expected grants: " + expected); } } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/RegisterPage.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/RegisterPage.java index 569b1ce5a8fe..952ee1ea60a8 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/RegisterPage.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/RegisterPage.java @@ -27,7 +27,7 @@ import org.keycloak.testsuite.util.UIUtils; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; @@ -126,7 +126,7 @@ public void register(String firstName, String lastName, String email, String use } if (!isPasswordPresent() && password != null) { - Assert.fail("Password expected to be filled, but password field not present on the registration page"); + Assertions.fail("Password expected to be filled, but password field not present on the registration page"); } if (isPasswordPresent()) { @@ -183,7 +183,7 @@ public void registerWithEmailAsUsername(String firstName, String lastName, Strin try { usernameInput.clear(); - Assert.fail("Form must be without username field"); + Assertions.fail("Form must be without username field"); } catch (NoSuchElementException e) { // OK } @@ -310,7 +310,7 @@ public void openWithLoginHint(String loginHint) { public void assertCurrent(String orgName) { String name = getClass().getSimpleName(); - Assert.assertTrue("Expected " + name + " but was " + DroneUtils.getCurrentDriver().getTitle() + " (" + DroneUtils.getCurrentDriver().getCurrentUrl() + ")", - isCurrent("Create an account to join the " + orgName + " organization")); + Assertions.assertTrue(isCurrent("Create an account to join the " + orgName + " organization"), + "Expected " + name + " but was " + DroneUtils.getCurrentDriver().getTitle() + " (" + DroneUtils.getCurrentDriver().getCurrentUrl() + ")"); } } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/SelectOrganizationPage.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/SelectOrganizationPage.java index 9b062e214ae3..8c33d3127dab 100755 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/SelectOrganizationPage.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/pages/SelectOrganizationPage.java @@ -21,7 +21,7 @@ import org.keycloak.testsuite.util.oauth.OAuthClient; import org.jboss.arquillian.test.api.ArquillianResource; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; @@ -48,8 +48,8 @@ public boolean isCurrent() { public void assertCurrent(String realm) { String name = getClass().getSimpleName(); - Assert.assertTrue("Expected " + name + " but was " + DroneUtils.getCurrentDriver().getTitle() + " (" + DroneUtils.getCurrentDriver().getCurrentUrl() + ")", - isCurrent(realm)); + Assertions.assertTrue(isCurrent(realm), + "Expected " + name + " but was " + DroneUtils.getCurrentDriver().getTitle() + " (" + DroneUtils.getCurrentDriver().getCurrentUrl() + ")"); } public void selectOrganization(String alias) { diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/KeyUtils.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/KeyUtils.java index f97c985351d3..1dae5808cb2d 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/KeyUtils.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/KeyUtils.java @@ -36,8 +36,8 @@ import org.keycloak.representations.idm.KeysMetadataRepresentation; import org.keycloak.testsuite.admin.ApiUtil; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author mhajas diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/KeystoreUtils.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/KeystoreUtils.java index 9815641ddbf6..289cbe389fde 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/KeystoreUtils.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/KeystoreUtils.java @@ -40,7 +40,7 @@ import org.junit.Assume; import org.junit.rules.TemporaryFolder; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Marek Posolda diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/MailUtils.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/MailUtils.java index dab44e401db3..37f1873dfea6 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/MailUtils.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/MailUtils.java @@ -26,7 +26,7 @@ import jakarta.mail.Multipart; import jakarta.mail.internet.MimeMessage; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Stian Thorgersen diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/SamlClient.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/SamlClient.java index 7fe6fe93764d..28cb6592946b 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/SamlClient.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/SamlClient.java @@ -103,7 +103,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author hmlnarik @@ -713,8 +713,8 @@ public static SAMLDocumentHolder extractSamlResponseFromRedirect(String response String samlResponse = encodedParams.getFirst(GeneralConstants.SAML_RESPONSE_KEY); String samlRequest = encodedParams.getFirst(GeneralConstants.SAML_REQUEST_KEY); - assertTrue("Only one SAMLRequest/SAMLResponse check", (samlResponse != null && samlRequest == null) - || (samlResponse == null && samlRequest != null)); + assertTrue((samlResponse != null && samlRequest == null) + || (samlResponse == null && samlRequest != null), "Only one SAMLRequest/SAMLResponse check"); String samlDoc = RedirectBindingUtil.urlDecode(samlResponse != null? samlResponse : samlRequest); SAMLDocumentHolder documentHolder = SAMLRequestParser.parseResponseRedirectBinding(samlDoc); diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/TokenUtil.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/TokenUtil.java index 3a41c3f5356b..c903d550e621 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/TokenUtil.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/TokenUtil.java @@ -23,7 +23,7 @@ import org.junit.rules.TestRule; import org.junit.runners.model.Statement; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Created by st on 22/03/17. diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/UIUtils.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/UIUtils.java index d7a5679ed5d2..7bd24599008e 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/UIUtils.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/UIUtils.java @@ -8,7 +8,7 @@ import org.keycloak.testsuite.pages.AbstractPage; import org.apache.commons.lang3.StringUtils; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; @@ -143,7 +143,7 @@ public static void switchCheckbox(WebElement checkbox, boolean enable) { boolean current = checkbox.isSelected(); if (current != enable) { clickElement(checkbox, Keys.SPACE); - Assert.assertNotEquals("Checkbox " + checkbox + " is still in the state " + current + " after click.", current, checkbox.isSelected()); + Assertions.assertNotEquals(current, checkbox.isSelected(), "Checkbox " + checkbox + " is still in the state " + current + " after click."); } } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/UserInfoClientUtil.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/UserInfoClientUtil.java index 61eee52b2bd6..27f2deb393f0 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/UserInfoClientUtil.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/UserInfoClientUtil.java @@ -31,7 +31,7 @@ import org.keycloak.testsuite.util.oauth.OAuthClient; import org.keycloak.utils.MediaType; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; /** * @author Marek Posolda @@ -65,20 +65,20 @@ public static UserInfo testSuccessfulUserInfoResponse(Response response, String } public static UserInfo testSuccessfulUserInfoResponse(Response response, String userId, String expectedUsername, String expectedEmail) { - Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - Assert.assertEquals(response.getHeaderString(HttpHeaders.CONTENT_TYPE), MediaType.APPLICATION_JSON); + Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + Assertions.assertEquals(response.getHeaderString(HttpHeaders.CONTENT_TYPE), MediaType.APPLICATION_JSON); UserInfo userInfo = response.readEntity(UserInfo.class); response.close(); - Assert.assertNotNull(userInfo); - Assert.assertNotNull(userInfo.getSubject()); + Assertions.assertNotNull(userInfo); + Assertions.assertNotNull(userInfo.getSubject()); if (userId != null) { - Assert.assertEquals(userId, userInfo.getSubject()); + Assertions.assertEquals(userId, userInfo.getSubject()); } - Assert.assertEquals(expectedEmail, userInfo.getEmail()); - Assert.assertEquals(expectedUsername, userInfo.getPreferredUsername()); + Assertions.assertEquals(expectedEmail, userInfo.getEmail()); + Assertions.assertEquals(expectedUsername, userInfo.getPreferredUsername()); return userInfo; } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/WaitUtils.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/WaitUtils.java index f9deaad02dd2..55fda2e6584c 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/WaitUtils.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/WaitUtils.java @@ -41,8 +41,8 @@ import static org.keycloak.testsuite.util.DroneUtils.getCurrentDriver; import static org.jboss.arquillian.graphene.Graphene.waitGui; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import static org.openqa.selenium.support.ui.ExpectedConditions.javaScriptThrowsNoExceptions; import static org.openqa.selenium.support.ui.ExpectedConditions.not; import static org.openqa.selenium.support.ui.ExpectedConditions.urlToBe; diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/saml/HandleArtifactStepBuilder.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/saml/HandleArtifactStepBuilder.java index 38c6a4b785b7..6c26848e514b 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/saml/HandleArtifactStepBuilder.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/saml/HandleArtifactStepBuilder.java @@ -41,8 +41,8 @@ import org.apache.http.util.EntityUtils; import org.w3c.dom.Document; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * This builder allows the SamlClient to handle a redirect or a POSTed form which contains an artifact (SAMLart) @@ -234,7 +234,7 @@ private String getArtifactFromResponse(CloseableHttpResponse currentResponse) th String form = EntityUtils.toString(currentResponse.getEntity()); Matcher m = artifactPattern.matcher(form); - assertTrue("Can't find artifact in " + form, m.find()); + assertTrue(m.find(), "Can't find artifact in " + form); return m.group(1); } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/saml/SamlDocumentStepBuilder.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/saml/SamlDocumentStepBuilder.java index 6baa27d90097..03ca0feee2ed 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/saml/SamlDocumentStepBuilder.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/saml/SamlDocumentStepBuilder.java @@ -41,7 +41,7 @@ import org.keycloak.testsuite.util.SamlClientBuilder; import org.jboss.logging.Logger; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.w3c.dom.Document; /** @@ -127,8 +127,8 @@ public static String saml2Object2String(final SAML2Object transformed) { } else if (transformed instanceof StatusResponseType) { new SAMLResponseWriter(xmlStreamWriter).write((StatusResponseType) transformed, SAMLProtocolQNames.LOGOUT_RESPONSE.getQName("samlp")); } else { - Assert.assertNotNull("Unknown type: ", transformed); - Assert.fail("Unknown type: " + transformed.getClass().getName()); + Assertions.assertNotNull(transformed, "Unknown type: "); + Assertions.fail("Unknown type: " + transformed.getClass().getName()); } return new String(bos.toByteArray(), GeneralConstants.SAML_CHARSET); } catch (ProcessingException ex) { diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/webauthn/pages/WebAuthnErrorPage.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/webauthn/pages/WebAuthnErrorPage.java index 72d6c30f5ac4..dfb4d3d1854f 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/webauthn/pages/WebAuthnErrorPage.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/webauthn/pages/WebAuthnErrorPage.java @@ -4,7 +4,7 @@ import org.keycloak.testsuite.util.UIUtils; import org.keycloak.testsuite.util.WaitUtils; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; @@ -36,7 +36,7 @@ public void clickCancelRegistrationAIA() { WaitUtils.waitUntilElement(cancelRegistrationAIA).is().clickable(); cancelRegistrationAIA.click(); } catch (NoSuchElementException e) { - Assert.fail("It only works with AIA"); + Assertions.fail("It only works with AIA"); } } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/webauthn/pages/fragments/AbstractHeader.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/webauthn/pages/fragments/AbstractHeader.java index 1c491dfe0af2..c47cd20ba4e1 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/webauthn/pages/fragments/AbstractHeader.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/webauthn/pages/fragments/AbstractHeader.java @@ -23,7 +23,7 @@ import static org.keycloak.testsuite.util.UIUtils.getTextFromElement; import static org.keycloak.testsuite.util.UIUtils.isElementVisible; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vaclav Muzikar @@ -63,7 +63,7 @@ protected boolean isToolsBtnVisible(WebElement btn) { protected void assertToolsBtnVisible(boolean expected, WebElement btn) { boolean actual = isToolsBtnVisible(btn); String msg = "Header button should" + (!expected ? " not" : "") + " be visible"; - assertEquals(msg, expected, actual); + assertEquals(expected, actual, msg); } protected String getToolsBtnText(WebElement btn) { diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/webauthn/pages/fragments/ContentAlert.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/webauthn/pages/fragments/ContentAlert.java index 78be96e55790..e0a91b385bf2 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/webauthn/pages/fragments/ContentAlert.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/webauthn/pages/fragments/ContentAlert.java @@ -27,8 +27,8 @@ import static org.keycloak.testsuite.util.UIUtils.getTextFromElement; import static org.keycloak.testsuite.util.WaitUtils.waitUntilElementIsNotPresent; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Vaclav Muzikar @@ -58,7 +58,7 @@ public boolean isDisplayed() { } public void assertIsDisplayed() { - assertTrue("Alert is not displayed", isDisplayed()); + assertTrue(isDisplayed(), "Alert is not displayed"); } public void assertIsNotDisplayed() { @@ -79,7 +79,7 @@ public void close() { } protected void assertAlertType(String type) { - assertTrue("Alert is not " + type, doesElementClassContain(alertElementRoot, type)); + assertTrue(doesElementClassContain(alertElementRoot, type), "Alert is not " + type); } protected void assertMessage(String expectedMessage) { diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/webauthn/pages/fragments/ContinueCancelModal.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/webauthn/pages/fragments/ContinueCancelModal.java index a16e44f30b61..99e83ba2beee 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/webauthn/pages/fragments/ContinueCancelModal.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/webauthn/pages/fragments/ContinueCancelModal.java @@ -25,8 +25,8 @@ import static org.keycloak.testsuite.util.UIUtils.clickLink; import static org.keycloak.testsuite.util.UIUtils.isElementVisible; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Vaclav Muzikar @@ -50,11 +50,11 @@ public boolean isDisplayed() { } public void assertIsDisplayed() { - assertTrue("Modal dialog should be displayed", isDisplayed()); + assertTrue(isDisplayed(), "Modal dialog should be displayed"); } public void assertIsNotDisplayed() { - assertFalse("Modal dialog should not be displayed", isDisplayed()); + assertFalse(isDisplayed(), "Modal dialog should not be displayed"); } public void clickConfirm() { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractChangeImportedUserPasswordsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractChangeImportedUserPasswordsTest.java index c0758720e7cb..e8eee653c4eb 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractChangeImportedUserPasswordsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractChangeImportedUserPasswordsTest.java @@ -27,6 +27,7 @@ import org.keycloak.testsuite.admin.AdminApiUtil; import org.junit.Before; +import org.junit.jupiter.api.Assertions; /** *

Abstract class that re-generates all imported user passwords with a random one. @@ -105,7 +106,7 @@ protected String generatePassword(String username) { protected String getPassword(String username) { final String password = userPasswords.get(username); - Assert.assertNotNull("password not generated for user " + username, password); + Assertions.assertNotNull(password, "password not generated for user " + username); return password; } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractClientTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractClientTest.java index 5c36e65f0c7d..cb8d4eba5b0e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractClientTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractClientTest.java @@ -37,6 +37,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.auth.page.AuthRealm.TEST; @@ -89,7 +90,7 @@ protected UserRepresentation getFullUserRep(String userName) { result = user; } } - Assert.assertNotNull("Did not find user with username " + userName, result); + Assertions.assertNotNull(result, "Did not find user with username " + userName); return result; } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractKeycloakTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractKeycloakTest.java index 5d8bb99f90b6..c97d17cc0581 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractKeycloakTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractKeycloakTest.java @@ -108,7 +108,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @@ -784,7 +784,7 @@ public static void eventuallyEquals(String message, T expected, Supplier } while (expectedEndTime - System.nanoTime() > 0); //last attempt - assertEquals(message, expected, actual.get()); + assertEquals(expected, actual.get(), message); } catch (Exception e) { throw new RuntimeException("Unexpected!", e); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractTestRealmKeycloakTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractTestRealmKeycloakTest.java index 1c6b479e1a1f..1b52525032bd 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractTestRealmKeycloakTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AbstractTestRealmKeycloakTest.java @@ -32,6 +32,7 @@ import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.junit.Before; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; @@ -123,7 +124,7 @@ protected AccessTokenResponse sendTokenRequestAndGetResponse(EventRepresentation String code = oauth.parseLoginResponse().getCode(); AccessTokenResponse response = oauth.doAccessTokenRequest(code); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); if (eventsField != null) { events.expectCodeToToken(codeId, sessionId).user(loginEvent.getUserId()).session(sessionId).assertEvent(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/Assert.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/Assert.java index 6c6799754bc9..b26cb3955fe7 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/Assert.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/Assert.java @@ -38,6 +38,7 @@ import org.keycloak.representations.info.ThemeInfoRepresentation; import org.hamcrest.MatcherAssert; +import org.junit.jupiter.api.Assertions; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsInAnyOrder; @@ -49,20 +50,20 @@ /** * @author Stian Thorgersen */ -public class Assert extends org.junit.Assert { +public class Assert extends Assertions { public static final Long DEFAULT_NUMBER_DEVIATION = 20L; public static void assertNames(Set actual, String... expected) { Arrays.sort(expected); String[] actualNames = names(new LinkedList(actual)); - assertArrayEquals("Expected: " + Arrays.toString(expected) + ", was: " + Arrays.toString(actualNames), expected, actualNames); + assertArrayEquals(expected, actualNames, "Expected: " + Arrays.toString(expected) + ", was: " + Arrays.toString(actualNames)); } public static void assertNames(List actual, String... expected) { Arrays.sort(expected); String[] actualNames = names(actual); - assertArrayEquals("Expected: " + Arrays.toString(expected) + ", was: " + Arrays.toString(actualNames), expected, actualNames); + assertArrayEquals(expected, actualNames, "Expected: " + Arrays.toString(expected) + ", was: " + Arrays.toString(actualNames)); } private static String[] names(List list) { @@ -118,11 +119,11 @@ public static void assertMap(Map config, String... expected) { expected = new String[] {}; } - Assert.assertEquals(config.size() * 2, expected.length); + Assertions.assertEquals(config.size() * 2, expected.length); for (int i=0 ; i confi for (int i=0 ; i> d : details.entrySet()) { String actualValue = actual.getDetails().get(d.getKey()); assertThat("Unexpected value for " + d.getKey(), actualValue, d.getValue()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AbstractRestServiceTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AbstractRestServiceTest.java index 36f142a3a283..d0f4bb9b6151 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AbstractRestServiceTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AbstractRestServiceTest.java @@ -41,8 +41,8 @@ import static org.keycloak.common.Profile.Feature.ACCOUNT_API; import static org.keycloak.testsuite.util.oauth.OAuthClient.APP_ROOT; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Stian Thorgersen diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceCorsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceCorsTest.java index ad176a23baf3..27266788d1b2 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceCorsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceCorsTest.java @@ -35,7 +35,7 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Stian Thorgersen diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceReadOnlyAttributesTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceReadOnlyAttributesTest.java index b0574aebfb12..6f52187100ad 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceReadOnlyAttributesTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceReadOnlyAttributesTest.java @@ -41,16 +41,16 @@ import org.keycloak.userprofile.UserProfileConstants; import org.jboss.logging.Logger; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Marek Posolda @@ -194,18 +194,18 @@ private void testAccountUpdateAttributeExpectFailure(String attrName, boolean de adminUserRep.singleAttribute(attrName, "foo"); adminUserResource.update(adminUserRep); if (deniedForAdminAsWell) { - Assert.fail("Not expected to update attribute " + attrName + " by admin REST API"); + Assertions.fail("Not expected to update attribute " + attrName + " by admin REST API"); } } catch (BadRequestException bre) { if (!deniedForAdminAsWell) { - Assert.fail("Was expected to update attribute " + attrName + " by admin REST API"); + Assertions.fail("Was expected to update attribute " + attrName + " by admin REST API"); } return; } // Update attribute of the user with account REST to the same value (Case when we are updating existing attribute) - should be fine as our attribute is not changed user = SimpleHttpDefault.doGet(getAccountUrl(null), httpClient).auth(tokenUtil.getToken()).asJson(UserRepresentation.class); - Assert.assertEquals("foo", user.getAttributes().get(attrName).get(0)); + Assertions.assertEquals("foo", user.getAttributes().get(attrName).get(0)); user.singleAttribute("someOtherAttr", "foo"); user = updateAndGet(user); @@ -236,7 +236,7 @@ private void testAccountUpdateAttributeExpectSuccess(String attrName) throws IOE // Update attribute of the user with account REST to the same value (Case when we are updating existing attribute) - should be fine as our attribute is not changed user = SimpleHttpDefault.doGet(getAccountUrl(null), httpClient).auth(tokenUtil.getToken()).asJson(UserRepresentation.class); - Assert.assertEquals("foo", user.getAttributes().get(attrName).get(0)); + Assertions.assertEquals("foo", user.getAttributes().get(attrName).get(0)); user.singleAttribute("someOtherAttr", "foo"); user = updateAndGet(user); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceTest.java index 98d2ad836cf4..5120d8aeb260 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceTest.java @@ -96,10 +96,10 @@ import org.apache.http.Header; import org.apache.http.impl.client.CloseableHttpClient; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.util.userprofile.UserProfileUtil.PERMISSIONS_ALL; @@ -108,11 +108,11 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stian Thorgersen @@ -254,9 +254,9 @@ protected static UserProfileAttributeMetadata assertUserProfileAttributeMetadata UserProfileAttributeMetadata uam = getUserProfileAttributeMetadata(user, attName); assertNotNull(uam); - assertEquals("Unexpected display name for attribute " + uam.getName(), displayName, uam.getDisplayName()); - assertEquals("Unexpected required flag for attribute " + uam.getName(), required, uam.isRequired()); - assertEquals("Unexpected readonly flag for attribute " + uam.getName(), readOnly, uam.isReadOnly()); + assertEquals(displayName, uam.getDisplayName(), "Unexpected display name for attribute " + uam.getName()); + assertEquals(required, uam.isRequired(), "Unexpected required flag for attribute " + uam.getName()); + assertEquals(readOnly, uam.isReadOnly(), "Unexpected readonly flag for attribute " + uam.getName()); return uam; } @@ -736,7 +736,7 @@ public void testCredentialsGet() throws IOException { List credentials = getCredentials(); - Assert.assertEquals(4, credentials.size()); + Assertions.assertEquals(4, credentials.size()); AccountCredentialResource.CredentialContainer password = credentials.get(0); assertCredentialContainerExpected(password, PasswordCredentialModel.TYPE, CredentialTypeMetadata.Category.BASIC_AUTHENTICATION.toString(), @@ -745,7 +745,7 @@ public void testCredentialsGet() throws IOException { CredentialRepresentation password1 = password.getUserCredentialMetadatas().get(0).getCredential(); assertNull(password1.getSecretData()); - Assert.assertNotNull(password1.getCredentialData()); + Assertions.assertNotNull(password1.getCredentialData()); AccountCredentialResource.CredentialContainer otp = credentials.get(1); assertCredentialContainerExpected(otp, OTPCredentialModel.TYPE, CredentialTypeMetadata.Category.TWO_FACTOR.toString(), @@ -779,18 +779,18 @@ public void testCredentialsGet() throws IOException { // Test password-only credentials = SimpleHttpDefault.doGet(getAccountUrl("credentials?" + AccountCredentialResource.TYPE + "=password"), httpClient) .auth(tokenUtil.getToken()).asJson(new TypeReference>() {}); - Assert.assertEquals(1, credentials.size()); + Assertions.assertEquals(1, credentials.size()); password = credentials.get(0); - Assert.assertEquals(PasswordCredentialModel.TYPE, password.getType()); - Assert.assertEquals(1, password.getUserCredentialMetadatas().size()); + Assertions.assertEquals(PasswordCredentialModel.TYPE, password.getType()); + Assertions.assertEquals(1, password.getUserCredentialMetadatas().size()); // Test password-only and user-credentials credentials = SimpleHttpDefault.doGet(getAccountUrl("credentials?" + AccountCredentialResource.TYPE + "=password&" + AccountCredentialResource.USER_CREDENTIALS + "=false"), httpClient) .auth(tokenUtil.getToken()).asJson(new TypeReference>() {}); - Assert.assertEquals(1, credentials.size()); + Assertions.assertEquals(1, credentials.size()); password = credentials.get(0); - Assert.assertEquals(PasswordCredentialModel.TYPE, password.getType()); + Assertions.assertEquals(PasswordCredentialModel.TYPE, password.getType()); assertNull(password.getUserCredentialMetadatas()); } @@ -827,7 +827,7 @@ public void testCRUDCredentialOfDifferentUser() throws IOException { .filter(credentialRep -> OTPCredentialModel.TYPE.equals(credentialRep.getType())) .findFirst() .get(); - Assert.assertTrue(ObjectUtil.isEqualOrBothNull(otpCredential.getUserLabel(), otpCredentialLoaded.getUserLabel())); + Assertions.assertTrue(ObjectUtil.isEqualOrBothNull(otpCredential.getUserLabel(), otpCredentialLoaded.getUserLabel())); } @Test @@ -847,15 +847,15 @@ public void testRemoveCredentialWithNonOtpCredentialTriggeringNoEvent() throws I user.update(userRep); credentials = getCredentials(); - Assert.assertEquals(2, credentials.size()); - Assert.assertTrue(credentials.get(1).isRemoveable()); + Assertions.assertEquals(2, credentials.size()); + Assertions.assertTrue(credentials.get(1).isRemoveable()); // Remove credential CredentialRepresentation credential = user.credentials().stream() .filter(credentialRep -> WebAuthnCredentialModel.TYPE_TWOFACTOR.equals(credentialRep.getType())) .findFirst() .get(); - Assert.assertNotNull(credential); + Assertions.assertNotNull(credential); user.removeCredential(credential.getId()); events.poll(); @@ -878,8 +878,8 @@ public void testRemoveCredentialWithOtpCredentialTriggeringEvent() throws IOExce user.update(userRep); credentials = getCredentials(); - Assert.assertEquals(2, credentials.size()); - Assert.assertTrue(credentials.get(1).isRemoveable()); + Assertions.assertEquals(2, credentials.size()); + Assertions.assertTrue(credentials.get(1).isRemoveable()); // Remove credential CredentialRepresentation otpCredential = user.credentials().stream() @@ -935,15 +935,15 @@ public void testCredentialsGetDisabledOtp() throws IOException { // Test that OTP credential is not included. Only password List credentials = getCredentials(); - Assert.assertEquals(1, credentials.size()); - Assert.assertEquals(PasswordCredentialModel.TYPE, credentials.get(0).getType()); + Assertions.assertEquals(1, credentials.size()); + Assertions.assertEquals(PasswordCredentialModel.TYPE, credentials.get(0).getType()); // Enable browser subflow. OTP should be available then setExecutionRequirement(DefaultAuthenticationFlows.BROWSER_FLOW, "Browser - Conditional 2FA", currentBrowserReq); credentials = getCredentials(); - Assert.assertEquals(2, credentials.size()); - Assert.assertEquals(OTPCredentialModel.TYPE, credentials.get(1).getType()); + Assertions.assertEquals(2, credentials.size()); + Assertions.assertEquals(OTPCredentialModel.TYPE, credentials.get(1).getType()); // Disable browser subflow and enable FirstBrokerLogin. OTP should be available then setExecutionRequirement(DefaultAuthenticationFlows.BROWSER_FLOW, @@ -951,8 +951,8 @@ public void testCredentialsGetDisabledOtp() throws IOException { setExecutionRequirement(DefaultAuthenticationFlows.FIRST_BROKER_LOGIN_FLOW, "OTP Form", currentFBLReq); credentials = getCredentials(); - Assert.assertEquals(2, credentials.size()); - Assert.assertEquals(OTPCredentialModel.TYPE, credentials.get(1).getType()); + Assertions.assertEquals(2, credentials.size()); + Assertions.assertEquals(OTPCredentialModel.TYPE, credentials.get(1).getType()); } finally { // Revert flows setExecutionRequirement(DefaultAuthenticationFlows.BROWSER_FLOW, @@ -1035,10 +1035,10 @@ private void setRequiredActionEnabledStatus(String requiredActionProviderId, boo } private void assertExpectedCredentialTypes(List credentialTypes, String... expectedCredentialTypes) { - Assert.assertEquals(credentialTypes.size(), expectedCredentialTypes.length); + Assertions.assertEquals(credentialTypes.size(), expectedCredentialTypes.length); int i = 0; for (AccountCredentialResource.CredentialContainer credential : credentialTypes) { - Assert.assertEquals(credential.getType(), expectedCredentialTypes[i]); + Assertions.assertEquals(credential.getType(), expectedCredentialTypes[i]); i++; } } @@ -1060,7 +1060,7 @@ public void testCredentialsForUserWithoutPassword() throws IOException { .auth(tokenUtil.getToken()) .asResponse()) { assertEquals(400, response.getStatus()); - Assert.assertEquals("Credential type cannot be removed", response.asJson(OAuth2ErrorRepresentation.class).getError()); + Assertions.assertEquals("Credential type cannot be removed", response.asJson(OAuth2ErrorRepresentation.class).getError()); } // Remove password from the user now @@ -1128,15 +1128,15 @@ private void removeWebAuthnFlow(String flowToDeleteAlias) { private void assertCredentialContainerExpected(AccountCredentialResource.CredentialContainer credential, String type, String category, String displayName, String helpText, String iconCssClass, String createAction, String updateAction, boolean removeable, int userCredentialsCount) { - Assert.assertEquals(type, credential.getType()); - Assert.assertEquals(category, credential.getCategory()); - Assert.assertEquals(displayName, credential.getDisplayName()); - Assert.assertEquals(helpText, credential.getHelptext()); - Assert.assertEquals(iconCssClass, credential.getIconCssClass()); - Assert.assertEquals(createAction, credential.getCreateAction()); - Assert.assertEquals(updateAction, credential.getUpdateAction()); - Assert.assertEquals(removeable, credential.isRemoveable()); - Assert.assertEquals(userCredentialsCount, credential.getUserCredentialMetadatas().size()); + Assertions.assertEquals(type, credential.getType()); + Assertions.assertEquals(category, credential.getCategory()); + Assertions.assertEquals(displayName, credential.getDisplayName()); + Assertions.assertEquals(helpText, credential.getHelptext()); + Assertions.assertEquals(iconCssClass, credential.getIconCssClass()); + Assertions.assertEquals(createAction, credential.getCreateAction()); + Assertions.assertEquals(updateAction, credential.getUpdateAction()); + Assertions.assertEquals(removeable, credential.isRemoveable()); + Assertions.assertEquals(userCredentialsCount, credential.getUserCredentialMetadatas().size()); } public void testDeleteSessions() throws IOException { @@ -1987,7 +1987,7 @@ public void testAudience() throws Exception { // update to correct audience org.keycloak.representations.idm.ClientRepresentation clientRep = testRealm().clients().findByClientId("custom-audience").get(0); ProtocolMapperRepresentation mapperRep = clientRep.getProtocolMappers().stream().filter(m -> m.getName().equals("aud")).findFirst().orElse(null); - assertNotNull("Audience mapper not found", mapperRep); + assertNotNull(mapperRep, "Audience mapper not found"); mapperRep.getConfig().put("included.custom.audience", "account"); testRealm().clients().get(clientRep.getId()).getProtocolMappers().update(mapperRep.getId(), mapperRep); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceWithUserProfileTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceWithUserProfileTest.java index 5870eb7e92df..9f82e030820a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceWithUserProfileTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceWithUserProfileTest.java @@ -57,10 +57,10 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test account rest service with custom user profile configurations @@ -303,13 +303,13 @@ public void testEditUsernameDisallowed() throws IOException { } protected void assertAnnotationValue(UserProfileAttributeMetadata uam, String key, Object value) { - assertNotNull("Missing annotations for attribute " + uam.getName(), uam.getAnnotations()); - assertEquals("Unexpexted value of the "+key+" annotation for attribute " + uam.getName(), value, uam.getAnnotations().get(key)); + assertNotNull(uam.getAnnotations(), "Missing annotations for attribute " + uam.getName()); + assertEquals(value, uam.getAnnotations().get(key), "Unexpexted value of the "+key+" annotation for attribute " + uam.getName()); } protected Map assertValidatorExists(UserProfileAttributeMetadata uam, String validatorId) { - assertNotNull("Missing validators for attribute " + uam.getName(), uam.getValidators()); - assertTrue("Missing validtor "+validatorId+" for attribute " + uam.getName(), uam.getValidators().containsKey(validatorId)); + assertNotNull(uam.getValidators(), "Missing validators for attribute " + uam.getName()); + assertTrue(uam.getValidators().containsKey(validatorId), "Missing validtor "+validatorId+" for attribute " + uam.getName()); return uam.getValidators().get(validatorId); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/LinkedAccountsRestServiceTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/LinkedAccountsRestServiceTest.java index e36181c177f7..b22ffdcd72ff 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/LinkedAccountsRestServiceTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/LinkedAccountsRestServiceTest.java @@ -55,11 +55,11 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stan Silvert diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/ResourcesRestServiceTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/ResourcesRestServiceTest.java index c71e0a6cdc54..0dfe7011ffdd 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/ResourcesRestServiceTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/ResourcesRestServiceTest.java @@ -68,11 +68,11 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor @@ -458,17 +458,21 @@ public void testEndpointPermissions() throws Exception { // test read access for (String url : Arrays.asList(resourcesUrl, sharedWithOthersUrl, sharedWithMeUrl, resourceUrl, permissionsUrl, requestsUrl)) { - assertEquals( "no-account-access GET " + url, 403, - SimpleHttpDefault.doGet(url, httpClient).acceptJson().auth(noAccessTokenUtil.getToken()).asStatus()); - assertEquals("view-account-access GET " + url,200, - SimpleHttpDefault.doGet(url, httpClient).acceptJson().auth(viewProfileTokenUtil.getToken()).asStatus()); + assertEquals( 403, + SimpleHttpDefault.doGet(url, httpClient).acceptJson().auth(noAccessTokenUtil.getToken()).asStatus(), + "no-account-access GET " + url); + assertEquals(200, + SimpleHttpDefault.doGet(url, httpClient).acceptJson().auth(viewProfileTokenUtil.getToken()).asStatus(), + "view-account-access GET " + url); } // test write access - assertEquals( "no-account-access PUT " + permissionsUrl, 403, - SimpleHttpDefault.doPut(permissionsUrl, httpClient).acceptJson().auth(noAccessTokenUtil.getToken()).json(Collections.emptyList()).asStatus()); - assertEquals( "view-account-access PUT " + permissionsUrl, 403, - SimpleHttpDefault.doPut(permissionsUrl, httpClient).acceptJson().auth(viewProfileTokenUtil.getToken()).json(Collections.emptyList()).asStatus()); + assertEquals( 403, + SimpleHttpDefault.doPut(permissionsUrl, httpClient).acceptJson().auth(noAccessTokenUtil.getToken()).json(Collections.emptyList()).asStatus(), + "no-account-access PUT " + permissionsUrl); + assertEquals( 403, + SimpleHttpDefault.doPut(permissionsUrl, httpClient).acceptJson().auth(viewProfileTokenUtil.getToken()).json(Collections.emptyList()).asStatus(), + "view-account-access PUT " + permissionsUrl); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/SessionRestServiceTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/SessionRestServiceTest.java index b429f452a21e..dcf71ebca8bc 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/SessionRestServiceTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/SessionRestServiceTest.java @@ -43,10 +43,10 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stian Thorgersen @@ -153,7 +153,7 @@ public void testGetDevicesResponse() throws Exception { List devices = getDevicesOtherThanOther(tokenResponse.getAccessToken()); - assertEquals("Should have a single device", 1, devices.size()); + assertEquals(1, devices.size(), "Should have a single device"); DeviceRepresentation device = devices.get(0); @@ -188,10 +188,10 @@ public void testGetDevicesSessions() throws Exception { setBrowserHeader("User-Agent", "Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:15.0) Gecko/20100101 Firefox/15.0.1"); AccessTokenResponse tokenResponse1 = codeGrant("public-client-0"); List devices = getDevicesOtherThanOther(); - assertEquals("Should have a single device", 1, devices.size()); + assertEquals(1, devices.size(), "Should have a single device"); List fedoraDevices = devices.stream() .filter(deviceRepresentation -> "Fedora".equals(deviceRepresentation.getOs())).collect(Collectors.toList()); - assertEquals("Should have a single Fedora device", 1, fedoraDevices.size()); + assertEquals(1, fedoraDevices.size(), "Should have a single Fedora device"); fedoraDevices.stream().forEach(device -> { List sessions = device.getSessions(); assertEquals(1, sessions.size()); @@ -205,7 +205,7 @@ public void testGetDevicesSessions() throws Exception { AccessTokenResponse tokenResponse2 = codeGrant("public-client-0"); devices = getDevicesOtherThanOther(); // should have two devices - assertEquals("Should have two devices", 2, devices.size()); + assertEquals(2, devices.size(), "Should have two devices"); fedoraDevices = devices.stream() .filter(deviceRepresentation -> "Fedora".equals(deviceRepresentation.getOs())).collect(Collectors.toList()); assertEquals(1, fedoraDevices.size()); @@ -240,8 +240,7 @@ public void testGetDevicesSessions() throws Exception { AccessTokenResponse tokenResponse3 = codeGrant("public-client-0"); devices = getDevicesOtherThanOther(tokenResponse3.getAccessToken()); assertEquals( - "Should have a single device because all browsers (and sessions) are from the same platform (OS + OS version)", - 1, devices.size()); + 1, devices.size(), "Should have a single device because all browsers (and sessions) are from the same platform (OS + OS version)"); windowsDevices = devices.stream() .filter(device -> "Windows".equals(device.getOs())).collect(Collectors.toList()); assertEquals(1, windowsDevices.size()); @@ -269,7 +268,7 @@ public void testGetDevicesSessions() throws Exception { devices = getDevicesOtherThanOther(); windowsDevices = devices.stream() .filter(device -> "Windows".equals(device.getOs())).collect(Collectors.toList()); - assertEquals("Should have two devices for two distinct Windows versions", 2, devices.size()); + assertEquals(2, devices.size(), "Should have two devices for two distinct Windows versions"); assertEquals(2, windowsDevices.size()); oauth.setDriver(firstBrowser); @@ -284,7 +283,7 @@ public void testGetDevicesSessions() throws Exception { "Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:15.0) Gecko/20100101 Firefox/15.0.1"); tokenResponse2 = codeGrant("public-client-0"); devices = getDevicesOtherThanOther(); - assertEquals("Should have 3 devices", 3, devices.size()); + assertEquals(3, devices.size(), "Should have 3 devices"); windowsDevices = devices.stream() .filter(device -> "Windows".equals(device.getOs())).collect(Collectors.toList()); assertEquals(1, windowsDevices.size()); @@ -362,7 +361,7 @@ public void testNullOrEmptyUserAgent() throws Exception { List devices = queryDevices(tokenResponse.getAccessToken()); - assertEquals("Should have a single device", 1, devices.size()); + assertEquals(1, devices.size(), "Should have a single device"); DeviceRepresentation device = devices.get(0); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/custom/CustomAuthFlowCookieTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/custom/CustomAuthFlowCookieTest.java index 856391175744..27c75be606f4 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/custom/CustomAuthFlowCookieTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/custom/CustomAuthFlowCookieTest.java @@ -20,7 +20,7 @@ import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/custom/CustomAuthFlowOTPTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/custom/CustomAuthFlowOTPTest.java index 78bb1eb534c2..70a07f0045a5 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/custom/CustomAuthFlowOTPTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/custom/CustomAuthFlowOTPTest.java @@ -66,8 +66,8 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @@ -551,7 +551,7 @@ private void setConditionalOTPForm(Map config) { flow.setBuiltIn(false); try (Response response = getAuthMgmtResource().createFlow(flow)) { - assertEquals(flowAlias + " create success", 201, response.getStatus()); + assertEquals(201, response.getStatus(), flowAlias + " create success"); } //add execution - username-password form @@ -586,7 +586,7 @@ private void setConditionalOTPForm(Map config) { //add auth config to the execution try (Response response = getAuthMgmtResource().newExecutionConfig(executionId, authConfig)) { - assertEquals("new execution success", 201, response.getStatus()); + assertEquals(201, response.getStatus(), "new execution success"); getCleanup().addAuthenticationConfigId(ApiUtil.getCreatedId(response)); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AbstractAppInitiatedActionUpdateEmailTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AbstractAppInitiatedActionUpdateEmailTest.java index 6ed5196e5f15..8f4cecd24da8 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AbstractAppInitiatedActionUpdateEmailTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AbstractAppInitiatedActionUpdateEmailTest.java @@ -26,9 +26,9 @@ import org.keycloak.testsuite.util.UserBuilder; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; public abstract class AbstractAppInitiatedActionUpdateEmailTest extends AbstractAppInitiatedActionTest { @@ -84,7 +84,7 @@ public void cancelUpdateEmail() { // assert nothing was updated in persistent store UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost"); - Assert.assertEquals("test-user@localhost", user.getEmail()); + Assertions.assertEquals("test-user@localhost", user.getEmail()); } @Test @@ -97,10 +97,10 @@ public void updateToExistingEmail() { emailUpdatePage.changeEmail("john-doh@localhost"); emailUpdatePage.assertCurrent(); - Assert.assertEquals("Email already exists.", emailUpdatePage.getEmailError()); + Assertions.assertEquals("Email already exists.", emailUpdatePage.getEmailError()); UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost"); - Assert.assertEquals("test-user@localhost", user.getEmail()); + Assertions.assertEquals("test-user@localhost", user.getEmail()); } @Test @@ -113,10 +113,10 @@ public void updateToInvalidEmail(){ emailUpdatePage.changeEmail("invalidemail"); emailUpdatePage.assertCurrent(); - Assert.assertEquals("Invalid email address.", emailUpdatePage.getEmailError()); + Assertions.assertEquals("Invalid email address.", emailUpdatePage.getEmailError()); UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost"); - Assert.assertEquals("test-user@localhost", user.getEmail()); + Assertions.assertEquals("test-user@localhost", user.getEmail()); } @Test @@ -129,10 +129,10 @@ public void updateToBlankEmail(){ emailUpdatePage.changeEmail(""); emailUpdatePage.assertCurrent(); - Assert.assertTrue(emailUpdatePage.getEmailError().contains("Please specify email.")); + Assertions.assertTrue(emailUpdatePage.getEmailError().contains("Please specify email.")); UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost"); - Assert.assertEquals("test-user@localhost", user.getEmail()); + Assertions.assertEquals("test-user@localhost", user.getEmail()); } @Test @@ -146,7 +146,7 @@ public void updateWithEmailAsUsernameEnabled() throws Exception { changeEmailUsingAIA("new@email.com"); UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "new@email.com"); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); } finally { setRegistrationEmailAsUsername(testRealm(), genuineRegistrationEmailAsUsername); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AbstractRequiredActionUpdateEmailTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AbstractRequiredActionUpdateEmailTest.java index dcd09cbf2d17..00a82a5d9337 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AbstractRequiredActionUpdateEmailTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AbstractRequiredActionUpdateEmailTest.java @@ -39,14 +39,14 @@ import org.jboss.arquillian.drone.api.annotation.Drone; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebDriver; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; @EnableFeature(Profile.Feature.UPDATE_EMAIL) public abstract class AbstractRequiredActionUpdateEmailTest extends AbstractTestRealmKeycloakTest { @@ -142,9 +142,9 @@ public void updateEmailMissing() { updateEmailPage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("", updateEmailPage.getEmail()); + Assertions.assertEquals("", updateEmailPage.getEmail()); - Assert.assertTrue(updateEmailPage.getEmailInputError().contains("Please specify email.")); + Assertions.assertTrue(updateEmailPage.getEmailInputError().contains("Please specify email.")); events.assertEmpty(); } @@ -162,9 +162,9 @@ public void updateEmailDuplicate() { updateEmailPage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("test-user@localhost", updateEmailPage.getEmail()); + Assertions.assertEquals("test-user@localhost", updateEmailPage.getEmail()); - Assert.assertEquals("Email already exists.", updateEmailPage.getEmailInputError()); + Assertions.assertEquals("Email already exists.", updateEmailPage.getEmailInputError()); events.assertEmpty(); } @@ -182,9 +182,9 @@ public void updateEmailInvalid() { updateEmailPage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("invalid", updateEmailPage.getEmail()); + Assertions.assertEquals("invalid", updateEmailPage.getEmail()); - Assert.assertEquals("Invalid email address.", updateEmailPage.getEmailInputError()); + Assertions.assertEquals("Invalid email address.", updateEmailPage.getEmailInputError()); events.assertEmpty(); } @@ -204,7 +204,7 @@ public void updateEmailWithEmailAsUsernameEnabled() throws Exception { assertNotNull(lastName); changeEmailUsingRequiredAction("new@localhost", true, true); user = ActionUtil.findUserWithAdminClient(adminClient, "new@localhost"); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); firstName = user.getFirstName(); lastName = user.getLastName(); assertNotNull(firstName); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionDeleteCredentialTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionDeleteCredentialTest.java index 1d3714224be3..c56d957845c0 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionDeleteCredentialTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionDeleteCredentialTest.java @@ -49,10 +49,10 @@ import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @author Marek Posolda @@ -123,7 +123,7 @@ public void removeOtpSuccess() throws Exception { appPage.assertCurrent(); assertKcActionStatus("success"); - Assert.assertNull(getCredentialIdByType(OTPCredentialModel.TYPE)); + Assertions.assertNull(getCredentialIdByType(OTPCredentialModel.TYPE)); events.expect(EventType.REMOVE_TOTP) .user(userId) @@ -139,10 +139,10 @@ public void removeOtpSuccess() throws Exception { .assertEvent(); MimeMessage[] receivedMessages = greenMail.getReceivedMessages(); - Assert.assertEquals(2, receivedMessages.length); + Assertions.assertEquals(2, receivedMessages.length); - Assert.assertEquals("Remove OTP", receivedMessages[0].getSubject()); - Assert.assertEquals("Remove credential", receivedMessages[1].getSubject()); + Assertions.assertEquals("Remove OTP", receivedMessages[0].getSubject()); + Assertions.assertEquals("Remove credential", receivedMessages[1].getSubject()); MatcherAssert.assertThat(MailUtils.getBody(receivedMessages[1]).getText(), Matchers.startsWith("Credential otp was removed from your account")); MatcherAssert.assertThat(MailUtils.getBody(receivedMessages[1]).getHtml(), @@ -168,7 +168,7 @@ public void removeOtpCancel() throws Exception { appPage.assertCurrent(); - Assert.assertNotNull(getCredentialIdByType(OTPCredentialModel.TYPE)); + Assertions.assertNotNull(getCredentialIdByType(OTPCredentialModel.TYPE)); } @Test @@ -263,7 +263,7 @@ public void removeOtpCustomLabel() throws Exception { appPage.assertCurrent(); assertKcActionStatus("success"); - Assert.assertNull(getCredentialIdByType(OTPCredentialModel.TYPE)); + Assertions.assertNull(getCredentialIdByType(OTPCredentialModel.TYPE)); events.expect(EventType.REMOVE_TOTP) .user(userId) diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionResetPasswordTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionResetPasswordTest.java index ad32d01815a8..5a84f8fe7feb 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionResetPasswordTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionResetPasswordTest.java @@ -61,15 +61,16 @@ import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.Cookie; import org.openqa.selenium.WebDriver; import static org.hamcrest.Matchers.contains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stan Silvert @@ -164,10 +165,10 @@ public void resetPassword() throws Exception { events.expectRequiredAction(EventType.UPDATE_CREDENTIAL).detail(Details.CREDENTIAL_TYPE, PasswordCredentialModel.TYPE).assertEvent(); MimeMessage[] receivedMessages = greenMail.getReceivedMessages(); - Assert.assertEquals(2, receivedMessages.length); + Assertions.assertEquals(2, receivedMessages.length); - Assert.assertEquals("Update password", receivedMessages[0].getSubject()); - Assert.assertEquals("Update credential", receivedMessages[1].getSubject()); + Assertions.assertEquals("Update password", receivedMessages[0].getSubject()); + Assertions.assertEquals("Update credential", receivedMessages[1].getSubject()); MatcherAssert.assertThat(MailUtils.getBody(receivedMessages[1]).getText(), Matchers.startsWith("Your password credential was changed")); MatcherAssert.assertThat(MailUtils.getBody(receivedMessages[1]).getHtml(), @@ -202,7 +203,7 @@ public void resetPasswordRequiresReAuth() { doAIA(); loginPage.assertCurrent(); - Assert.assertEquals("test-user@localhost", loginPage.getAttemptedUsername()); + Assertions.assertEquals("test-user@localhost", loginPage.getAttemptedUsername()); loginPage.login("password"); changePasswordPage.assertCurrent(); @@ -239,7 +240,7 @@ public void resetPasswordRequiresReAuthWithIndividualMaxAuthAgeConfig() throws E doAIA(); loginPage.assertCurrent(); - Assert.assertEquals("test-user@localhost", loginPage.getAttemptedUsername()); + Assertions.assertEquals("test-user@localhost", loginPage.getAttemptedUsername()); loginPage.login("password"); @@ -317,7 +318,7 @@ public void resetPasswordRequiresReAuthWithMaxAuthAgePasswordPolicy() { loginPage.assertCurrent(); - Assert.assertEquals("test-user@localhost", loginPage.getAttemptedUsername()); + Assertions.assertEquals("test-user@localhost", loginPage.getAttemptedUsername()); loginPage.login("password"); @@ -367,7 +368,7 @@ public void cancelWhenOTPRequiredAction() { // Cancel button should not be displayed totpPage.assertCurrent(); - Assert.assertFalse(totpPage.isCancelDisplayed()); + Assertions.assertFalse(totpPage.isCancelDisplayed()); // Try to manually send POST request from browser with cancel the AIA String actionUrl = URLUtils.getActionUrlFromCurrentPage(driver); @@ -435,7 +436,7 @@ public void checkLogoutSessions() { sessions = testUser.getUserSessions(); assertEquals(1, sessions.size()); - assertEquals("Old session is still valid", firstSessionId, sessions.get(0).getId()); + assertEquals(firstSessionId, sessions.get(0).getId(), "Old session is still valid"); } @Test @@ -455,7 +456,7 @@ public void uncheckLogoutSessions() { doAIA(); changePasswordPage.assertCurrent(); - assertFalse("Logout other sessions was ticked", changePasswordPage.isLogoutSessionsChecked()); + assertFalse(changePasswordPage.isLogoutSessionsChecked(), "Logout other sessions was ticked"); changePasswordPage.changePassword("All Right Then, Keep Your Secrets", "All Right Then, Keep Your Secrets"); events.expectRequiredAction(EventType.UPDATE_PASSWORD).assertEvent(); events.expectRequiredAction(EventType.UPDATE_CREDENTIAL).detail(Details.CREDENTIAL_TYPE, PasswordCredentialModel.TYPE).assertEvent(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionTest.java index 6b3f9ec6bae0..ebf1e6d7da64 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionTest.java @@ -37,8 +37,8 @@ import static org.keycloak.testsuite.actions.AbstractAppInitiatedActionTest.SUCCESS; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Hiroyuki Wada diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionTotpSetupTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionTotpSetupTest.java index ecc82dbdee22..d6191207b025 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionTotpSetupTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionTotpSetupTest.java @@ -47,14 +47,14 @@ import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stan Silvert @@ -459,7 +459,7 @@ public void setupTotpRegisteredAfterTotpRemoval() { String uri = driver.getCurrentUrl(); String src = driver.getPageSource(); assertTrue(loginPage.isCurrent()); - Assert.assertFalse(totpPage.isCurrent()); + Assertions.assertFalse(totpPage.isCurrent()); setOtpTimeOffset(TimeBasedOTP.DEFAULT_INTERVAL_SECONDS, totp); @@ -468,7 +468,7 @@ public void setupTotpRegisteredAfterTotpRemoval() { events.expectLogin().user(userId).detail(Details.USERNAME, "setupTotp2").assertEvent(); // Remove google authenticator - Assert.assertTrue(AccountHelper.deleteTotpAuthentication(testRealm(),"setupTotp2")); + Assertions.assertTrue(AccountHelper.deleteTotpAuthentication(testRealm(),"setupTotp2")); AccountHelper.logout(testRealm(),"setupTotp2"); // Try to login @@ -659,9 +659,9 @@ private void setupTotpRegisterVerifyRecoveryCodesSetup(boolean enforceRecoveryCo try { // This should now fail setupRecoveryAuthnCodesPage.assertCurrent(); - Assert.fail("Expected AssertionError was not thrown"); + Assertions.fail("Expected AssertionError was not thrown"); } catch (AssertionError e) { - Assert.assertTrue(e.getMessage().startsWith("Expected SetupRecoveryAuthnCodesPage")); + Assertions.assertTrue(e.getMessage().startsWith("Expected SetupRecoveryAuthnCodesPage")); } } finally { // finally, reset totp action config diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionUpdateEmailTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionUpdateEmailTest.java index 4f48cecb4d4d..fa24e04f6d8f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionUpdateEmailTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionUpdateEmailTest.java @@ -37,8 +37,8 @@ import org.keycloak.validate.validators.LengthValidator; import org.junit.After; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.FindBy; @@ -47,8 +47,8 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class AppInitiatedActionUpdateEmailTest extends AbstractAppInitiatedActionUpdateEmailTest { @@ -79,9 +79,9 @@ public void updateEmail() throws Exception { assertKcActionStatus("success"); UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost"); - Assert.assertEquals("new@email.com", user.getEmail()); - Assert.assertEquals("Tom", user.getFirstName()); - Assert.assertEquals("Brady", user.getLastName()); + Assertions.assertEquals("new@email.com", user.getEmail()); + Assertions.assertEquals("Tom", user.getFirstName()); + Assertions.assertEquals("Brady", user.getLastName()); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionUpdateEmailWithVerificationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionUpdateEmailWithVerificationTest.java index b07487447ddb..721947563f31 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionUpdateEmailWithVerificationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionUpdateEmailWithVerificationTest.java @@ -43,9 +43,9 @@ import org.hamcrest.Matchers; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; @@ -54,8 +54,8 @@ import static org.keycloak.testsuite.util.ServerURLs.getAuthServerContextRoot; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class AppInitiatedActionUpdateEmailWithVerificationTest extends AbstractAppInitiatedActionUpdateEmailTest { @@ -88,7 +88,7 @@ protected void changeEmailUsingAIA(String newEmail) throws Exception { emailUpdatePage.changeEmail(newEmail); events.expect(EventType.SEND_VERIFY_EMAIL).detail(Details.EMAIL, newEmail).assertEvent(); - Assert.assertEquals("test-user@localhost", ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost").getEmail()); + Assertions.assertEquals("test-user@localhost", ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost").getEmail()); driver.navigate().to(fetchEmailConfirmationLink(newEmail)); @@ -104,7 +104,7 @@ public void updateEmail() throws Exception { .detail(Details.PREVIOUS_EMAIL, "test-user@localhost") .detail(Details.UPDATED_EMAIL, "new@localhost"); - Assert.assertEquals("new@localhost", ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost").getEmail()); + Assertions.assertEquals("new@localhost", ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost").getEmail()); } @Test @@ -151,10 +151,10 @@ public void confirmEmailAfterDuplicateEmailSetForThirdPartyAccount() throws Mess private String fetchEmailConfirmationLink(String emailRecipient) throws MessagingException, IOException { MimeMessage[] receivedMessages = greenMail.getReceivedMessages(); - Assert.assertEquals(1, receivedMessages.length); + Assertions.assertEquals(1, receivedMessages.length); MimeMessage message = receivedMessages[0]; Address[] recipients = message.getRecipients(Message.RecipientType.TO); - Assert.assertTrue(recipients.length >= 1); + Assertions.assertTrue(recipients.length >= 1); assertEquals(emailRecipient, recipients[0].toString()); return MailUtils.getPasswordResetEmailLink(message).trim(); @@ -170,7 +170,7 @@ public void updateEmailWithRedirect() throws Exception { emailUpdatePage.changeEmail("new@localhost"); events.expect(EventType.SEND_VERIFY_EMAIL).detail(Details.EMAIL, "new@localhost").assertEvent(); - Assert.assertEquals("test-user@localhost", ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost").getEmail()); + Assertions.assertEquals("test-user@localhost", ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost").getEmail()); String link = fetchEmailConfirmationLink("new@localhost"); String token = link.substring(link.indexOf("key=") + "key=".length()).split("&")[0]; try { @@ -191,7 +191,7 @@ public void updateEmailWithRedirect() throws Exception { events.expect(EventType.UPDATE_EMAIL) .detail(Details.PREVIOUS_EMAIL, "test-user@localhost") .detail(Details.UPDATED_EMAIL, "new@localhost"); - Assert.assertEquals("new@localhost", ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost").getEmail()); + Assertions.assertEquals("new@localhost", ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost").getEmail()); } @Test @@ -238,7 +238,7 @@ public void updateEmailWithVerificationBackToApplicationInCleanBrowserShouldTrig events.expect(EventType.UPDATE_EMAIL) .detail(Details.PREVIOUS_EMAIL, "test-user@localhost") .detail(Details.UPDATED_EMAIL, "new@localhost"); - Assert.assertEquals("new@localhost", ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost").getEmail()); + Assertions.assertEquals("new@localhost", ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost").getEmail()); } finally { // Restore original client configuration diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionUpdateProfileTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionUpdateProfileTest.java index 35f708da4a6f..75ab879c1776 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionUpdateProfileTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionUpdateProfileTest.java @@ -29,9 +29,9 @@ import org.hamcrest.Matchers; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.anyOf; @@ -100,10 +100,10 @@ public void updateProfile() { // assert user is really updated in persistent store UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost"); - Assert.assertEquals("New first", user.getFirstName()); - Assert.assertEquals("New last", user.getLastName()); - Assert.assertEquals("new@email.com", user.getEmail()); - Assert.assertEquals("test-user@localhost", user.getUsername()); + Assertions.assertEquals("New first", user.getFirstName()); + Assertions.assertEquals("New last", user.getLastName()); + Assertions.assertEquals("new@email.com", user.getEmail()); + Assertions.assertEquals("test-user@localhost", user.getUsername()); } @Test @@ -131,10 +131,10 @@ public void updateProfileLoginFirst() { // assert user is really updated in persistent store UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost"); - Assert.assertEquals("New first", user.getFirstName()); - Assert.assertEquals("New last", user.getLastName()); - Assert.assertEquals("new@email.com", user.getEmail()); - Assert.assertEquals("test-user@localhost", user.getUsername()); + Assertions.assertEquals("New first", user.getFirstName()); + Assertions.assertEquals("New last", user.getLastName()); + Assertions.assertEquals("new@email.com", user.getEmail()); + Assertions.assertEquals("test-user@localhost", user.getUsername()); } @Test @@ -151,10 +151,10 @@ public void cancelUpdateProfile() { // assert nothing was updated in persistent store UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost"); - Assert.assertEquals("Tom", user.getFirstName()); - Assert.assertEquals("Brady", user.getLastName()); - Assert.assertEquals("test-user@localhost", user.getEmail()); - Assert.assertEquals("test-user@localhost", user.getUsername()); + Assertions.assertEquals("Tom", user.getFirstName()); + Assertions.assertEquals("Brady", user.getLastName()); + Assertions.assertEquals("test-user@localhost", user.getEmail()); + Assertions.assertEquals("test-user@localhost", user.getUsername()); } @@ -187,10 +187,10 @@ public void updateUsername() { // assert user is really updated in persistent store UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "new"); - Assert.assertEquals("New first", user.getFirstName()); - Assert.assertEquals("New last", user.getLastName()); - Assert.assertEquals("john-doh@localhost", user.getEmail()); - Assert.assertEquals("new", user.getUsername()); + Assertions.assertEquals("New first", user.getFirstName()); + Assertions.assertEquals("New last", user.getLastName()); + Assertions.assertEquals("john-doh@localhost", user.getEmail()); + Assertions.assertEquals("new", user.getUsername()); getCleanup().addUserId(user.getId()); } @@ -207,11 +207,11 @@ public void updateProfileMissingFirstName() { updateProfilePage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("", updateProfilePage.getFirstName()); - Assert.assertEquals("New last", updateProfilePage.getLastName()); - Assert.assertEquals("new@email.com", updateProfilePage.getEmail()); + Assertions.assertEquals("", updateProfilePage.getFirstName()); + Assertions.assertEquals("New last", updateProfilePage.getLastName()); + Assertions.assertEquals("new@email.com", updateProfilePage.getEmail()); - Assert.assertEquals("Please specify this field.", updateProfilePage.getInputErrors().getFirstNameError()); + Assertions.assertEquals("Please specify this field.", updateProfilePage.getInputErrors().getFirstNameError()); events.assertEmpty(); } @@ -229,11 +229,11 @@ public void updateProfileMissingLastName() { updateProfilePage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("New first", updateProfilePage.getFirstName()); - Assert.assertEquals("", updateProfilePage.getLastName()); - Assert.assertEquals("new@email.com", updateProfilePage.getEmail()); + Assertions.assertEquals("New first", updateProfilePage.getFirstName()); + Assertions.assertEquals("", updateProfilePage.getLastName()); + Assertions.assertEquals("new@email.com", updateProfilePage.getEmail()); - Assert.assertEquals("Please specify this field.", updateProfilePage.getInputErrors().getLastNameError()); + Assertions.assertEquals("Please specify this field.", updateProfilePage.getInputErrors().getLastNameError()); events.assertEmpty(); } @@ -251,9 +251,9 @@ public void updateProfileMissingEmail() { updateProfilePage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("New first", updateProfilePage.getFirstName()); - Assert.assertEquals("New last", updateProfilePage.getLastName()); - Assert.assertEquals("", updateProfilePage.getEmail()); + Assertions.assertEquals("New first", updateProfilePage.getFirstName()); + Assertions.assertEquals("New last", updateProfilePage.getLastName()); + Assertions.assertEquals("", updateProfilePage.getEmail()); assertThat(updateProfilePage.getInputErrors().getEmailError(), anyOf( containsString("Please specify email"), @@ -276,11 +276,11 @@ public void updateProfileInvalidEmail() { updateProfilePage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("New first", updateProfilePage.getFirstName()); - Assert.assertEquals("New last", updateProfilePage.getLastName()); - Assert.assertEquals("invalidemail", updateProfilePage.getEmail()); + Assertions.assertEquals("New first", updateProfilePage.getFirstName()); + Assertions.assertEquals("New last", updateProfilePage.getLastName()); + Assertions.assertEquals("invalidemail", updateProfilePage.getEmail()); - Assert.assertEquals("Invalid email address.", updateProfilePage.getInputErrors().getEmailError()); + Assertions.assertEquals("Invalid email address.", updateProfilePage.getInputErrors().getEmailError()); events.assertEmpty(); } @@ -298,12 +298,12 @@ public void updateProfileMissingUsername() { updateProfilePage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("New first", updateProfilePage.getFirstName()); - Assert.assertEquals("New last", updateProfilePage.getLastName()); - Assert.assertEquals("new@email.com", updateProfilePage.getEmail()); - Assert.assertEquals("", updateProfilePage.getUsername()); + Assertions.assertEquals("New first", updateProfilePage.getFirstName()); + Assertions.assertEquals("New last", updateProfilePage.getLastName()); + Assertions.assertEquals("new@email.com", updateProfilePage.getEmail()); + Assertions.assertEquals("", updateProfilePage.getUsername()); - Assert.assertEquals("Please specify username.", updateProfilePage.getInputErrors().getUsernameError()); + Assertions.assertEquals("Please specify username.", updateProfilePage.getInputErrors().getUsernameError()); events.assertEmpty(); } @@ -321,12 +321,12 @@ public void updateProfileDuplicateUsername() { updateProfilePage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("New first", updateProfilePage.getFirstName()); - Assert.assertEquals("New last", updateProfilePage.getLastName()); - Assert.assertEquals("new@email.com", updateProfilePage.getEmail()); - Assert.assertEquals("test-user@localhost", updateProfilePage.getUsername()); + Assertions.assertEquals("New first", updateProfilePage.getFirstName()); + Assertions.assertEquals("New last", updateProfilePage.getLastName()); + Assertions.assertEquals("new@email.com", updateProfilePage.getEmail()); + Assertions.assertEquals("test-user@localhost", updateProfilePage.getUsername()); - Assert.assertEquals("Username already exists.", updateProfilePage.getInputErrors().getUsernameError()); + Assertions.assertEquals("Username already exists.", updateProfilePage.getInputErrors().getUsernameError()); events.assertEmpty(); } @@ -344,11 +344,11 @@ public void updateProfileDuplicatedEmail() { updateProfilePage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("New first", updateProfilePage.getFirstName()); - Assert.assertEquals("New last", updateProfilePage.getLastName()); - Assert.assertEquals("keycloak-user@localhost", updateProfilePage.getEmail()); + Assertions.assertEquals("New first", updateProfilePage.getFirstName()); + Assertions.assertEquals("New last", updateProfilePage.getLastName()); + Assertions.assertEquals("keycloak-user@localhost", updateProfilePage.getEmail()); - Assert.assertEquals("Email already exists.", updateProfilePage.getInputErrors().getEmailError()); + Assertions.assertEquals("Email already exists.", updateProfilePage.getInputErrors().getEmailError()); events.assertEmpty(); } @@ -369,7 +369,7 @@ public void updateProfileExpiredCookies() { String backToAppLink = errorPage.getBackToApplicationLink(); ClientRepresentation client = AdminApiUtil.findClientByClientId(adminClient.realm("test"), "test-app").toRepresentation(); - Assert.assertEquals(backToAppLink, client.getBaseUrl()); + Assertions.assertEquals(backToAppLink, client.getBaseUrl()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedRegistrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedRegistrationTest.java index 9740f3732c57..b2ef7af8602c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedRegistrationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedRegistrationTest.java @@ -4,7 +4,6 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.pages.AppPage; import org.keycloak.testsuite.pages.RegisterPage; @@ -12,6 +11,7 @@ import org.jboss.arquillian.graphene.page.Page; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; public class AppInitiatedRegistrationTest extends AbstractTestRealmKeycloakTest { @@ -44,6 +44,6 @@ public void ensureLocaleParameterIsPropagatedDuringAppInitiatedRegistration() { UserRepresentation user = testRealm().users().searchByEmail("test-user@localhost", true).get(0); // ensure that the locale was set on the user - Assert.assertEquals("en", user.getAttributes().get("locale").get(0)); + Assertions.assertEquals("en", user.getAttributes().get("locale").get(0)); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/DeleteAccountActionTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/DeleteAccountActionTest.java index b489387d26b7..ad8e9b8b2d76 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/DeleteAccountActionTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/DeleteAccountActionTest.java @@ -23,10 +23,10 @@ import org.keycloak.testsuite.util.UserBuilder; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.Cookie; public class DeleteAccountActionTest extends AbstractTestRealmKeycloakTest { @@ -65,7 +65,7 @@ public void deleteAccountActionSucceeds() { loginPage.login("test-user@localhost", "password"); - Assert.assertTrue(deleteAccountPage.isCurrent()); + Assertions.assertTrue(deleteAccountPage.isCurrent()); deleteAccountPage.clickConfirmAction(); @@ -73,7 +73,7 @@ public void deleteAccountActionSucceeds() { List users = testRealm().users().search("test-user@localhost"); - Assert.assertEquals(users.size(), 0); + Assertions.assertEquals(users.size(), 0); } @Test @@ -91,7 +91,7 @@ public void testReauthenticateAfterDeletingAccount() { loginPage.login(userRep.getUsername(), "password"); - Assert.assertTrue(deleteAccountPage.isCurrent()); + Assertions.assertTrue(deleteAccountPage.isCurrent()); Cookie authSessionCookie = driver.manage().getCookieNamed(CookieType.AUTH_SESSION_ID.getName()); deleteAccountPage.clickConfirmAction(); @@ -100,18 +100,18 @@ public void testReauthenticateAfterDeletingAccount() { List users = testRealm().users().search(userRep.getUsername()); - Assert.assertEquals(users.size(), 0); + Assertions.assertEquals(users.size(), 0); testRealm().users().create(userRep).close(); addDeleteAccountRoleToUserClientRoles(userRep.getUsername()); oauth.openLoginForm(); Cookie newAuthSessionCookie = driver.manage().getCookieNamed(CookieType.AUTH_SESSION_ID.getName()); - Assert.assertFalse(authSessionCookie.getValue().equals(newAuthSessionCookie.getValue())); + Assertions.assertFalse(authSessionCookie.getValue().equals(newAuthSessionCookie.getValue())); loginPage.login(userRep.getUsername(), "password"); - Assert.assertTrue(deleteAccountPage.isCurrent()); + Assertions.assertTrue(deleteAccountPage.isCurrent()); deleteAccountPage.clickConfirmAction(); users = testRealm().users().search(userRep.getUsername()); - Assert.assertEquals(users.size(), 0); + Assertions.assertEquals(users.size(), 0); } @Test @@ -121,9 +121,9 @@ public void deleteAccountFailsWithoutRoleFails() { loginPage.login("test-user@localhost", "password"); - Assert.assertTrue(errorPage.isCurrent()); + Assertions.assertTrue(errorPage.isCurrent()); - Assert.assertEquals(errorPage.getError(), "You do not have enough permissions to delete your own account, contact admin."); + Assertions.assertEquals(errorPage.getError(), "You do not have enough permissions to delete your own account, contact admin."); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionEmailVerificationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionEmailVerificationTest.java index 71c495faa7ce..127e78df7e3c 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionEmailVerificationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionEmailVerificationTest.java @@ -72,11 +72,11 @@ import org.hamcrest.Matchers; import org.jboss.arquillian.drone.api.annotation.Drone; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; @@ -86,9 +86,9 @@ import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stian Thorgersen @@ -186,15 +186,15 @@ public void verifyEmailConfig() throws MessagingException { verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); // see testsuite/integration-arquillian/tests/base/src/test/resources/testrealm.json - Assert.assertEquals("", message.getHeader("Return-Path")[0]); + Assertions.assertEquals("", message.getHeader("Return-Path")[0]); // displayname - Assert.assertEquals("Keycloak SSO ", message.getHeader("From")[0]); - Assert.assertEquals("Keycloak no-reply ", message.getHeader("Reply-To")[0]); + Assertions.assertEquals("Keycloak SSO ", message.getHeader("From")[0]); + Assertions.assertEquals("Keycloak no-reply ", message.getHeader("Reply-To")[0]); } @Test @@ -204,7 +204,7 @@ public void verifyEmailExisting() throws IOException { verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; @@ -224,7 +224,7 @@ public void verifyEmailExisting() throws IOException { .assertEvent(); appPage.assertCurrent(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().user(testUserId).session(mailCodeId).detail(Details.USERNAME, "test-user@localhost").assertEvent(); } @@ -239,7 +239,7 @@ public void verifyEmailRegister() throws IOException { verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; @@ -259,7 +259,7 @@ public void verifyEmailRegister() throws IOException { updatePasswordOnChangePasswordPage(updatePasswordPage, userId); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().user(userId).session(mailCodeId).detail(Details.USERNAME, "verifyemail").assertEvent(); } @@ -288,7 +288,7 @@ public void verifyEmailRegisterWithSecondBrowser() throws IOException { String userId = events.expectRegister("verifyemail-br2", "email-br2@mail.com").assertEvent().getUserId(); verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; events.expectRequiredAction(EventType.SEND_VERIFY_EMAIL).user(userId).detail(Details.USERNAME, "verifyemail-br2").detail("email", "email-br2@mail.com").assertEvent(); @@ -309,15 +309,15 @@ public void verifyEmailRegisterWithSecondBrowser() throws IOException { updatePasswordOnChangePasswordPage(updatePasswordPageSecondBrowser, userId); infoPageSecondBrowser.setDriver(driver2); infoPageSecondBrowser.assertCurrent(); - Assert.assertEquals("Your account has been updated.", infoPageSecondBrowser.getInfo()); + Assertions.assertEquals("Your account has been updated.", infoPageSecondBrowser.getInfo()); // Refresh in the original browser. Authentication session is expired and user needs to login from the beginning infoPage.setDriver(driver); driver.navigate().refresh(); loginPage.assertCurrent(); - Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); + Assertions.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); loginPage.login("verifyemail-br2", "password"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); } @Test @@ -331,7 +331,7 @@ public void verifyEmailRegisterSetLocale() throws IOException { loginPage.openLanguage("Português"); registerPage.registerWithoutPassword("firstName", "lastName", "locale@mail.com", "locale"); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String verificationUrl = getEmailLink(message); @@ -347,7 +347,7 @@ public void verifyEmailFromAnotherAccountWhenUserIsAuthenticated() throws Except String username1 = KeycloakModelUtils.generateId(); registerPage.registerWithoutPassword("firstName", "lastName", username1 + "@mail.com", username1); verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String verificationLink1 = getEmailLink(message); @@ -356,13 +356,13 @@ public void verifyEmailFromAnotherAccountWhenUserIsAuthenticated() throws Except String username2 = KeycloakModelUtils.generateId(); registerPage.registerWithoutPassword("firstName", "lastName", username2 + "@mail.com", username2); verifyEmailPage.assertCurrent(); - Assert.assertEquals(2, greenMail.getReceivedMessages().length); + Assertions.assertEquals(2, greenMail.getReceivedMessages().length); message = greenMail.getReceivedMessages()[1]; String verificationLink2 = getEmailLink(message); driver.navigate().to(verificationLink2.trim()); updatePasswordPage.assertCurrent(); updatePasswordPage.changePassword("password", "password"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); driver.navigate().to(verificationLink1.trim()); assertTrue(errorPage.getError().contains("You are already authenticated as different user")); UserRepresentation user1 = testRealm().users().search(username1).get(0); @@ -378,7 +378,7 @@ public void verifyEmailFromAnotherAccountAfterEmalIsVerified() throws Exception String username1 = KeycloakModelUtils.generateId(); registerPage.registerWithoutPassword("firstName", "lastName", username1 + "@mail.com", username1); verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String verificationLink1 = getEmailLink(message); @@ -387,7 +387,7 @@ public void verifyEmailFromAnotherAccountAfterEmalIsVerified() throws Exception String username2 = KeycloakModelUtils.generateId(); registerPage.registerWithoutPassword("firstName", "lastName", username2 + "@mail.com", username2); verifyEmailPage.assertCurrent(); - Assert.assertEquals(2, greenMail.getReceivedMessages().length); + Assertions.assertEquals(2, greenMail.getReceivedMessages().length); message = greenMail.getReceivedMessages()[1]; String verificationLink2 = getEmailLink(message); @@ -406,7 +406,7 @@ public void verifyEmailResend() throws IOException { verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); EventRepresentation sendEvent = events.expectRequiredAction(EventType.SEND_VERIFY_EMAIL) .detail("email", "test-user@localhost") @@ -422,7 +422,7 @@ public void verifyEmailResend() throws IOException { .detail("email", "test-user@localhost") .assertEvent(); - Assert.assertEquals(2, greenMail.getReceivedMessages().length); + Assertions.assertEquals(2, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); String verificationUrl = getEmailLink(message); @@ -430,7 +430,7 @@ public void verifyEmailResend() throws IOException { driver.navigate().to(verificationUrl.trim()); appPage.assertCurrent(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectRequiredAction(EventType.VERIFY_EMAIL) .user(testUserId) @@ -448,16 +448,16 @@ public void verifyEmailResendTooFast() { loginPage.login("test-user@localhost", "password"); verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); verifyEmailPage.clickResendEmail(); assertThat(verifyEmailPage.getFeedbackText(), Matchers.containsString("You must wait")); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); try { setTimeOffset(40); verifyEmailPage.clickResendEmail(); - Assert.assertEquals(2, greenMail.getReceivedMessages().length); + Assertions.assertEquals(2, greenMail.getReceivedMessages().length); } finally { setTimeOffset(0); } @@ -472,7 +472,7 @@ public void verifyEmailResendWithRefreshes() throws IOException { verifyEmailPage.assertCurrent(); driver.navigate().refresh(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); EventRepresentation sendEvent = events.expectRequiredAction(EventType.SEND_VERIFY_EMAIL) .detail("email", "test-user@localhost") @@ -489,7 +489,7 @@ public void verifyEmailResendWithRefreshes() throws IOException { .detail("email", "test-user@localhost") .assertEvent(); - Assert.assertEquals(2, greenMail.getReceivedMessages().length); + Assertions.assertEquals(2, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); String verificationUrl = getEmailLink(message); @@ -497,7 +497,7 @@ public void verifyEmailResendWithRefreshes() throws IOException { driver.navigate().to(verificationUrl.trim()); appPage.assertCurrent(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectRequiredAction(EventType.VERIFY_EMAIL) .user(testUserId) @@ -519,7 +519,7 @@ public void verifyEmailResendFirstStillValidEvenWithSecond() throws IOException verifyEmailPage.clickResendEmail(); verifyEmailPage.assertCurrent(); - Assert.assertEquals(2, greenMail.getReceivedMessages().length); + Assertions.assertEquals(2, greenMail.getReceivedMessages().length); MimeMessage message1 = greenMail.getReceivedMessages()[0]; @@ -528,7 +528,7 @@ public void verifyEmailResendFirstStillValidEvenWithSecond() throws IOException driver.navigate().to(verificationUrl1.trim()); appPage.assertCurrent(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); MimeMessage message2 = greenMail.getReceivedMessages()[1]; @@ -541,7 +541,7 @@ public void verifyEmailResendFirstStillValidEvenWithSecond() throws IOException .detail(Details.REDIRECT_URI, Matchers.any(String.class)) .assertEvent(); infoPage.assertCurrent(); - Assert.assertEquals("Your email address has been verified already.", infoPage.getInfo()); + Assertions.assertEquals("Your email address has been verified already.", infoPage.getInfo()); } @Test @@ -554,7 +554,7 @@ public void verifyEmailResendFirstAndSecondStillValid() throws IOException { verifyEmailPage.clickResendEmail(); verifyEmailPage.assertCurrent(); - Assert.assertEquals(2, greenMail.getReceivedMessages().length); + Assertions.assertEquals(2, greenMail.getReceivedMessages().length); MimeMessage message1 = greenMail.getReceivedMessages()[0]; @@ -581,7 +581,7 @@ public void verifyEmailResendAndVerifyWithLatestLink() throws IOException { clearCooldownForUser(); verifyEmailPage.clickResendEmail(); verifyEmailPage.assertCurrent(); - Assert.assertEquals(2, greenMail.getReceivedMessages().length); + Assertions.assertEquals(2, greenMail.getReceivedMessages().length); MimeMessage message1 = greenMail.getReceivedMessages()[0]; String verificationUrl1 = getEmailLink(message1); @@ -601,7 +601,7 @@ public void verifyEmailNewBrowserSession() throws IOException { verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); @@ -640,7 +640,7 @@ public void verifyEmailInvalidKeyInVerficationLink() throws IOException { verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); @@ -671,7 +671,7 @@ public void verifyEmailExpiredCode() throws IOException { verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); @@ -713,7 +713,7 @@ public void verifyEmailExpiredCodedPerActionLifespan() throws IOException { verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); @@ -758,7 +758,7 @@ public void verifyEmailExpiredCodedPerActionMultipleTimeouts() throws IOExceptio verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); @@ -796,7 +796,7 @@ public void verifyEmailExpiredCodeAndExpiredSession() throws IOException { verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); @@ -840,7 +840,7 @@ public void verifyEmailNewBrowserSessionWithClientRedirect() throws IOException .update()) { testRealm().users().get(testUserId).executeActionsEmail(List.of(RequiredAction.VERIFY_EMAIL.name())); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); String verificationUrl = getEmailLink(message); @@ -868,7 +868,7 @@ public void verifyEmailNewBrowserSessionPreserveClient() throws IOException { verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); @@ -907,7 +907,7 @@ public void verifyEmailDuringAuthFlow() throws IOException { verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); String verificationUrl = getEmailLink(message); @@ -926,7 +926,7 @@ public void verifyEmailDuringAuthFlowFirstClickLink() throws IOException { .update()) { testRealm().users().get(testUserId).executeActionsEmail(List.of(RequiredAction.VERIFY_EMAIL.name())); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); String verificationUrl = getEmailLink(message); @@ -951,7 +951,7 @@ public void verifyEmailClickLinkRequiredActionsCleared() throws IOException { .update()) { testRealm().users().get(testUserId).executeActionsEmail(List.of(RequiredAction.VERIFY_EMAIL.name())); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); String verificationUrl = getEmailLink(message); @@ -1027,7 +1027,7 @@ public void verifyEmailDuringAuthFlowAfterRefresh() throws IOException { verifyEmailPage.assertCurrent(); // Browser 2 [still logged in]: Click the email verification link - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); String verificationUrl = getEmailLink(message); @@ -1066,7 +1066,7 @@ public void verifyEmailWhileLoggedIn() throws IOException { oauth.openLoginForm(); verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); String verificationUrl = getEmailLink(message); @@ -1107,7 +1107,7 @@ public void verifyEmailViaAuthSessionWhileLoggedIn() throws IOException { verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); String verificationUrl = getEmailLink(message); @@ -1139,7 +1139,7 @@ public void verifyEmailInNewBrowserWhileLoggedInFirstBrowser() throws IOExceptio oauth.openLoginForm(); verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); String verificationUrl = getEmailLink(message); @@ -1183,7 +1183,7 @@ public void verifyEmailExpiredRegistration() throws IOException { verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); @@ -1229,7 +1229,7 @@ public void actionTokenWithInvalidRequiredActions() throws IOException { // Send email with required action testRealm().users().get(testUserId).executeActionsEmail(List.of(RequiredAction.UPDATE_EMAIL.name())); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getLastReceivedMessage(); MailUtils.EmailBody body = MailUtils.getBody(message); @@ -1276,7 +1276,7 @@ public void testVerifyEmailWithNoEmailAndVerifyProfile() throws Exception { .assertEvent(); // verify email is presented now - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); final MimeMessage message = greenMail.getLastReceivedMessage(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionMultipleActionsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionMultipleActionsTest.java index 4e1ae3b8f148..8558ef513d09 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionMultipleActionsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionMultipleActionsTest.java @@ -31,9 +31,9 @@ import org.keycloak.testsuite.pages.LoginUpdateProfileEditUsernameAllowedPage; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @author Stian Thorgersen @@ -78,10 +78,10 @@ public void updateProfileAndPassword() throws Exception { changePasswordPage.assertCurrent(); updatePassword(codeId); } else { - Assert.fail("Expected to update password and profile before login"); + Assertions.fail("Expected to update password and profile before login"); } - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().session(codeId).assertEvent(); } @@ -101,7 +101,7 @@ public String updatePassword(String codeId) { } EventRepresentation eventRep2 = expectedEvent2.assertEvent(); - Assert.assertEquals(eventRep1.getDetails().get(Details.CODE_ID), eventRep2.getDetails().get(Details.CODE_ID)); + Assertions.assertEquals(eventRep1.getDetails().get(Details.CODE_ID), eventRep2.getDetails().get(Details.CODE_ID)); return eventRep2.getDetails().get(Details.CODE_ID); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionPriorityTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionPriorityTest.java index cd024a0f12dd..406b1d00aebb 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionPriorityTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionPriorityTest.java @@ -52,8 +52,8 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Hiroyuki Wada diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionResetPasswordTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionResetPasswordTest.java index d0dd2419c104..187fde9a13e3 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionResetPasswordTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionResetPasswordTest.java @@ -54,14 +54,14 @@ import org.jboss.arquillian.drone.api.annotation.Drone; import org.jboss.arquillian.graphene.page.Page; import org.junit.After; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebDriver; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stian Thorgersen @@ -114,7 +114,7 @@ public void tempPassword() throws Exception { events.expectRequiredAction(EventType.UPDATE_PASSWORD).detail(Details.CREDENTIAL_TYPE, PasswordCredentialModel.TYPE).assertEvent(); events.expectRequiredAction(EventType.UPDATE_CREDENTIAL).detail(Details.CREDENTIAL_TYPE, PasswordCredentialModel.TYPE).assertEvent(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); EventRepresentation loginEvent = events.expectLogin().assertEvent(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionTotpSetupTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionTotpSetupTest.java index 51db43b56581..9ff257b45df6 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionTotpSetupTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionTotpSetupTest.java @@ -66,16 +66,16 @@ import org.hamcrest.Matchers; import org.jboss.arquillian.drone.api.annotation.Drone; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stian Thorgersen @@ -353,8 +353,8 @@ public void setupTotpRegisterVerifyCustomOtpLabelSetProperly() { totpPage.configure(totp.generateTOTP(totpPage.getTotpSecret()), customOtpLabel); // Check if OTP credential is present - Assert.assertTrue(AccountHelper.isTotpPresent(testRealm(), "setupTotpRegister")); - Assert.assertTrue(AccountHelper.totpUserLabelComparator(testRealm(), "setupTotpRegister", customOtpLabel)); + Assertions.assertTrue(AccountHelper.isTotpPresent(testRealm(), "setupTotpRegister")); + Assertions.assertTrue(AccountHelper.totpUserLabelComparator(testRealm(), "setupTotpRegister", customOtpLabel)); } @Test @@ -521,7 +521,7 @@ public void setupTotpRegisteredAfterTotpRemoval() { String uri = driver.getCurrentUrl(); String src = driver.getPageSource(); assertTrue(loginPage.isCurrent()); - Assert.assertFalse(totpPage.isCurrent()); + Assertions.assertFalse(totpPage.isCurrent()); // Login with one-time password loginTotpPage.login(totp.generateTOTP(totpCode)); @@ -529,7 +529,7 @@ public void setupTotpRegisteredAfterTotpRemoval() { loginEvent = events.expectLogin().user(userId).detail(Details.USERNAME, "setupTotp2").assertEvent(); // Remove google authenticator - Assert.assertTrue(AccountHelper.deleteTotpAuthentication(testRealm(), "setupTotp2")); + Assertions.assertTrue(AccountHelper.deleteTotpAuthentication(testRealm(), "setupTotp2")); AccountHelper.logout(testRealm(), "setupTotp2"); setOtpTimeOffset(TimeBasedOTP.DEFAULT_INTERVAL_SECONDS, totp); @@ -741,7 +741,7 @@ private void testTotpLogoutOtherSessions(boolean logoutOtherSessions) { if (logoutOtherSessions) { totpPage.checkLogoutSessions(); } - Assert.assertEquals(logoutOtherSessions, totpPage.isLogoutSessionsChecked()); + Assertions.assertEquals(logoutOtherSessions, totpPage.isLogoutSessionsChecked()); totpPage.configure(totp.generateTOTP(totpPage.getTotpSecret())); assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateEmailTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateEmailTest.java index e810f874b057..567dfd7d24cf 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateEmailTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateEmailTest.java @@ -42,16 +42,16 @@ import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.userprofile.UserProfileConstants.ROLE_ADMIN; import static org.keycloak.userprofile.UserProfileConstants.ROLE_USER; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public class RequiredActionUpdateEmailTest extends AbstractRequiredActionUpdateEmailTest { @@ -64,7 +64,7 @@ protected void changeEmailUsingRequiredAction(String newEmail, boolean logoutOth if (logoutOtherSessions) { updateEmailPage.checkLogoutSessions(); } - Assert.assertEquals(logoutOtherSessions, updateEmailPage.isLogoutSessionsChecked()); + Assertions.assertEquals(logoutOtherSessions, updateEmailPage.isLogoutSessionsChecked()); updateEmailPage.changeEmail(newEmail); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateEmailTestWithVerificationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateEmailTestWithVerificationTest.java index 7c360909cea4..b3da3b79a256 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateEmailTestWithVerificationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateEmailTestWithVerificationTest.java @@ -55,9 +55,9 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.util.ServerURLs.getAuthServerContextRoot; import static org.keycloak.testsuite.util.oauth.OAuthClient.updateAppRootRealm; @@ -65,13 +65,13 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class RequiredActionUpdateEmailTestWithVerificationTest extends AbstractRequiredActionUpdateEmailTest { @@ -119,7 +119,7 @@ protected void changeEmailUsingRequiredAction(String newEmail, boolean logoutOth updateEmailPage.checkLogoutSessions(); } - Assert.assertEquals(logoutOtherSessions, updateEmailPage.isLogoutSessionsChecked()); + Assertions.assertEquals(logoutOtherSessions, updateEmailPage.isLogoutSessionsChecked()); updateEmailPage.changeEmail(newEmail); events.expect(EventType.SEND_VERIFY_EMAIL).detail(Details.EMAIL, newEmail).assertEvent(); @@ -511,10 +511,10 @@ public void testEmailVerificationPendingMessageOnReAuthentication() throws Messa // Verification email should be sent and email should be set UserRepresentation updatedUser = testRealm().users().get(findUser("pendinguser").getId()).toRepresentation(); - assertNull("Email should be not set immediately", updatedUser.getEmail()); + assertNull(updatedUser.getEmail(), "Email should be not set immediately"); - assertTrue("User should have UPDATE_EMAIL required action", - updatedUser.getRequiredActions().contains(UserModel.RequiredAction.UPDATE_EMAIL.name())); + assertTrue(updatedUser.getRequiredActions().contains(UserModel.RequiredAction.UPDATE_EMAIL.name()), + "User should have UPDATE_EMAIL required action"); infoPage.assertCurrent(); @@ -533,14 +533,13 @@ public void testEmailVerificationPendingMessageOnReAuthentication() throws Messa updateEmailPage.getInfo(), containsString("A verification email was sent to pending@localhost")); // Check that the email field is pre-filled with the pending email, not the old email - assertEquals("Email field should be pre-filled with pending email", - "pending@localhost", updateEmailPage.getEmail()); + assertEquals("pending@localhost", updateEmailPage.getEmail(), "Email field should be pre-filled with pending email"); updateEmailPage.changeEmail("pending@localhost"); // Same email to resend // Should send verification email String confirmationLink = fetchEmailConfirmationLink("pending@localhost", greenMail.getLastReceivedMessage()); - assertNotNull("Should have received verification email", confirmationLink); + assertNotNull(confirmationLink, "Should have received verification email"); } finally { // Always restore original configuration and clean up @@ -579,7 +578,7 @@ public void testPendingVerificationMessageWithRealmVerificationEnabled() throws // Should send verification email and show confirmation events.expect(EventType.SEND_VERIFY_EMAIL).detail(Details.EMAIL, "realmverify@localhost").user(findUser("realmverifyuser").getId()).assertEvent(); String confirmationLink = fetchEmailConfirmationLink("realmverify@localhost"); - assertNotNull("Should have received verification email", confirmationLink); + assertNotNull(confirmationLink, "Should have received verification email"); // Step 2: Logout and login again (should show pending verification message) testRealm().users().get(findUser("realmverifyuser").getId()).logout(); @@ -652,11 +651,11 @@ public void testEmailVerificationCancelledByAdmin() throws Exception { // Verify EMAIL_PENDING attribute is set UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost"); Map> attributes = user.getAttributes(); - assertEquals("EMAIL_PENDING should contain new email", "new@localhost", attributes.get(UserModel.EMAIL_PENDING).get(0)); - assertTrue("User should have UPDATE_EMAIL required action", user.getRequiredActions().contains(UserModel.RequiredAction.UPDATE_EMAIL.name())); + assertEquals("new@localhost", attributes.get(UserModel.EMAIL_PENDING).get(0), "EMAIL_PENDING should contain new email"); + assertTrue(user.getRequiredActions().contains(UserModel.RequiredAction.UPDATE_EMAIL.name()), "User should have UPDATE_EMAIL required action"); String confirmationLink = fetchEmailConfirmationLink("new@localhost"); - assertNotNull("Should have received verification email", confirmationLink); + assertNotNull(confirmationLink, "Should have received verification email"); // Admin sets EMAIL_PENDING to empty string (simulating admin UI removal) user.singleAttribute(UserModel.EMAIL_PENDING, ""); @@ -693,11 +692,10 @@ public void testUpdateEmailVerificationResendTooFast() throws Exception { updateEmailPage.changeEmail("newemail@localhost"); assertThat("Should show cooldown error message", driver.getPageSource(), containsString("You must wait")); - assertEquals("Email should not be sent again due to cooldown", 1, greenMail.getReceivedMessages().length); + assertEquals(1, greenMail.getReceivedMessages().length, "Email should not be sent again due to cooldown"); // Check that email field is pre-filled with the pending email after cooldown error - assertEquals("Email field should be pre-filled with pending email during cooldown", - "newemail@localhost", updateEmailPage.getEmail()); + assertEquals("newemail@localhost", updateEmailPage.getEmail(), "Email field should be pre-filled with pending email during cooldown"); try { // Move time forward beyond cooldown period (default 30 seconds) @@ -711,7 +709,7 @@ public void testUpdateEmailVerificationResendTooFast() throws Exception { // Now resend should work updateEmailPage.changeEmail("newemail@localhost"); - assertEquals("Second email should be sent after cooldown expires", 2, greenMail.getReceivedMessages().length); + assertEquals(2, greenMail.getReceivedMessages().length, "Second email should be sent after cooldown expires"); } finally { setTimeOffset(0); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateProfileTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateProfileTest.java index 3520d9bf4354..483b2528cc86 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateProfileTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateProfileTest.java @@ -50,10 +50,10 @@ import org.hamcrest.Matchers; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.ElementClickInterceptedException; import org.openqa.selenium.htmlunit.HtmlUnitDriver; @@ -63,7 +63,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author Stian Thorgersen @@ -132,18 +132,18 @@ public void updateProfile() { .detail(Details.PREVIOUS_LAST_NAME, "Brady").detail(Details.UPDATED_LAST_NAME, "New last") .detail(Details.PREVIOUS_EMAIL, "test-user@localhost").detail(Details.UPDATED_EMAIL, "new@email.com") .assertEvent(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().assertEvent(); // assert user is really updated in persistent store user = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost"); - Assert.assertEquals("New first", user.getFirstName()); - Assert.assertEquals("New last", user.getLastName()); - Assert.assertEquals("new@email.com", user.getEmail()); - Assert.assertEquals("test-user@localhost", user.getUsername()); + Assertions.assertEquals("New first", user.getFirstName()); + Assertions.assertEquals("New last", user.getLastName()); + Assertions.assertEquals("new@email.com", user.getEmail()); + Assertions.assertEquals("test-user@localhost", user.getUsername()); // email changed so verify that emailVerified flag is reset - Assert.assertEquals(false, user.isEmailVerified()); + Assertions.assertEquals(false, user.isEmailVerified()); } @Test @@ -163,18 +163,18 @@ public void updateUsername() { .detail(Details.USERNAME, "john-doh@localhost") .assertEvent(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().detail(Details.USERNAME, "john-doh@localhost").user(userId).assertEvent(); // assert user is really updated in persistent store UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "new"); - Assert.assertEquals("New first", user.getFirstName()); - Assert.assertEquals("New last", user.getLastName()); - Assert.assertEquals("john-doh@localhost", user.getEmail()); - Assert.assertEquals("new", user.getUsername()); + Assertions.assertEquals("New first", user.getFirstName()); + Assertions.assertEquals("New last", user.getLastName()); + Assertions.assertEquals("john-doh@localhost", user.getEmail()); + Assertions.assertEquals("new", user.getUsername()); // email not changed so verify that emailVerified flag is NOT reset - Assert.assertEquals(true, user.isEmailVerified()); + Assertions.assertEquals(true, user.isEmailVerified()); getCleanup().addUserId(user.getId()); } @@ -191,10 +191,10 @@ public void updateProfileMissingFirstName() { updateProfilePage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("", updateProfilePage.getFirstName()); - Assert.assertEquals("New last", updateProfilePage.getLastName()); - Assert.assertEquals("new@email.com", updateProfilePage.getEmail()); - Assert.assertEquals("Please specify this field.", updateProfilePage.getInputErrors().getFirstNameError()); + Assertions.assertEquals("", updateProfilePage.getFirstName()); + Assertions.assertEquals("New last", updateProfilePage.getLastName()); + Assertions.assertEquals("new@email.com", updateProfilePage.getEmail()); + Assertions.assertEquals("Please specify this field.", updateProfilePage.getInputErrors().getFirstNameError()); events.assertEmpty(); } @@ -212,11 +212,11 @@ public void updateProfileMissingLastName() { updateProfilePage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("New first", updateProfilePage.getFirstName()); - Assert.assertEquals("", updateProfilePage.getLastName()); - Assert.assertEquals("new@email.com", updateProfilePage.getEmail()); + Assertions.assertEquals("New first", updateProfilePage.getFirstName()); + Assertions.assertEquals("", updateProfilePage.getLastName()); + Assertions.assertEquals("new@email.com", updateProfilePage.getEmail()); - Assert.assertEquals("Please specify this field.", updateProfilePage.getInputErrors().getLastNameError()); + Assertions.assertEquals("Please specify this field.", updateProfilePage.getInputErrors().getLastNameError()); events.assertEmpty(); } @@ -235,9 +235,9 @@ public void updateProfileMissingEmail() { updateProfilePage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("New first", updateProfilePage.getFirstName()); - Assert.assertEquals("New last", updateProfilePage.getLastName()); - Assert.assertEquals("", updateProfilePage.getEmail()); + Assertions.assertEquals("New first", updateProfilePage.getFirstName()); + Assertions.assertEquals("New last", updateProfilePage.getLastName()); + Assertions.assertEquals("", updateProfilePage.getEmail()); assertThat(updateProfilePage.getInputErrors().getEmailError(), anyOf( containsString("Please specify email"), @@ -261,11 +261,11 @@ public void updateProfileInvalidEmail() { updateProfilePage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("New first", updateProfilePage.getFirstName()); - Assert.assertEquals("New last", updateProfilePage.getLastName()); - Assert.assertEquals("invalidemail", updateProfilePage.getEmail()); + Assertions.assertEquals("New first", updateProfilePage.getFirstName()); + Assertions.assertEquals("New last", updateProfilePage.getLastName()); + Assertions.assertEquals("invalidemail", updateProfilePage.getEmail()); - Assert.assertEquals("Invalid email address.", updateProfilePage.getInputErrors().getEmailError()); + Assertions.assertEquals("Invalid email address.", updateProfilePage.getInputErrors().getEmailError()); events.assertEmpty(); } @@ -283,12 +283,12 @@ public void updateProfileMissingUsername() { updateProfilePage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("New first", updateProfilePage.getFirstName()); - Assert.assertEquals("New last", updateProfilePage.getLastName()); - Assert.assertEquals("new@email.com", updateProfilePage.getEmail()); - Assert.assertEquals("", updateProfilePage.getUsername()); + Assertions.assertEquals("New first", updateProfilePage.getFirstName()); + Assertions.assertEquals("New last", updateProfilePage.getLastName()); + Assertions.assertEquals("new@email.com", updateProfilePage.getEmail()); + Assertions.assertEquals("", updateProfilePage.getUsername()); - Assert.assertEquals("Please specify username.", updateProfilePage.getInputErrors().getUsernameError()); + Assertions.assertEquals("Please specify username.", updateProfilePage.getInputErrors().getUsernameError()); events.assertEmpty(); } @@ -306,12 +306,12 @@ public void updateProfileDuplicateUsername() { updateProfilePage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("New first", updateProfilePage.getFirstName()); - Assert.assertEquals("New last", updateProfilePage.getLastName()); - Assert.assertEquals("new@email.com", updateProfilePage.getEmail()); - Assert.assertEquals("test-user@localhost", updateProfilePage.getUsername()); + Assertions.assertEquals("New first", updateProfilePage.getFirstName()); + Assertions.assertEquals("New last", updateProfilePage.getLastName()); + Assertions.assertEquals("new@email.com", updateProfilePage.getEmail()); + Assertions.assertEquals("test-user@localhost", updateProfilePage.getUsername()); - Assert.assertEquals("Username already exists.", updateProfilePage.getInputErrors().getUsernameError()); + Assertions.assertEquals("Username already exists.", updateProfilePage.getInputErrors().getUsernameError()); events.assertEmpty(); } @@ -330,11 +330,11 @@ public void updateProfileDuplicatedEmail() { updateProfilePage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("New first", updateProfilePage.getFirstName()); - Assert.assertEquals("New last", updateProfilePage.getLastName()); - Assert.assertEquals("keycloak-user@localhost", updateProfilePage.getEmail()); + Assertions.assertEquals("New first", updateProfilePage.getFirstName()); + Assertions.assertEquals("New last", updateProfilePage.getLastName()); + Assertions.assertEquals("keycloak-user@localhost", updateProfilePage.getEmail()); - Assert.assertEquals("Email already exists.", updateProfilePage.getInputErrors().getEmailError()); + Assertions.assertEquals("Email already exists.", updateProfilePage.getInputErrors().getEmailError()); events.assertEmpty(); } @@ -354,12 +354,12 @@ public void updateProfileDuplicateUsernameWithEmail() { updateProfilePage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("New first", updateProfilePage.getFirstName()); - Assert.assertEquals("New last", updateProfilePage.getLastName()); - Assert.assertEquals("new@email.com", updateProfilePage.getEmail()); - Assert.assertEquals("user1@local.org", updateProfilePage.getUsername()); + Assertions.assertEquals("New first", updateProfilePage.getFirstName()); + Assertions.assertEquals("New last", updateProfilePage.getLastName()); + Assertions.assertEquals("new@email.com", updateProfilePage.getEmail()); + Assertions.assertEquals("user1@local.org", updateProfilePage.getUsername()); - Assert.assertEquals("Username already exists.", updateProfilePage.getInputErrors().getUsernameError()); + Assertions.assertEquals("Username already exists.", updateProfilePage.getInputErrors().getUsernameError()); events.assertEmpty(); } @@ -380,11 +380,11 @@ public void updateProfileDuplicatedEmailWithUsername() { updateProfilePage.assertCurrent(); // assert that form holds submitted values during validation error - Assert.assertEquals("New first", updateProfilePage.getFirstName()); - Assert.assertEquals("New last", updateProfilePage.getLastName()); - Assert.assertEquals("user1@local.com", updateProfilePage.getEmail()); + Assertions.assertEquals("New first", updateProfilePage.getFirstName()); + Assertions.assertEquals("New last", updateProfilePage.getLastName()); + Assertions.assertEquals("user1@local.com", updateProfilePage.getEmail()); - Assert.assertEquals("Email already exists.", updateProfilePage.getInputErrors().getEmailError()); + Assertions.assertEquals("Email already exists.", updateProfilePage.getInputErrors().getEmailError()); events.assertEmpty(); } @@ -405,7 +405,7 @@ public void updateProfileExpiredCookies() { String backToAppLink = errorPage.getBackToApplicationLink(); ClientRepresentation client = AdminApiUtil.findClientByClientId(adminClient.realm("test"), "test-app").toRepresentation(); - Assert.assertEquals(backToAppLink, client.getBaseUrl()); + Assertions.assertEquals(backToAppLink, client.getBaseUrl()); } @Test @@ -435,18 +435,18 @@ public void updateProfileWithoutRemoveCustomAttributes() { events.expectRequiredAction(EventType.UPDATE_PROFILE).detail(Details.CONTEXT, UserProfileContext.UPDATE_PROFILE.name()).detail(Details.PREVIOUS_EMAIL, "test-user@localhost").detail(Details.UPDATED_EMAIL, "new@email.com").assertEvent(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().assertEvent(); // assert user is really updated in persistent store userRep = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost"); - Assert.assertEquals("New first", userRep.getFirstName()); - Assert.assertEquals("New last", userRep.getLastName()); - Assert.assertEquals("new@email.com", userRep.getEmail()); - Assert.assertEquals("test-user@localhost", userRep.getUsername()); - Assert.assertNotNull(userRep.getAttributes()); - Assert.assertTrue(userRep.getAttributes().containsKey("custom")); + Assertions.assertEquals("New first", userRep.getFirstName()); + Assertions.assertEquals("New last", userRep.getLastName()); + Assertions.assertEquals("new@email.com", userRep.getEmail()); + Assertions.assertEquals("test-user@localhost", userRep.getUsername()); + Assertions.assertNotNull(userRep.getAttributes()); + Assertions.assertTrue(userRep.getAttributes().containsKey("custom")); } finally { upConfig.setUnmanagedAttributePolicy(null); upResource.update(upConfig); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateProfileWithUserProfileTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateProfileWithUserProfileTest.java index a5fb73f1ab69..45ee445a339f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateProfileWithUserProfileTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateProfileWithUserProfileTest.java @@ -43,10 +43,10 @@ import org.apache.commons.lang3.StringUtils; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; @@ -60,10 +60,10 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test update-profile required action with custom user profile configurations @@ -149,11 +149,11 @@ public void testDisplayName() { //assert field names // i18n replaced - Assert.assertEquals("First name", updateProfilePage.getLabelForField("firstName")); + Assertions.assertEquals("First name", updateProfilePage.getLabelForField("firstName")); // attribute name used if no display name set - Assert.assertEquals("lastName", updateProfilePage.getLabelForField("lastName")); + Assertions.assertEquals("lastName", updateProfilePage.getLabelForField("lastName")); // direct value in display name - Assert.assertEquals("Department", updateProfilePage.getLabelForField("department")); + Assertions.assertEquals("Department", updateProfilePage.getLabelForField("department")); } @@ -281,16 +281,16 @@ public void testOptionalAttribute() { .detail(Details.PREVIOUS_LAST_NAME, "Brady") .detail(Details.PREVIOUS_EMAIL, USERNAME1).detail(Details.UPDATED_EMAIL, "new@email.com") .assertEvent(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().assertEvent(); // assert user is really updated in persistent store UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, USERNAME1); - Assert.assertEquals("New first", user.getFirstName()); + Assertions.assertEquals("New first", user.getFirstName()); assertThat(StringUtils.isEmpty(user.getLastName()), is(true)); - Assert.assertEquals("new@email.com", user.getEmail()); - Assert.assertEquals(USERNAME1, user.getUsername()); + Assertions.assertEquals("new@email.com", user.getEmail()); + Assertions.assertEquals(USERNAME1, user.getUsername()); assertNull(user.getLastName()); } @@ -317,8 +317,8 @@ public void testCustomValidationLastName() { //submit OK updateProfilePage.prepareUpdate().username(USERNAME1).firstName("First").lastName("Last").email(USERNAME1).submit(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUserByUsername(USERNAME1); assertEquals("First", user.getFirstName()); @@ -340,14 +340,14 @@ public void testRequiredReadOnlyAttribute() { loginPage.login(USERNAME1, PASSWORD); updateProfilePage.assertCurrent(); - Assert.assertEquals("Brady", updateProfilePage.getLastName()); - Assert.assertFalse(updateProfilePage.isDepartmentEnabled()); + Assertions.assertEquals("Brady", updateProfilePage.getLastName()); + Assertions.assertFalse(updateProfilePage.isDepartmentEnabled()); //update of the other attributes must be successful in this case updateProfilePage.prepareUpdate().username(USERNAME1).firstName("First").lastName("Last").email(USERNAME1).submit(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUserByUsername(USERNAME1); assertEquals("First", user.getFirstName()); @@ -367,14 +367,14 @@ public void testRequiredReadOnlyExistingAttribute() { loginPage.login(USERNAME1, PASSWORD); updateProfilePage.assertCurrent(); - Assert.assertEquals("last", updateProfilePage.getLastName()); - Assert.assertFalse(updateProfilePage.isDepartmentEnabled()); + Assertions.assertEquals("last", updateProfilePage.getLastName()); + Assertions.assertFalse(updateProfilePage.isDepartmentEnabled()); //update of the other attributes must be successful in this case updateProfilePage.prepareUpdate().username(USERNAME1).firstName("First").lastName("Last").email(USERNAME1).submit(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUserByUsername(USERNAME1); assertEquals("First", user.getFirstName()); @@ -394,14 +394,14 @@ public void testAttributeNotVisible() { loginPage.login(USERNAME1, PASSWORD); updateProfilePage.assertCurrent(); - Assert.assertEquals("Brady", updateProfilePage.getLastName()); - Assert.assertFalse("'department' field is visible", updateProfilePage.isDepartmentPresent()); + Assertions.assertEquals("Brady", updateProfilePage.getLastName()); + Assertions.assertFalse(updateProfilePage.isDepartmentPresent(), "'department' field is visible"); //update of the other attributes must be successful in this case updateProfilePage.prepareUpdate().username(USERNAME1).firstName("First").lastName("Last").email(USERNAME1).submit(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUserByUsername(USERNAME1); assertEquals("First", user.getFirstName()); @@ -438,8 +438,8 @@ public void testRequiredAttribute() { .detail(Details.PREF_UPDATED + "department", "DepartmentCC") .assertEvent(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUserByUsername(USERNAME1); assertEquals("FirstCC", user.getFirstName()); @@ -478,8 +478,8 @@ public void testAttributeRequiredForScope() { .assertEvent(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUserByUsername(USERNAME1); assertEquals("FirstCC", user.getFirstName()); @@ -512,8 +512,8 @@ public void testAttributeRequiredForDefaultScope() { updateProfilePage.prepareUpdate().username(USERNAME1).firstName("FirstCC").lastName("LastCC").email(USERNAME1) .department("DepartmentCC").submit(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUserByUsername(USERNAME1); assertEquals("FirstCC", user.getFirstName()); @@ -546,8 +546,8 @@ public void testAttributeRequiredAndSelectedByScope() { updateProfilePage.prepareUpdate().username(USERNAME1).firstName("FirstCC").lastName("LastCC").email(USERNAME1) .department("DepartmentCC").submit(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUserByUsername(USERNAME1); assertEquals("FirstCC", user.getFirstName()); @@ -571,12 +571,12 @@ public void testAttributeNotRequiredAndSelectedByScopeCanBeUpdated() { updateProfilePage.assertCurrent(); - Assert.assertTrue(updateProfilePage.isDepartmentPresent()); + Assertions.assertTrue(updateProfilePage.isDepartmentPresent()); updateProfilePage.prepareUpdate().username(USERNAME1).firstName("FirstCC").lastName("LastCC").email(USERNAME1) .department("DepartmentCC").submit(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUserByUsername(USERNAME1); assertEquals("FirstCC", user.getFirstName()); @@ -600,11 +600,11 @@ public void testAttributeRequiredButNotSelectedByScopeIsNotRendered() { updateProfilePage.assertCurrent(); - Assert.assertFalse(updateProfilePage.isDepartmentPresent()); + Assertions.assertFalse(updateProfilePage.isDepartmentPresent()); updateProfilePage.prepareUpdate().username(USERNAME1).firstName("FirstCC").lastName("LastCC").email(USERNAME1).submit(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUserByUsername(USERNAME1); assertEquals("FirstCC", user.getFirstName()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/TermsAndConditionsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/TermsAndConditionsTest.java index 1a9617944d5c..599b1f9474dc 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/TermsAndConditionsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/TermsAndConditionsTest.java @@ -43,10 +43,10 @@ import org.hamcrest.Matchers; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; @@ -56,10 +56,10 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Stian Thorgersen @@ -95,28 +95,28 @@ public void termsAccepted() { loginPage.login("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertTrue(termsPage.isCurrent()); + Assertions.assertTrue(termsPage.isCurrent()); termsPage.acceptTerms(); events.expectRequiredAction(EventType.CUSTOM_REQUIRED_ACTION).removeDetail(Details.REDIRECT_URI).detail(Details.CUSTOM_REQUIRED_ACTION, TermsAndConditions.PROVIDER_ID).assertEvent(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); AuthorizationEndpointResponse response = oauth.parseLoginResponse(); - Assert.assertNotNull(response.getCode()); + Assertions.assertNotNull(response.getCode()); events.expectLogin().assertEvent(); // assert user attribute is properly set UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost"); Map> attributes = user.getAttributes(); - assertNotNull("timestamp for terms acceptance was not stored in user attributes", attributes); + assertNotNull(attributes, "timestamp for terms acceptance was not stored in user attributes"); List termsAndConditions = attributes.get(TermsAndConditions.USER_ATTRIBUTE); - assertTrue("timestamp for terms acceptance was not stored in user attributes as " - + TermsAndConditions.USER_ATTRIBUTE, termsAndConditions.size() == 1); + assertTrue(termsAndConditions.size() == 1, "timestamp for terms acceptance was not stored in user attributes as " + + TermsAndConditions.USER_ATTRIBUTE); String timestamp = termsAndConditions.get(0); - assertNotNull("expected non-null timestamp for terms acceptance in user attribute " - + TermsAndConditions.USER_ATTRIBUTE, timestamp); + assertNotNull(timestamp, "expected non-null timestamp for terms acceptance in user attribute " + + TermsAndConditions.USER_ATTRIBUTE); try { Integer.valueOf(timestamp); } catch (NumberFormatException e) { @@ -128,17 +128,17 @@ public void termsAccepted() { public void termsDeclined() throws Exception { oauth.openLoginForm(); loginPage.login("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertTrue(termsPage.isCurrent()); + Assertions.assertTrue(termsPage.isCurrent()); termsPage.declineTerms(); WaitUtils.waitForPageToLoad(); // assert on app page with reject login - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); AuthorizationEndpointResponse response = oauth.parseLoginResponse(); - Assert.assertNull(response.getCode()); - Assert.assertEquals(Errors.ACCESS_DENIED, response.getError()); - Assert.assertEquals(Messages.TERMS_AND_CONDITIONS_DECLINED, response.getErrorDescription()); + Assertions.assertNull(response.getCode()); + Assertions.assertEquals(Errors.ACCESS_DENIED, response.getError()); + Assertions.assertEquals(Messages.TERMS_AND_CONDITIONS_DECLINED, response.getErrorDescription()); // assert event events.expectLogin().event(EventType.CUSTOM_REQUIRED_ACTION_ERROR).detail(Details.CUSTOM_REQUIRED_ACTION, TermsAndConditions.PROVIDER_ID) @@ -151,8 +151,8 @@ public void termsDeclined() throws Exception { UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost"); Map> attributes = user.getAttributes(); if (attributes != null) { - assertNull("expected null for terms acceptance user attribute " + TermsAndConditions.USER_ATTRIBUTE, - attributes.get(TermsAndConditions.USER_ATTRIBUTE)); + assertNull(attributes.get(TermsAndConditions.USER_ATTRIBUTE), + "expected null for terms acceptance user attribute " + TermsAndConditions.USER_ATTRIBUTE); } } @@ -166,7 +166,7 @@ public void termsDeclinedAccount() { loginPage.login("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertTrue(termsPage.isCurrent()); + Assertions.assertTrue(termsPage.isCurrent()); termsPage.declineTerms(); @@ -185,12 +185,12 @@ public void termsDeclinedAccount() { UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost"); Map> attributes = user.getAttributes(); if (attributes != null) { - assertNull("expected null for terms acceptance user attribute " + TermsAndConditions.USER_ATTRIBUTE, - attributes.get(TermsAndConditions.USER_ATTRIBUTE)); + assertNull(attributes.get(TermsAndConditions.USER_ATTRIBUTE), + "expected null for terms acceptance user attribute " + TermsAndConditions.USER_ATTRIBUTE); } assertThat(DroneUtils.getCurrentDriver().getTitle(), equalTo("Account Management")); - Assert.assertTrue(DroneUtils.getCurrentDriver().getPageSource().contains("Access denied")); - Assert.assertFalse(DroneUtils.getCurrentDriver().getPageSource().contains("An unexpected error occurred")); + Assertions.assertTrue(DroneUtils.getCurrentDriver().getPageSource().contains("Access denied")); + Assertions.assertFalse(DroneUtils.getCurrentDriver().getPageSource().contains("An unexpected error occurred")); WebElement tryAgainButton = DroneUtils.getCurrentDriver().findElement(By.tagName("button")); assertThat(tryAgainButton.getText(), equalTo("Try again")); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/AbstractServletsAdapterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/AbstractServletsAdapterTest.java index 8b35fd95fc68..925f0377aa92 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/AbstractServletsAdapterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/AbstractServletsAdapterTest.java @@ -36,7 +36,7 @@ import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.asset.UrlAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.auth.page.AuthRealm.DEMO; import static org.keycloak.testsuite.util.WaitUtils.waitForPageToLoad; @@ -63,10 +63,10 @@ public static WebArchive samlServletDeployment(String name, String customArchive String webInfPath = baseSAMLPath + name + "/WEB-INF/"; URL keycloakSAMLConfig = AbstractServletsAdapterTest.class.getResource(webInfPath + "keycloak-saml.xml"); - Assert.assertNotNull("keycloak-saml.xml should be in " + webInfPath, keycloakSAMLConfig); + Assertions.assertNotNull(keycloakSAMLConfig, "keycloak-saml.xml should be in " + webInfPath); URL webXML = AbstractServletsAdapterTest.class.getResource(baseSAMLPath + webXMLPath); - Assert.assertNotNull("web.xml should be in " + baseSAMLPath + webXMLPath, keycloakSAMLConfig); + Assertions.assertNotNull(keycloakSAMLConfig, "web.xml should be in " + baseSAMLPath + webXMLPath); WebArchive deployment = ShrinkWrap.create(WebArchive.class, customArchiveName + ".war") .addClasses(servletClasses) @@ -116,7 +116,7 @@ public static WebArchive samlServletDeploymentMultiTenant(String name, String we String webInfPath = baseSAMLPath + name + "/WEB-INF/"; URL webXML = AbstractServletsAdapterTest.class.getResource(baseSAMLPath + webXMLPath); - Assert.assertNotNull("web.xml should be in " + baseSAMLPath + webXMLPath, webXML); + Assertions.assertNotNull(webXML, "web.xml should be in " + baseSAMLPath + webXMLPath); WebArchive deployment = ShrinkWrap.create(WebArchive.class, name + ".war") .addClasses(servletClasses) @@ -134,18 +134,18 @@ public static WebArchive samlServletDeploymentMultiTenant(String name, String we // add the xml for each tenant in classes URL config1Url = AbstractServletsAdapterTest.class.getResource(webInfPath + config1); - Assert.assertNotNull("config1Url should be in " + webInfPath + config1, config1Url); + Assertions.assertNotNull(config1Url, "config1Url should be in " + webInfPath + config1); deployment.add(new UrlAsset(config1Url), "/WEB-INF/classes/" + config1); URL config2Url = AbstractServletsAdapterTest.class.getResource(webInfPath + config2); - Assert.assertNotNull("config2Url should be in " + webInfPath + config2, config2Url); + Assertions.assertNotNull(config2Url, "config2Url should be in " + webInfPath + config2); deployment.add(new UrlAsset(config2Url), "/WEB-INF/classes/" + config2); // add the keystores for each tenant in classes URL keystore1Url = AbstractServletsAdapterTest.class.getResource(webInfPath + keystore1); - Assert.assertNotNull("keystore1Url should be in " + webInfPath + keystore1, keystore1Url); + Assertions.assertNotNull(keystore1Url, "keystore1Url should be in " + webInfPath + keystore1); deployment.add(new UrlAsset(keystore1Url), "/WEB-INF/classes/" + keystore1); URL keystore2Url = AbstractServletsAdapterTest.class.getResource(webInfPath + keystore2); - Assert.assertNotNull("keystore2Url should be in " + webInfPath + keystore2, keystore2Url); + Assertions.assertNotNull(keystore2Url, "keystore2Url should be in " + webInfPath + keystore2); deployment.add(new UrlAsset(keystore2Url), "/WEB-INF/classes/" + keystore2); return deployment; diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SAMLLoginResponseHandlingTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SAMLLoginResponseHandlingTest.java index ddfebb692d8e..98abcd0080bc 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SAMLLoginResponseHandlingTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SAMLLoginResponseHandlingTest.java @@ -35,8 +35,8 @@ import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.graphene.page.Page; import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.w3c.dom.Document; @@ -191,7 +191,7 @@ public void testAttributes() throws Exception { driver.navigate().to(employee2ServletPage.getUriBuilder().clone().path("getAssertionFromDocument").build().toURL()); waitForPageToLoad(); - Assert.assertEquals("", getRawPageSource()); + Assertions.assertEquals("", getRawPageSource()); employee2ServletPage.logout(); checkLoggedOut(employee2ServletPage, testRealmSAMLPostLoginPage); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SAMLServletAdapterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SAMLServletAdapterTest.java index a9d6519ffaa7..7e6276327306 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SAMLServletAdapterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SAMLServletAdapterTest.java @@ -201,9 +201,9 @@ import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.Assert; import org.junit.Assume; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.Cookie; import org.openqa.selenium.htmlunit.HtmlUnitDriver; @@ -539,7 +539,7 @@ private void assertForbidden(AbstractPage page, String expectedNotContains) { page.navigateTo(); waitUntilElement(By.xpath("//body")).text().not().contains(expectedNotContains); //Different 403 status page on EAP and Wildfly - Assert.assertTrue(driver.getPageSource().contains("Forbidden") + Assertions.assertTrue(driver.getPageSource().contains("Forbidden") || driver.getPageSource().contains(FORBIDDEN_TEXT) || driver.getPageSource().contains(WEBSPHERE_FORBIDDEN_TEXT)); // WebSphere } @@ -555,7 +555,7 @@ private void assertForbiddenLogin(AbstractPage page, String username, String pas loginPage.form().login(username, password); waitUntilElement(By.xpath("//body")).text().not().contains(expectedNotContains); //Different 403 status page on EAP and Wildfly - Assert.assertTrue(driver.getPageSource().contains("Forbidden") + Assertions.assertTrue(driver.getPageSource().contains("Forbidden") || driver.getPageSource().contains(FORBIDDEN_TEXT) || driver.getPageSource().contains(WEBSPHERE_FORBIDDEN_TEXT)); // WebSphere } @@ -652,7 +652,7 @@ public void badRealmSalesPostSigTest() { waitUntilElement(By.xpath("//body")).text().not().contains("principal="); //Different 403 status page on EAP and Wildfly - Assert.assertTrue(driver.getPageSource().contains("Forbidden") + Assertions.assertTrue(driver.getPageSource().contains("Forbidden") || driver.getPageSource().contains(FORBIDDEN_TEXT) || driver.getPageSource().contains(WEBSPHERE_FORBIDDEN_TEXT)); // WebSphere } @@ -875,7 +875,7 @@ public void salesMetadataTest() { clientRep.setAdminUrl(ServerURLs.getAppServerContextRoot() + "/sales-metadata/saml"); try (Response response = testRealmResource().clients().create(clientRep)) { - Assert.assertEquals(201, response.getStatus()); + Assertions.assertEquals(201, response.getStatus()); } testSuccessfulAndUnauthorizedLogin(salesMetadataServletPage, testRealmSAMLPostLoginPage); @@ -1173,7 +1173,7 @@ public void idpInitiatedUnauthorizedLoginTest() { waitUntilElement(By.xpath("//body")).text().not().contains("bburke"); //Different 403 status page on EAP and Wildfly - Assert.assertTrue(driver.getPageSource().contains("Forbidden") + Assertions.assertTrue(driver.getPageSource().contains("Forbidden") || driver.getPageSource().contains(FORBIDDEN_TEXT) || driver.getPageSource().contains(WEBSPHERE_FORBIDDEN_TEXT)); // WebSphere @@ -1197,7 +1197,7 @@ public void testSavedPostRequest() { // test that user principal and KeycloakSecurityContext available driver.navigate().to(inputPortalPage + "/insecure"); waitUntilElement(By.xpath("//body")).text().contains("Insecure Page"); - Assert.assertNotEquals("SessionID has not been changed at login", sessionId, driver.manage().getCookieNamed("JSESSIONID").getValue()); + Assertions.assertNotEquals(sessionId, driver.manage().getCookieNamed("JSESSIONID").getValue(), "SessionID has not been changed at login"); if (System.getProperty("insecure.user.principal.unsupported") == null) waitUntilElement(By.xpath("//body")).text().contains("UserPrincipal"); @@ -1211,7 +1211,7 @@ public void testSavedPostRequest() { Form form = new Form(); form.param("parameter", "hello"); String text = client.target(inputPortalPage + "/unsecured").request().post(Entity.form(form), String.class); - Assert.assertTrue(text.contains("parameter=hello")); + Assertions.assertTrue(text.contains("parameter=hello")); client.close(); } @@ -1241,7 +1241,7 @@ public void testPostBadAssertionSignature() { testRealmSAMLPostLoginPage.form().login("bburke", "password"); waitUntilElement(By.xpath("//body")).text().contains("Error info: SamlAuthenticationError [reason=INVALID_SIGNATURE"); - Assert.assertEquals(driver.getCurrentUrl(), badAssertionSalesPostSigPage.getUriBuilder().clone().path("saml").build().toASCIIString()); + Assertions.assertEquals(driver.getCurrentUrl(), badAssertionSalesPostSigPage.getUriBuilder().clone().path("saml").build().toASCIIString()); } @Test @@ -1251,7 +1251,7 @@ public void testMissingAssertionSignature() { testRealmSAMLPostLoginPage.form().login("bburke", "password"); waitUntilElement(By.xpath("//body")).text().contains("Error info: SamlAuthenticationError [reason=INVALID_SIGNATURE"); - Assert.assertEquals(driver.getCurrentUrl(), missingAssertionSigPage.getUriBuilder().clone().path("saml").build().toASCIIString()); + Assertions.assertEquals(driver.getCurrentUrl(), missingAssertionSigPage.getUriBuilder().clone().path("saml").build().toASCIIString()); } @Test @@ -1455,10 +1455,10 @@ public void idpMetadataValidation(boolean signature) throws Exception { Document doc = DocumentUtil.getDocument(stringResponse); if (signature) { - Assert.assertNotNull("IdP metadata is not signed", XMLSignatureUtil.getSignature(doc.getDocumentElement())); + Assertions.assertNotNull(XMLSignatureUtil.getSignature(doc.getDocumentElement()), "IdP metadata is not signed"); EntityDescriptorType entityType = (EntityDescriptorType) descriptor; IDPSSODescriptorType idpDescriptor = SAMLMetadataUtil.locateIDPSSODescriptorType(entityType); - Assert.assertNotNull("No IDPSSODescriptorType in the IdP metadata", idpDescriptor); + Assertions.assertNotNull(idpDescriptor, "No IDPSSODescriptorType in the IdP metadata"); List keyDescriptors = idpDescriptor.getKeyDescriptor(); X509Certificate cert = null; if (keyDescriptors != null) { @@ -1467,10 +1467,10 @@ public void idpMetadataValidation(boolean signature) throws Exception { break; } } - Assert.assertNotNull("No signing certificate found in the IdP metadata", cert); + Assertions.assertNotNull(cert, "No signing certificate found in the IdP metadata"); SamlProtocolUtils.verifyDocumentSignature(doc, new HardcodedKeyLocator(cert.getPublicKey())); } else { - Assert.assertNull("IdP metadata is signed", XMLSignatureUtil.getSignature(doc.getDocumentElement())); + Assertions.assertNull(XMLSignatureUtil.getSignature(doc.getDocumentElement()), "IdP metadata is signed"); } } } @@ -1498,13 +1498,13 @@ public void testDOMAssertion() throws Exception { driver.navigate().to(employeeDomServletPage.getUriBuilder().clone().path("getAssertionFromDocument").build().toURL()); waitForPageToLoad(); String xml = getRawPageSource(); - Assert.assertNotEquals("", xml); + Assertions.assertNotEquals("", xml); Document doc = DocumentUtil.getDocument(new StringReader(xml)); String certBase64 = DocumentUtil.getElement(doc, new QName("http://www.w3.org/2000/09/xmldsig#", "X509Certificate")).getTextContent(); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate cert = cf.generateCertificate(new ByteArrayInputStream(Base64.getMimeDecoder().decode(certBase64))); PublicKey pubkey = cert.getPublicKey(); - Assert.assertTrue(AssertionUtil.isSignatureValid(doc.getDocumentElement(), pubkey)); + Assertions.assertTrue(AssertionUtil.isSignatureValid(doc.getDocumentElement(), pubkey)); employeeDomServletPage.logout(); checkLoggedOut(employeeDomServletPage, testRealmSAMLPostLoginPage); @@ -1667,42 +1667,42 @@ public void testAutodetectBearerOnly() { // Do not redirect client to login page if it's an XHR WebTarget target = client.target(salesPostAutodetectServletPage.toString() + "/"); Response response = target.request().header("X-Requested-With", "XMLHttpRequest").get(); - Assert.assertEquals(401, response.getStatus()); + Assertions.assertEquals(401, response.getStatus()); response.close(); // Do not redirect client to login page if it's a partial Faces request response = target.request().header("Faces-Request", "partial/ajax").get(); - Assert.assertEquals(401, response.getStatus()); + Assertions.assertEquals(401, response.getStatus()); response.close(); // Do not redirect client to login page if it's a SOAP request response = target.request().header("SOAPAction", "").get(); - Assert.assertEquals(401, response.getStatus()); + Assertions.assertEquals(401, response.getStatus()); response.close(); // Do not redirect client to login page if Accept header is missing response = target.request().get(); - Assert.assertEquals(401, response.getStatus()); + Assertions.assertEquals(401, response.getStatus()); response.close(); // Do not redirect client to login page if client does not understand HTML reponses response = target.request().header(HttpHeaders.ACCEPT, "application/json,text/xml").get(); - Assert.assertEquals(401, response.getStatus()); + Assertions.assertEquals(401, response.getStatus()); response.close(); // Redirect client to login page if it's not an XHR response = target.request().header("X-Requested-With", "Dont-Know").header(HttpHeaders.ACCEPT, "*/*").get(); - Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); response.close(); // Redirect client to login page if client explicitely understands HTML responses response = target.request().header(HttpHeaders.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9").get(); - Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); response.close(); // Redirect client to login page if client understands all response types response = target.request().header(HttpHeaders.ACCEPT, "*/*").get(); - Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); response.close(); client.close(); } @@ -1903,9 +1903,9 @@ public void testReloginWithInvalidAuthSessionCookie() { authenticate.navigateTo(); waitForPageToLoad(); infoPage.assertCurrent(); - Assert.assertEquals("You are already logged in.", infoPage.getInfo()); + Assertions.assertEquals("You are already logged in.", infoPage.getInfo()); Cookie identityCookie = driver.manage().getCookieNamed(CookieType.IDENTITY.getName()); - Assert.assertNotNull(identityCookie); + Assertions.assertNotNull(identityCookie); driver.manage().deleteCookieNamed(CookieType.AUTH_SESSION_ID.getName()); driver.manage().addCookie(new Cookie(CookieType.AUTH_SESSION_ID.getName(), "invalid-value", identityCookie.getPath())); @@ -1923,7 +1923,7 @@ public void testReloginWithInvalidAuthSessionCookie() { public void testMultipleTabsParallelLogin() { try (BrowserTabUtil tabUtil = BrowserTabUtil.getInstanceAndSetEnv(driver)) { // open an application in tab1 and go to the login page - Assert.assertEquals(1, tabUtil.getCountOfTabs()); + Assertions.assertEquals(1, tabUtil.getCountOfTabs()); salesPostServletPage.navigateTo(); waitForPageToLoad(); assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage); @@ -1932,13 +1932,13 @@ public void testMultipleTabsParallelLogin() { tabUtil.newTab(salesPostServletPage.buildUri().toASCIIString()); waitForPageToLoad(); assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage); - Assert.assertEquals(2, tabUtil.getCountOfTabs()); + Assertions.assertEquals(2, tabUtil.getCountOfTabs()); testRealmSAMLPostLoginPage.form().login(bburkeUser); waitUntilElement(By.xpath("//body")).text().contains("principal=bburke"); // Go back to tab1 and it should automatically login tabUtil.closeTab(1); - Assert.assertEquals(1, tabUtil.getCountOfTabs()); + Assertions.assertEquals(1, tabUtil.getCountOfTabs()); if (driver instanceof HtmlUnitDriver) { // go to restart URI manually as JS does not work KeycloakUriBuilder current = KeycloakUriBuilder.fromUri(driver.getCurrentUrl(), false); @@ -1957,7 +1957,7 @@ public void testMultipleTabsParallelLogin() { public void testMultipleTabsParallelLoginAfterAuthSessionExpiration() { try (BrowserTabUtil tabUtil = BrowserTabUtil.getInstanceAndSetEnv(driver)) { // open an application in tab1 and go to the login page - Assert.assertEquals(1, tabUtil.getCountOfTabs()); + Assertions.assertEquals(1, tabUtil.getCountOfTabs()); salesPostServletPage.navigateTo(); waitForPageToLoad(); assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage); @@ -1966,11 +1966,11 @@ public void testMultipleTabsParallelLoginAfterAuthSessionExpiration() { tabUtil.newTab(salesPostServletPage.buildUri().toASCIIString()); waitForPageToLoad(); assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage); - Assert.assertEquals(2, tabUtil.getCountOfTabs()); + Assertions.assertEquals(2, tabUtil.getCountOfTabs()); // remove the authentication session in the server to simulate expiration Cookie sessionCookie = driver.manage().getCookieNamed(CookieType.AUTH_SESSION_ID.getName()); - Assert.assertNotNull(sessionCookie); + Assertions.assertNotNull(sessionCookie); final String authSessionId = sessionCookie.getValue(); testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName(DEMO); @@ -1984,7 +1984,7 @@ public void testMultipleTabsParallelLoginAfterAuthSessionExpiration() { testRealmSAMLPostLoginPage.form().login(bburkeUser); waitForPageToLoad(); assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage); // we are still in login - Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", + Assertions.assertEquals("Your login attempt timed out. Login will start from the beginning.", UIUtils.getTextFromElement(driver.findElement(By.cssSelector("div[class^='pf-v5-c-alert'], div[class^='alert-error']")))); // login successfully in tab2 after the error @@ -1993,7 +1993,7 @@ public void testMultipleTabsParallelLoginAfterAuthSessionExpiration() { // Go back to tab1 and it should automatically log into the app with retry tabUtil.closeTab(1); - Assert.assertEquals(1, tabUtil.getCountOfTabs()); + Assertions.assertEquals(1, tabUtil.getCountOfTabs()); if (driver instanceof HtmlUnitDriver) { // go to restart URI manually as JS does not work KeycloakUriBuilder current = KeycloakUriBuilder.fromUri(driver.getCurrentUrl(), false); @@ -2023,11 +2023,11 @@ private List impersonate(String admin, String adminPassword, String user .addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + client.tokenManager().getAccessTokenString()) .build(); HttpResponse res = httpClient.execute(req); - Assert.assertEquals(Response.Status.OK.getStatusCode(), res.getStatusLine().getStatusCode()); + Assertions.assertEquals(Response.Status.OK.getStatusCode(), res.getStatusLine().getStatusCode()); String resBody = EntityUtils.toString(res.getEntity()); - Assert.assertNotNull(resBody); - Assert.assertTrue(resBody.contains("redirect")); + Assertions.assertNotNull(resBody); + Assertions.assertTrue(resBody.contains("redirect")); // return cookies not expired in the store as selenium cookies final Date now = new Date(); @@ -2044,12 +2044,12 @@ public void testImpersonationForSaml() throws IOException { RealmResource realm = adminClient.realm(SAMLSERVLETDEMO); List users = realm.users().search("bburke", true); - Assert.assertNotNull(users); - Assert.assertEquals(1, users.size()); + Assertions.assertNotNull(users); + Assertions.assertEquals(1, users.size()); // impersonate and get all returned cookies List cookies = impersonate("admindemo", "password", users.get(0).getId()); - Assert.assertNotNull(cookies); + Assertions.assertNotNull(cookies); // go to the authenticate page and add all the returned cookies by the impersonation authenticate.setAuthRealm(SAMLSERVLETDEMO); @@ -2060,7 +2060,7 @@ public void testImpersonationForSaml() throws IOException { driver.navigate().refresh(); waitForPageToLoad(); infoPage.assertCurrent(); - Assert.assertEquals("You are already logged in.", infoPage.getInfo()); + Assertions.assertEquals("You are already logged in.", infoPage.getInfo()); // now go to the saml app with all the impersonation cookies testRealmSAMLPostLoginPage.navigateTo(); @@ -2097,17 +2097,17 @@ public void testChangeSessionID() throws Exception { driver.navigate().to(employeeDomServletPage.getUriBuilder().clone().path("getAssertionFromDocument").build().toURL()); waitForPageToLoad(); String xml = getRawPageSource(); - Assert.assertNotEquals("", xml); + Assertions.assertNotEquals("", xml); // change the session id driver.navigate().to(employeeDomServletPage.getUriBuilder().clone().path("change-session-id").build().toURL()); waitForPageToLoad(); - Assert.assertNotEquals("SessionID has not been changed at login", sessionId, getCookieValue("JSESSIONID", "/employee-dom")); + Assertions.assertNotEquals(sessionId, getCookieValue("JSESSIONID", "/employee-dom"), "SessionID has not been changed at login"); // retrieve again the saml document and should be the same as login should be maintained driver.navigate().to(employeeDomServletPage.getUriBuilder().clone().path("getAssertionFromDocument").build().toURL()); waitForPageToLoad(); - Assert.assertEquals(xml, getRawPageSource()); + Assertions.assertEquals(xml, getRawPageSource()); // logout employeeDomServletPage.logout(); @@ -2151,7 +2151,7 @@ private void validateXMLWithSchema(String xml, String schemaFileName) throws SAX } catch (SAXException e) { System.out.println(xmlFile.getSystemId() + " is NOT valid"); System.out.println("Reason: " + e.getLocalizedMessage()); - Assert.fail(); + Assertions.fail(); } } @@ -2159,7 +2159,7 @@ private void assertOnForbiddenPage() { waitUntilElement(By.xpath("//body")).is().present(); //Different 403 status page on EAP and Wildfly - Assert.assertTrue(driver.getPageSource().contains("Forbidden") + Assertions.assertTrue(driver.getPageSource().contains("Forbidden") || driver.getPageSource().contains(FORBIDDEN_TEXT) || driver.getPageSource().contains(WEBSPHERE_FORBIDDEN_TEXT)); // WebSphere } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SamlSignatureTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SamlSignatureTest.java index 857d3b559c7e..a56db059bb9e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SamlSignatureTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/servlet/SamlSignatureTest.java @@ -67,10 +67,10 @@ import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.graphene.page.Page; import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -398,7 +398,7 @@ private static void removeAllSignatures(Document doc) throws DOMException { private static void removeDocumentSignature(Document doc) throws DOMException { Element responseSignature = (Element) doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature").item(0); - Assert.assertNotNull(doc.getDocumentElement().removeChild(responseSignature)); + Assertions.assertNotNull(doc.getDocumentElement().removeChild(responseSignature)); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AbstractResourceServerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AbstractResourceServerTest.java index 3bf77657d85a..a44434ac7f29 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AbstractResourceServerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AbstractResourceServerTest.java @@ -46,7 +46,7 @@ import org.keycloak.testsuite.util.RolesBuilder; import org.keycloak.testsuite.util.UserBuilder; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AttributeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AttributeTest.java index 92ae0672bda7..c6c4327c75d5 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AttributeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AttributeTest.java @@ -30,9 +30,9 @@ import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthorizationAPITest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthorizationAPITest.java index d5bc37c32625..1213e1be3676 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthorizationAPITest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthorizationAPITest.java @@ -38,7 +38,6 @@ import org.keycloak.representations.idm.authorization.PolicyRepresentation; import org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation; import org.keycloak.representations.idm.authorization.ResourceRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.client.resources.TestApplicationResourceUrls; import org.keycloak.testsuite.util.ClientBuilder; import org.keycloak.testsuite.util.RealmBuilder; @@ -49,12 +48,13 @@ import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Pedro Igor @@ -210,8 +210,8 @@ public void testResourceServerAsAudience(String clientId, String resourceServerC // Ticket is opaque to client or resourceServer. The audience should be just an authorization server itself JsonWebToken ticketDecoded = JsonSerialization.readValue(new JWSInput(ticket).getContent(), JsonWebToken.class); - Assert.assertFalse(ticketDecoded.hasAudience(clientId)); - Assert.assertFalse(ticketDecoded.hasAudience(resourceServerClientId)); + Assertions.assertFalse(ticketDecoded.hasAudience(clientId)); + Assertions.assertFalse(ticketDecoded.hasAudience(resourceServerClientId)); AuthorizationResponse response = authzClient.authorization(accessToken).authorize(new AuthorizationRequest(ticket)); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthorizationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthorizationTest.java index ac611de0a93d..776a6eb43981 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthorizationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthorizationTest.java @@ -51,9 +51,9 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthzClientCredentialsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthzClientCredentialsTest.java index 08feaaf7128d..0f41d67415fa 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthzClientCredentialsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthzClientCredentialsTest.java @@ -63,12 +63,12 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Bill Burke diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthzClientTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthzClientTest.java index 2c9d7d617a74..4a1faf047a07 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthzClientTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/AuthzClientTest.java @@ -6,10 +6,10 @@ import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.EnvironmentVariables; +import org.junit.jupiter.api.Assertions; public class AuthzClientTest { @@ -21,7 +21,7 @@ public void testCreateWithEnvVars() { envVars.set("KEYCLOAK_REALM", "test"); envVars.set("KEYCLOAK_AUTH_SERVER", "http://test"); - RuntimeException runtimeException = Assert.assertThrows(RuntimeException.class, () -> { + RuntimeException runtimeException = Assertions.assertThrows(RuntimeException.class, () -> { AuthzClient.create(new ByteArrayInputStream(("{\n" + " \"realm\": \"${env.KEYCLOAK_REALM}\",\n" diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/ClientScopePolicyTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/ClientScopePolicyTest.java index 2ced48c86af2..4791562796f6 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/ClientScopePolicyTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/ClientScopePolicyTest.java @@ -41,10 +41,10 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Yoshiyuki Tabata diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/ConflictingScopePermissionTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/ConflictingScopePermissionTest.java index 4b2896407eb5..c02a5d7cb314 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/ConflictingScopePermissionTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/ConflictingScopePermissionTest.java @@ -55,10 +55,10 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Bill Burke @@ -263,7 +263,7 @@ private Collection getEntitlements(String username, String password) AccessToken.Authorization authorization = accessToken.getAuthorization(); - assertNotNull("RPT does not contain any authorization data", authorization); + assertNotNull(authorization, "RPT does not contain any authorization data"); return authorization.getPermissions(); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/EntitlementAPITest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/EntitlementAPITest.java index dd6a5a577724..4bbaae7de179 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/EntitlementAPITest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/EntitlementAPITest.java @@ -100,12 +100,12 @@ import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/GroupNamePolicyTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/GroupNamePolicyTest.java index e6fd91a600b7..0a7153d78ec0 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/GroupNamePolicyTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/GroupNamePolicyTest.java @@ -53,8 +53,8 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/GroupPathPolicyTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/GroupPathPolicyTest.java index 1b73ba8ef6e4..48afe994b91b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/GroupPathPolicyTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/GroupPathPolicyTest.java @@ -53,8 +53,8 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PermissionClaimTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PermissionClaimTest.java index 170c30f6c444..c697afe34080 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PermissionClaimTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PermissionClaimTest.java @@ -59,10 +59,10 @@ import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PermissionEqualsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PermissionEqualsTest.java index 205f15c73b93..ffb0340b3f99 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PermissionEqualsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PermissionEqualsTest.java @@ -25,8 +25,8 @@ import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PermissionManagementTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PermissionManagementTest.java index de405316b1fa..70bc1bab8ee6 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PermissionManagementTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PermissionManagementTest.java @@ -47,11 +47,11 @@ import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor @@ -477,19 +477,19 @@ public void testGetPermissionTicketWithPagination() throws Exception { // start with fetching the second half of all permission tickets Collection expectedScopes = new ArrayList(Arrays.asList(scopes)); List tickets = getAuthzClient().protection().permission().find(resource.getId(), null, null, null, null, true, 2, 2); - assertEquals("Returned number of permissions tickets must match the specified page size (i.e., 'maxResult').", 2, tickets.size()); + assertEquals(2, tickets.size(), "Returned number of permissions tickets must match the specified page size (i.e., 'maxResult')."); boolean foundScope = expectedScopes.remove(tickets.get(0).getScopeName()); - assertTrue("Returned set of permission tickets must be only a sub-set as per pagination offset and specified page size.", foundScope); + assertTrue(foundScope, "Returned set of permission tickets must be only a sub-set as per pagination offset and specified page size."); foundScope = expectedScopes.remove(tickets.get(1).getScopeName()); - assertTrue("Returned set of permission tickets must be only a sub-set as per pagination offset and specified page size.", foundScope); + assertTrue(foundScope, "Returned set of permission tickets must be only a sub-set as per pagination offset and specified page size."); // fetch the first half of all permission tickets tickets = getAuthzClient().protection().permission().find(resource.getId(), null, null, null, null, true, 0, 2); - assertEquals("Returned number of permissions tickets must match the specified page size (i.e., 'maxResult').", 2, tickets.size()); + assertEquals(2, tickets.size(), "Returned number of permissions tickets must match the specified page size (i.e., 'maxResult')."); foundScope = expectedScopes.remove(tickets.get(0).getScopeName()); - assertTrue("Returned set of permission tickets must be only a sub-set as per pagination offset and specified page size.", foundScope); + assertTrue(foundScope, "Returned set of permission tickets must be only a sub-set as per pagination offset and specified page size."); foundScope = expectedScopes.remove(tickets.get(1).getScopeName()); - assertTrue("Returned set of permission tickets must be only a sub-set as per pagination offset and specified page size.", foundScope); + assertTrue(foundScope, "Returned set of permission tickets must be only a sub-set as per pagination offset and specified page size."); } @Test @@ -509,6 +509,6 @@ public void testPermissionCount() throws Exception { } Long ticketCount = getAuthzClient().protection().permission().count(resource.getId(), null, null, null, null, true); - assertEquals("Returned number of permissions tickets must match the amount of permission tickets.", Long.valueOf(4), ticketCount); + assertEquals(Long.valueOf(4), ticketCount, "Returned number of permissions tickets must match the amount of permission tickets."); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationCompositeRoleTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationCompositeRoleTest.java index f10ea991edfa..014c9f8641a0 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationCompositeRoleTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationCompositeRoleTest.java @@ -42,8 +42,8 @@ import org.keycloak.representations.idm.authorization.PolicyRepresentation; import org.keycloak.representations.idm.authorization.ScopePermissionRepresentation; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.auth.page.AuthRealm.TEST; @@ -132,7 +132,7 @@ public void testCreate() throws Exception { request.setClientId(resourceServerId); request.addResource("myresource", "myscope"); PolicyEvaluationResponse result = realm.clients().get(resourceServerId).authorization().policies().evaluate(request); - Assert.assertEquals(DecisionEffect.PERMIT, result.getStatus()); + Assertions.assertEquals(DecisionEffect.PERMIT, result.getStatus()); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationTest.java index b3bcca4b7158..bc1176798bfc 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/PolicyEvaluationTest.java @@ -80,12 +80,12 @@ import org.keycloak.testsuite.util.RolesBuilder; import org.keycloak.testsuite.util.UserBuilder; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Pedro Igor @@ -199,7 +199,7 @@ public static void testCheckUserInGroup(KeycloakSession session) { provider.evaluate(evaluation); - Assert.assertNull(evaluation.getEffect()); + Assertions.assertNull(evaluation.getEffect()); policyRepresentation = new JSPolicyRepresentation(); policyRepresentation.setId(KeycloakModelUtils.generateId()); @@ -236,7 +236,7 @@ public static void testCheckUserInGroup(KeycloakSession session) { provider.evaluate(evaluation); - Assert.assertNull(evaluation.getEffect()); + Assertions.assertNull(evaluation.getEffect()); policyRepresentation = new JSPolicyRepresentation(); policyRepresentation.setName("allow-user-in-group-path-e-policy"); @@ -272,7 +272,7 @@ public static void testCheckUserInGroup(KeycloakSession session) { provider.evaluate(evaluation); - Assert.assertNull(evaluation.getEffect()); + Assertions.assertNull(evaluation.getEffect()); policyRepresentation = new JSPolicyRepresentation(); policyRepresentation.setName("allow-alice-in-group-path-e-policy.js"); @@ -284,7 +284,7 @@ public static void testCheckUserInGroup(KeycloakSession session) { provider.evaluate(evaluation); - Assert.assertNull(evaluation.getEffect()); + Assertions.assertNull(evaluation.getEffect()); policyRepresentation = new JSPolicyRepresentation(); policyRepresentation.setName("allow-alice-in-group-name-e-policy.js"); @@ -296,7 +296,7 @@ public static void testCheckUserInGroup(KeycloakSession session) { provider.evaluate(evaluation); - Assert.assertNull(evaluation.getEffect()); + Assertions.assertNull(evaluation.getEffect()); } @Test @@ -335,7 +335,7 @@ public static void testCheckUserInRole(KeycloakSession session) { provider.evaluate(evaluation); - Assert.assertNull(evaluation.getEffect()); + Assertions.assertNull(evaluation.getEffect()); } @Test @@ -373,7 +373,7 @@ public static void testCheckUserInClientRole(KeycloakSession session) { provider.evaluate(evaluation); - Assert.assertNull(evaluation.getEffect()); + Assertions.assertNull(evaluation.getEffect()); } @Test @@ -412,7 +412,7 @@ public static void testCheckGroupInRole(KeycloakSession session) { provider.evaluate(evaluation); - Assert.assertNull(evaluation.getEffect()); + Assertions.assertNull(evaluation.getEffect()); } @Test @@ -593,7 +593,7 @@ public static void testCheckReadOnlyInstances(KeycloakSession session) { try { evaluator.evaluate(resourceServer, null); - Assert.fail("Instances should be marked as read-only"); + Assertions.fail("Instances should be marked as read-only"); } catch (Exception ignore) { } } finally { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/RegexPolicyTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/RegexPolicyTest.java index e07f31cd9b76..d3ced6d3b2c0 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/RegexPolicyTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/RegexPolicyTest.java @@ -48,12 +48,12 @@ import org.keycloak.testsuite.util.RealmBuilder; import org.keycloak.testsuite.util.UserBuilder; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Yoshiyuki Tabata @@ -302,8 +302,8 @@ public void testWithExpectedUserAttributeValueMappedToComplexJsonClaimPermission theRequest.setMetadata(metadata); List permissions = authzClient.authorization("admin", "password").getPermissions(theRequest); assertNotNull(permissions); - Assert.assertTrue(permissions.get(0).getResourceName().equals("service")); - Assert.assertTrue(permissions.get(0).getScopes().contains("read")); + Assertions.assertTrue(permissions.get(0).getResourceName().equals("service")); + Assertions.assertTrue(permissions.get(0).getScopes().contains("read")); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/RolePolicyTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/RolePolicyTest.java index 487d3acb7af9..92437ceae90a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/RolePolicyTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/RolePolicyTest.java @@ -49,8 +49,8 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaDiscoveryDocumentTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaDiscoveryDocumentTest.java index 288245745749..e80012cbbf95 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaDiscoveryDocumentTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaDiscoveryDocumentTest.java @@ -38,7 +38,7 @@ import org.jboss.arquillian.test.api.ArquillianResource; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class UmaDiscoveryDocumentTest extends AbstractKeycloakTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaGrantTypeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaGrantTypeTest.java index dbbf95f870a1..ddc418465049 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaGrantTypeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaGrantTypeTest.java @@ -70,12 +70,12 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaPermissionTicketPushedClaimsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaPermissionTicketPushedClaimsTest.java index f6d0f20c620b..7b3e686ff3d5 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaPermissionTicketPushedClaimsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaPermissionTicketPushedClaimsTest.java @@ -38,9 +38,9 @@ import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaResourceTypeRepresentationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaResourceTypeRepresentationTest.java index ba923a7a21cb..1613c562f6fe 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaResourceTypeRepresentationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UmaResourceTypeRepresentationTest.java @@ -30,8 +30,8 @@ import org.keycloak.representations.idm.authorization.PolicyEvaluationResponse.PolicyResultRepresentation; import org.keycloak.representations.idm.authorization.ResourceRepresentation; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; public class UmaResourceTypeRepresentationTest extends AbstractResourceServerTest { private ResourceRepresentation resource; @@ -54,15 +54,15 @@ public void testCanRepresentPermissionTicketWithNamesOfResourceOwnedByUser() thr createPermissionTicket(); List permissionTickets = permission.find(resource.getId(), null, null, null, null, true, null, null); - Assert.assertFalse(permissionTickets.isEmpty()); - Assert.assertEquals(1, permissionTickets.size()); + Assertions.assertFalse(permissionTickets.isEmpty()); + Assertions.assertEquals(1, permissionTickets.size()); PermissionTicketRepresentation ticket = permissionTickets.get(0); - Assert.assertEquals(ticket.getOwnerName(), "marta"); - Assert.assertEquals(ticket.getRequesterName(), "kolo"); - Assert.assertEquals(ticket.getResourceName(), "Resource A"); - Assert.assertEquals(ticket.getScopeName(), "ScopeA"); - Assert.assertTrue(ticket.isGranted()); + Assertions.assertEquals(ticket.getOwnerName(), "marta"); + Assertions.assertEquals(ticket.getRequesterName(), "kolo"); + Assertions.assertEquals(ticket.getResourceName(), "Resource A"); + Assertions.assertEquals(ticket.getScopeName(), "ScopeA"); + Assertions.assertTrue(ticket.isGranted()); } @Test @@ -72,15 +72,15 @@ public void testCanRepresentPermissionTicketWithNamesOfResourceOwnedByClient() t createPermissionTicket(); List permissionTickets = permission.find(resource.getId(), null, null, null, null, true, null, null); - Assert.assertFalse(permissionTickets.isEmpty()); - Assert.assertEquals(1, permissionTickets.size()); + Assertions.assertFalse(permissionTickets.isEmpty()); + Assertions.assertEquals(1, permissionTickets.size()); PermissionTicketRepresentation ticket = permissionTickets.get(0); - Assert.assertEquals(ticket.getOwnerName(), "resource-server-test"); - Assert.assertEquals(ticket.getRequesterName(), "kolo"); - Assert.assertEquals(ticket.getResourceName(), "Resource A"); - Assert.assertEquals(ticket.getScopeName(), "ScopeA"); - Assert.assertTrue(ticket.isGranted()); + Assertions.assertEquals(ticket.getOwnerName(), "resource-server-test"); + Assertions.assertEquals(ticket.getRequesterName(), "kolo"); + Assertions.assertEquals(ticket.getResourceName(), "Resource A"); + Assertions.assertEquals(ticket.getScopeName(), "ScopeA"); + Assertions.assertTrue(ticket.isGranted()); } @Test @@ -98,18 +98,18 @@ public void testCanRepresentPolicyResultGrantOfResourceOwnedByUser() throws Exce request.setClientId(resourceServerId); request.addResource("Resource A", "ScopeA"); PolicyEvaluationResponse result = getClient(realm).authorization().policies().evaluate(request); - Assert.assertEquals(result.getStatus(), DecisionEffect.PERMIT); + Assertions.assertEquals(result.getStatus(), DecisionEffect.PERMIT); List evaluations = result.getResults(); - Assert.assertFalse(evaluations.isEmpty()); - Assert.assertEquals(1, evaluations.size()); + Assertions.assertFalse(evaluations.isEmpty()); + Assertions.assertEquals(1, evaluations.size()); Set policies = evaluations.get(0).getPolicies(); - Assert.assertFalse(evaluations.isEmpty()); - Assert.assertEquals(1, evaluations.size()); + Assertions.assertFalse(evaluations.isEmpty()); + Assertions.assertEquals(1, evaluations.size()); String description = policies.iterator().next().getPolicy().getDescription(); - Assert.assertTrue(description.startsWith("Resource owner (marta) grants access")); + Assertions.assertTrue(description.startsWith("Resource owner (marta) grants access")); } @Test @@ -127,17 +127,17 @@ public void testCanRepresentPolicyResultGrantOfResourceOwnedByClient() throws Ex request.setClientId(resourceServerId); request.addResource("Resource A", "ScopeA"); PolicyEvaluationResponse result = getClient(realm).authorization().policies().evaluate(request); - Assert.assertEquals(result.getStatus(), DecisionEffect.PERMIT); + Assertions.assertEquals(result.getStatus(), DecisionEffect.PERMIT); List evaluations = result.getResults(); - Assert.assertFalse(evaluations.isEmpty()); - Assert.assertEquals(1, evaluations.size()); + Assertions.assertFalse(evaluations.isEmpty()); + Assertions.assertEquals(1, evaluations.size()); Set policies = evaluations.get(0).getPolicies(); - Assert.assertFalse(evaluations.isEmpty()); - Assert.assertEquals(1, evaluations.size()); + Assertions.assertFalse(evaluations.isEmpty()); + Assertions.assertEquals(1, evaluations.size()); String description = policies.iterator().next().getPolicy().getDescription(); - Assert.assertTrue(description.startsWith("Resource owner (resource-server-test) grants access")); + Assertions.assertTrue(description.startsWith("Resource owner (resource-server-test) grants access")); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UserManagedAccessTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UserManagedAccessTest.java index 203359cf4dff..f47fc3af435a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UserManagedAccessTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UserManagedAccessTest.java @@ -45,11 +45,11 @@ import org.junit.Rule; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UserManagedPermissionServiceTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UserManagedPermissionServiceTest.java index 38bbcc779987..4848edcc5cd2 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UserManagedPermissionServiceTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/UserManagedPermissionServiceTest.java @@ -72,11 +72,11 @@ import static org.keycloak.authorization.model.Policy.FilterOption.OWNER; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AbstractAuthorizationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AbstractAuthorizationTest.java index 1ad9357fda85..05f09e2bbe1d 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AbstractAuthorizationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AbstractAuthorizationTest.java @@ -40,7 +40,7 @@ import static org.keycloak.common.Profile.Feature.AUTHORIZATION; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AbstractPolicyManagementTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AbstractPolicyManagementTest.java index b9cf62ac4c18..47c7ddb9ca3d 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AbstractPolicyManagementTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AbstractPolicyManagementTest.java @@ -45,10 +45,10 @@ import static org.keycloak.common.Profile.Feature.AUTHORIZATION; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AggregatePolicyManagementTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AggregatePolicyManagementTest.java index fc507f8a6eca..3d56efa03795 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AggregatePolicyManagementTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AggregatePolicyManagementTest.java @@ -38,8 +38,8 @@ import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AuthorizationDisabledInPreviewTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AuthorizationDisabledInPreviewTest.java index c064e68ccae8..8eadc9ab2c2f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AuthorizationDisabledInPreviewTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AuthorizationDisabledInPreviewTest.java @@ -28,8 +28,8 @@ import org.junit.BeforeClass; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Stian Thorgersen diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AuthorizationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AuthorizationTest.java index 9d9a758d3cb9..ba2991e7bb66 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AuthorizationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/AuthorizationTest.java @@ -31,11 +31,11 @@ import org.keycloak.representations.idm.authorization.ResourceServerRepresentation; import org.keycloak.representations.idm.authorization.RolePolicyRepresentation; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @@ -50,18 +50,18 @@ public void testEnableAuthorizationServices() { RealmResource realm = realmsResouce().realm(getRealmId()); UserRepresentation serviceAccount = realm.users().search(ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + resourceServer.getClientId()).get(0); - Assert.assertNotNull(serviceAccount); + Assertions.assertNotNull(serviceAccount); List serviceAccountRoles = realm.users().get(serviceAccount.getId()).roles().clientLevel(resourceServer.getId()).listEffective(); - Assert.assertTrue(serviceAccountRoles.stream().anyMatch(roleRepresentation -> "uma_protection".equals(roleRepresentation.getName()))); + Assertions.assertTrue(serviceAccountRoles.stream().anyMatch(roleRepresentation -> "uma_protection".equals(roleRepresentation.getName()))); enableAuthorizationServices(false); enableAuthorizationServices(true); serviceAccount = clientResource.getServiceAccountUser(); - Assert.assertNotNull(serviceAccount); + Assertions.assertNotNull(serviceAccount); realm = realmsResouce().realm(getRealmId()); serviceAccountRoles = realm.users().get(serviceAccount.getId()).roles().clientLevel(resourceServer.getId()).listEffective(); - Assert.assertTrue(serviceAccountRoles.stream().anyMatch(roleRepresentation -> "uma_protection".equals(roleRepresentation.getName()))); + Assertions.assertTrue(serviceAccountRoles.stream().anyMatch(roleRepresentation -> "uma_protection".equals(roleRepresentation.getName()))); RolePolicyRepresentation policy = new RolePolicyRepresentation(); @@ -86,8 +86,8 @@ public void testEnableAuthorizationServices() { assertTrue(policies.isEmpty()); serviceAccount = clientResource.getServiceAccountUser(); - Assert.assertNotNull(serviceAccount); + Assertions.assertNotNull(serviceAccount); serviceAccountRoles = realm.users().get(serviceAccount.getId()).roles().clientLevel(resourceServer.getId()).listEffective(); - Assert.assertTrue(serviceAccountRoles.stream().anyMatch(roleRepresentation -> "uma_protection".equals(roleRepresentation.getName()))); + Assertions.assertTrue(serviceAccountRoles.stream().anyMatch(roleRepresentation -> "uma_protection".equals(roleRepresentation.getName()))); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ClientPolicyManagementTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ClientPolicyManagementTest.java index a3339ba01e61..6e0548fda7bd 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ClientPolicyManagementTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ClientPolicyManagementTest.java @@ -35,13 +35,13 @@ import org.keycloak.testsuite.util.ClientBuilder; import org.keycloak.testsuite.util.RealmBuilder; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor @@ -156,24 +156,24 @@ public void testDeleteClient() { representation = authorization.policies().client().findById(representation.getId()).toRepresentation(); - Assert.assertEquals(2, representation.getClients().size()); - Assert.assertFalse(representation.getClients().contains(client.getId())); + Assertions.assertEquals(2, representation.getClients().size()); + Assertions.assertFalse(representation.getClients().contains(client.getId())); client = clients.findByClientId("Client E").get(0); clients.get(client.getId()).remove(); representation = authorization.policies().client().findById(representation.getId()).toRepresentation(); - Assert.assertEquals(1, representation.getClients().size()); - Assert.assertFalse(representation.getClients().contains(client.getId())); + Assertions.assertEquals(1, representation.getClients().size()); + Assertions.assertFalse(representation.getClients().contains(client.getId())); client = clients.findByClientId("Client F").get(0); clients.get(client.getId()).remove(); representation = authorization.policies().client().findById(representation.getId()).toRepresentation(); - Assert.assertEquals(0, representation.getClients().size()); - Assert.assertFalse(representation.getClients().contains(client.getId())); + Assertions.assertEquals(0, representation.getClients().size()); + Assertions.assertFalse(representation.getClients().contains(client.getId())); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ExportAuthorizationSettingsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ExportAuthorizationSettingsTest.java index fb38f52c0a76..20ccf0d81625 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ExportAuthorizationSettingsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ExportAuthorizationSettingsTest.java @@ -32,11 +32,11 @@ import org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation; import org.keycloak.representations.idm.authorization.ResourceRepresentation; import org.keycloak.representations.idm.authorization.ResourceServerRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.ClientBuilder; import org.keycloak.testsuite.util.RoleBuilder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; @@ -59,7 +59,7 @@ public void testResourceBasedPermission() throws Exception { ResourceRepresentation resourceRepresentation = new ResourceRepresentation(); resourceRepresentation.setName("resource-for-export-test"); try (Response response = authorizationResource.resources().create(resourceRepresentation)) { - Assert.assertEquals(Status.CREATED, response.getStatusInfo()); + Assertions.assertEquals(Status.CREATED, response.getStatusInfo()); } List resources = authorizationResource.resources().findByName("resource-for-export-test"); assertThat(resources, hasSize(1)); @@ -69,7 +69,7 @@ public void testResourceBasedPermission() throws Exception { policyRepresentation.setName("policy-for-export-test"); policyRepresentation.setType("client"); try (Response response = authorizationResource.policies().create(policyRepresentation)) { - Assert.assertEquals(Status.CREATED, response.getStatusInfo()); + Assertions.assertEquals(Status.CREATED, response.getStatusInfo()); } PolicyRepresentation policy = authorizationResource.policies().findByName("policy-for-export-test"); assertThat(policy, notNullValue()); @@ -81,7 +81,7 @@ public void testResourceBasedPermission() throws Exception { permission.addResource(resourceId); try (Response create = authorizationResource.permissions().resource().create(permission)) { - Assert.assertEquals(Status.CREATED, create.getStatusInfo()); + Assertions.assertEquals(Status.CREATED, create.getStatusInfo()); } //export authorization settings @@ -92,11 +92,11 @@ public void testResourceBasedPermission() throws Exception { for (PolicyRepresentation p : exportSettings.getPolicies()) { if (p.getName().equals(permissionName)) { found = true; - Assert.assertEquals("[\"resource-for-export-test\"]", p.getConfig().get("resources")); - Assert.assertEquals("[\"policy-for-export-test\"]", p.getConfig().get("applyPolicies")); + Assertions.assertEquals("[\"resource-for-export-test\"]", p.getConfig().get("resources")); + Assertions.assertEquals("[\"policy-for-export-test\"]", p.getConfig().get("applyPolicies")); } } - Assert.assertTrue("Permission \"role-based-permission\" was not found.", found); + Assertions.assertTrue(found, "Permission \"role-based-permission\" was not found."); } //KEYCLOAK-4340 @@ -116,7 +116,7 @@ public void testRoleBasedPolicy() { policy.setConfig(config); Response create = authorizationResource.policies().create(policy); try { - Assert.assertEquals(Status.CREATED, create.getStatusInfo()); + Assertions.assertEquals(Status.CREATED, create.getStatusInfo()); } finally { create.close(); } @@ -154,7 +154,7 @@ public void testRoleBasedPolicyWithMultipleRoles() { config.put("roles", "[{\"id\":\"" + role1.getId() +"\"},{\"id\":\"" + role2.getId() +"\"}]"); policy.setConfig(config); try (Response create = authorizationResource.policies().create(policy)) { - Assert.assertEquals(Status.CREATED, create.getStatusInfo()); + Assertions.assertEquals(Status.CREATED, create.getStatusInfo()); } //export authorization settings @@ -164,18 +164,18 @@ public void testRoleBasedPolicyWithMultipleRoles() { for (PolicyRepresentation p : exportSettings.getPolicies()) { if (p.getName().equals("role-based-policy")) { found = true; - Assert.assertTrue(p.getConfig().get("roles").contains("test-client-1/client-role") && + Assertions.assertTrue(p.getConfig().get("roles").contains("test-client-1/client-role") && p.getConfig().get("roles").contains("test-client-2/client-role")); } } if (!found) { - Assert.fail("Policy \"role-based-policy\" was not found in exported settings."); + Assertions.fail("Policy \"role-based-policy\" was not found in exported settings."); } } private ClientRepresentation getClientByClientId(String clientId) { List findByClientId = testRealmResource().clients().findByClientId(clientId); - Assert.assertTrue(findByClientId.size() == 1); + Assertions.assertTrue(findByClientId.size() == 1); return findByClientId.get(0); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/GenericPolicyManagementTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/GenericPolicyManagementTest.java index 61272dfaeb13..a945c4ff8c32 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/GenericPolicyManagementTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/GenericPolicyManagementTest.java @@ -45,11 +45,11 @@ import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/GroupPolicyManagementTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/GroupPolicyManagementTest.java index cc9702dd2308..a300e8bc7e5e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/GroupPolicyManagementTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/GroupPolicyManagementTest.java @@ -40,10 +40,10 @@ import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ImportAuthorizationSettingsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ImportAuthorizationSettingsTest.java index 705427b22b6a..8fcc77f8fdb7 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ImportAuthorizationSettingsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ImportAuthorizationSettingsTest.java @@ -27,7 +27,7 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/JSPolicyManagementTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/JSPolicyManagementTest.java index b82348bc424a..f1b850e0dae7 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/JSPolicyManagementTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/JSPolicyManagementTest.java @@ -32,8 +32,8 @@ import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ResourceManagementTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ResourceManagementTest.java index 7974033e52a5..556ab98083aa 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ResourceManagementTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ResourceManagementTest.java @@ -39,12 +39,12 @@ import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ResourceManagementWithAuthzClientTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ResourceManagementWithAuthzClientTest.java index 2f86ce09d565..e15042f69112 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ResourceManagementWithAuthzClientTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ResourceManagementWithAuthzClientTest.java @@ -33,8 +33,8 @@ import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ResourcePermissionManagementTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ResourcePermissionManagementTest.java index 750f5ee6e0a9..c14a1a268045 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ResourcePermissionManagementTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ResourcePermissionManagementTest.java @@ -30,8 +30,8 @@ import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ResourceServerManagementTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ResourceServerManagementTest.java index 7f8503ed8ae4..72453e8ccb69 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ResourceServerManagementTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ResourceServerManagementTest.java @@ -37,11 +37,11 @@ import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/RolePolicyManagementTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/RolePolicyManagementTest.java index 2f3d85a2bb62..b2d241fd8997 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/RolePolicyManagementTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/RolePolicyManagementTest.java @@ -38,17 +38,17 @@ import org.keycloak.representations.idm.authorization.Logic; import org.keycloak.representations.idm.authorization.PolicyRepresentation; import org.keycloak.representations.idm.authorization.RolePolicyRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.RealmBuilder; import org.keycloak.testsuite.util.RoleBuilder; import org.keycloak.testsuite.util.RolesBuilder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor @@ -261,7 +261,7 @@ public void testFailDuplicatedRoles() { representation.addRole("Role B"); try { authorization.policies().role().findById(representation.getId()).update(representation); - Assert.fail("should fail due to duplicated roles"); + Assertions.fail("should fail due to duplicated roles"); } catch (BadRequestException bre) { Response response = bre.getResponse(); assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ScopeManagementTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ScopeManagementTest.java index e86636701d41..00e7d110b2da 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ScopeManagementTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ScopeManagementTest.java @@ -32,8 +32,8 @@ import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ScopePermissionManagementTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ScopePermissionManagementTest.java index 3f1666d2c9bf..228aeda56c4d 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ScopePermissionManagementTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/ScopePermissionManagementTest.java @@ -28,8 +28,8 @@ import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/TimePolicyManagementTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/TimePolicyManagementTest.java index 4ab063335ff1..cf772500cd6b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/TimePolicyManagementTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/TimePolicyManagementTest.java @@ -31,12 +31,12 @@ import org.keycloak.representations.idm.authorization.DecisionStrategy; import org.keycloak.representations.idm.authorization.Logic; import org.keycloak.representations.idm.authorization.TimePolicyRepresentation; -import org.keycloak.testsuite.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor @@ -154,7 +154,7 @@ public void testInvalidDateFormat() { try { representation.setNotOnOrAfter("2016-02-01 00:00:00"); authorization.policies().time().findById(representation.getId()).update(representation); - Assert.fail("should fail due to invalid dates"); + Assertions.fail("should fail due to invalid dates"); } catch (BadRequestException bre) { Response response = bre.getResponse(); assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/UserPolicyManagementTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/UserPolicyManagementTest.java index c4889110c91e..2312cc3ac41c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/UserPolicyManagementTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/UserPolicyManagementTest.java @@ -38,13 +38,13 @@ import org.keycloak.testsuite.util.RealmBuilder; import org.keycloak.testsuite.util.UserBuilder; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor @@ -165,24 +165,24 @@ public void testDeleteUser() { representation = authorization.policies().user().findById(representation.getId()).toRepresentation(); - Assert.assertEquals(2, representation.getUsers().size()); - Assert.assertFalse(representation.getUsers().contains(user.getId())); + Assertions.assertEquals(2, representation.getUsers().size()); + Assertions.assertFalse(representation.getUsers().contains(user.getId())); user = users.search("User E").get(0); users.get(user.getId()).remove(); representation = authorization.policies().user().findById(representation.getId()).toRepresentation(); - Assert.assertEquals(1, representation.getUsers().size()); - Assert.assertFalse(representation.getUsers().contains(user.getId())); + Assertions.assertEquals(1, representation.getUsers().size()); + Assertions.assertFalse(representation.getUsers().contains(user.getId())); user = users.search("User F").get(0); users.get(user.getId()).remove(); representation = authorization.policies().user().findById(representation.getId()).toRepresentation(); - Assert.assertEquals(0, representation.getUsers().size()); - Assert.assertFalse(representation.getUsers().contains(user.getId())); + Assertions.assertEquals(0, representation.getUsers().size()); + Assertions.assertFalse(representation.getUsers().contains(user.getId())); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/permissions/ExportImportTestFGAPV2.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/permissions/ExportImportTestFGAPV2.java index 753d8dcc8c2e..979fc4d733e4 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/permissions/ExportImportTestFGAPV2.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/admin/permissions/ExportImportTestFGAPV2.java @@ -30,8 +30,8 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ExportImportTestFGAPV2 extends ExportImportTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractAdvancedBrokerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractAdvancedBrokerTest.java index ec47d5d45c89..d4ef6fa6bd93 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractAdvancedBrokerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractAdvancedBrokerTest.java @@ -23,7 +23,6 @@ import org.keycloak.representations.idm.RoleRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.storage.UserStorageProvider; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.federation.DummyUserFederationProviderFactory; import org.keycloak.testsuite.util.AccountHelper; @@ -33,6 +32,7 @@ import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.TimeoutException; import static org.keycloak.testsuite.admin.AdminApiUtil.removeUserByUsername; @@ -47,11 +47,11 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test of advanced functionalities related to brokering like: @@ -100,7 +100,7 @@ public void testAccountManagementLinkIdentity() { // Link identity provider through Admin REST api Response response = AccountHelper.addIdentityProvider(adminClient.realm(bc.consumerRealmName()), "consumer", adminClient.realm(bc.providerRealmName()), bc.getUserLogin(), bc.getIDPAlias()); - Assert.assertEquals("status", 204, response.getStatus()); + Assertions.assertEquals(204, response.getStatus(), "status"); // Assert identity is linked through Admin REST api assertTrue(AccountHelper.isIdentityProviderLinked(adminClient.realm(bc.consumerRealmName()), "consumer", bc.getIDPAlias())); @@ -119,7 +119,7 @@ public void testAccountManagementLinkIdentity() { AccountHelper.logout(adminClient.realm(bc.providerRealmName()), "testuser"); // Assert I am not logged immediately into app page and first-broker-login appears instead - Assert.assertFalse(testAppHelper.login(bc.getUserLogin(), bc.getUserPassword(), bc.consumerRealmName(), "broker-app", bc.getIDPAlias())); + Assertions.assertFalse(testAppHelper.login(bc.getUserLogin(), bc.getUserPassword(), bc.consumerRealmName(), "broker-app", bc.getIDPAlias())); waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); @@ -142,7 +142,7 @@ public void testAccountManagementLinkIdentity() { AccountHelper.logout(adminClient.realm(bc.providerRealmName()), "testuser"); //Try to log in. Previous link is not valid anymore, so now it should try to register new user instead of logging into app page - Assert.assertFalse(testAppHelper.login(bc.getUserLogin(), bc.getUserPassword(), bc.consumerRealmName(), "broker-app", bc.getIDPAlias())); + Assertions.assertFalse(testAppHelper.login(bc.getUserLogin(), bc.getUserPassword(), bc.consumerRealmName(), "broker-app", bc.getIDPAlias())); waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); } @@ -158,10 +158,10 @@ public void testAccountManagementLinkedIdentityAlreadyExists() { // Link identity provider through Admin REST api Response response = AccountHelper.addIdentityProvider(adminClient.realm(bc.consumerRealmName()), "consumer", adminClient.realm(bc.providerRealmName()), bc.getUserLogin(), bc.getIDPAlias()); - Assert.assertEquals("status", 204, response.getStatus()); + Assertions.assertEquals(204, response.getStatus(), "status"); // Test we will log in immediately into app page - Assert.assertTrue(testAppHelper.login(bc.getUserLogin(), bc.getUserPassword(), bc.consumerRealmName(), "broker-app", bc.getIDPAlias())); + Assertions.assertTrue(testAppHelper.login(bc.getUserLogin(), bc.getUserPassword(), bc.consumerRealmName(), "broker-app", bc.getIDPAlias())); } // KEYCLOAK-3267 @@ -173,7 +173,7 @@ public void loginWithExistingUserWithBruteForceEnabled() { loginWithExistingUser(); - Assert.assertTrue(AccountHelper.updatePassword(adminClient.realm(bc.consumerRealmName()), bc.getUserLogin(), "password")); + Assertions.assertTrue(AccountHelper.updatePassword(adminClient.realm(bc.consumerRealmName()), bc.getUserLogin(), "password")); logoutFromConsumerRealm(); AccountHelper.logout(adminClient.realm(bc.providerRealmName()), bc.getUserLogin()); @@ -186,14 +186,14 @@ public void loginWithExistingUserWithBruteForceEnabled() { } catch (TimeoutException e) { log.debug(driver.getTitle()); log.debug(driver.getPageSource()); - Assert.fail("Timeout while waiting for login page"); + Assertions.fail("Timeout while waiting for login page"); } for (int i = 0; i < 3; i++) { try { waitForElementEnabled(driver, "login"); } catch (TimeoutException e) { - Assert.fail("Timeout while waiting for login element enabled"); + Assertions.fail("Timeout while waiting for login element enabled"); } loginPage.login(bc.getUserLogin(), "invalid"); @@ -208,10 +208,10 @@ public void loginWithExistingUserWithBruteForceEnabled() { } catch (TimeoutException e) { log.debug(driver.getTitle()); log.debug(driver.getPageSource()); - Assert.fail("Timeout while waiting for login page"); + Assertions.fail("Timeout while waiting for login page"); } - Assert.assertTrue("Driver should be on the provider realm page right now", driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), "Driver should be on the provider realm page right now"); loginPage.login(bc.getUserLogin(), bc.getUserPassword()); @@ -417,7 +417,7 @@ public void testExpiredCode() { waitForPage(driver, "sorry", false); errorPage.assertCurrent(); String link = errorPage.getBackToApplicationLink(); - Assert.assertTrue(link.contains("/auth/realms/" + bc.consumerRealmName() + "/app")); + Assertions.assertTrue(link.contains("/auth/realms/" + bc.consumerRealmName() + "/app")); } /** @@ -530,7 +530,7 @@ public void testWithLinkedFederationProvider() { // Updating password and the rest of the test is irrelevant for transient sessions return; } - Assert.assertTrue(AccountHelper.updatePassword(adminClient.realm(bc.consumerRealmName()), "test-user", "new-password")); + Assertions.assertTrue(AccountHelper.updatePassword(adminClient.realm(bc.consumerRealmName()), "test-user", "new-password")); AccountHelper.logout(adminClient.realm(bc.consumerRealmName()), "test-user"); AccountHelper.logout(adminClient.realm(bc.providerRealmName()), "test-user"); @@ -544,7 +544,7 @@ public void testWithLinkedFederationProvider() { loginPage.login("test-user-noemail", "password"); - Assert.assertTrue(AccountHelper.updatePassword(adminClient.realm(bc.consumerRealmName()), "test-user-noemail", "new-password")); + Assertions.assertTrue(AccountHelper.updatePassword(adminClient.realm(bc.consumerRealmName()), "test-user-noemail", "new-password")); } finally { removeUserByUsername(adminClient.realm(bc.consumerRealmName()), "test-user"); removeUserByUsername(adminClient.realm(bc.consumerRealmName()), "test-user-noemail"); @@ -575,7 +575,7 @@ public void testDisabledBroker() { oauth.openLoginForm(); loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), "Driver should be on the provider realm page right now"); idpRep.setEnabled(false); identityProviderResource.update(idpRep); loginPage.login(bc.getUserLogin(), bc.getUserPassword()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractBaseBrokerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractBaseBrokerTest.java index dda4ebeab8d3..74465bcca075 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractBaseBrokerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractBaseBrokerTest.java @@ -35,7 +35,6 @@ import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.services.resources.RealmsResource; import org.keycloak.testsuite.AbstractKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.pages.AppPage; import org.keycloak.testsuite.pages.ErrorPage; import org.keycloak.testsuite.pages.IdpConfirmLinkPage; @@ -64,6 +63,7 @@ import org.jboss.arquillian.graphene.page.Page; import org.junit.After; import org.junit.Before; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.TimeoutException; @@ -78,7 +78,7 @@ import static org.keycloak.testsuite.util.ServerURLs.removeDefaultPorts; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * No test methods there. Just some useful common functionality @@ -245,7 +245,7 @@ protected void logInAsUserInIDPWithReAuthenticate() { // We are re-authenticating. Username field not visible log.debug("Reauthenticating"); - Assert.assertFalse(loginPage.isUsernameInputPresent()); + Assertions.assertFalse(loginPage.isUsernameInputPresent()); loginPage.login(bc.getUserPassword()); } @@ -295,9 +295,9 @@ protected void logInAsUserInIDPForFirstTimeAndAssertSuccess() { protected void updateAccountInformation() { waitForPage(driver, "update account information", false); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); @@ -423,7 +423,7 @@ protected void assertLoginPage(String realm) { } catch (TimeoutException e) { log.debug(driver.getTitle()); log.debug(driver.getPageSource()); - Assert.fail("Timeout while waiting for login page"); + Assertions.fail("Timeout while waiting for login page"); } } @@ -434,7 +434,7 @@ protected void waitForAccountManagementTitle() { protected void assertErrorPage(String expectedError) { errorPage.assertCurrent(); - Assert.assertEquals(expectedError, errorPage.getError()); + Assertions.assertEquals(expectedError, errorPage.getError()); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractBrokerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractBrokerTest.java index 9599c09eb6e1..2f2091cdd2e2 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractBrokerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractBrokerTest.java @@ -22,12 +22,12 @@ import org.keycloak.representations.idm.RoleRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.representations.idm.UserSessionRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.pages.ConsentPage; import org.keycloak.testsuite.util.AccountHelper; import org.jboss.arquillian.graphene.page.Page; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.models.utils.DefaultAuthenticationFlows.IDP_REVIEW_PROFILE_CONFIG_ALIAS; import static org.keycloak.testsuite.broker.BrokerTestTools.getConsumerRoot; @@ -37,9 +37,9 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Contains just few basic tests. This is good class to override if you're testing custom IDP configuration and you need @@ -71,8 +71,8 @@ protected void loginUser() { waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); @@ -93,14 +93,14 @@ protected void loginUser() { UsersResource consumerUsers = adminClient.realm(bc.consumerRealmName()).users(); int userCount = consumerUsers.count(); - Assert.assertTrue("There must be at least one user", userCount > 0); + Assertions.assertTrue(userCount > 0, "There must be at least one user"); } boolean isUserFound = getConsumerUserRepresentations() .anyMatch(user -> user.getUsername().equals(bc.getUserLogin()) && user.getEmail().equals(bc.getUserEmail())); - Assert.assertTrue("There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName(), - isUserFound); + Assertions.assertTrue(isUserFound, + "There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName()); } protected boolean isUsingTransientSessions() { @@ -120,9 +120,9 @@ protected UserRepresentation getConsumerUserRepresentation(String userName) { .filter(userRep -> userName.equals(userRep.getUsername())) .iterator(); - assertTrue("At least one user expected with username " + userName, it.hasNext()); + assertTrue(it.hasNext(), "At least one user expected with username " + userName); UserRepresentation res = it.next(); - assertFalse("At most one user expected with username " + userName, it.hasNext()); + assertFalse(it.hasNext(), "At most one user expected with username " + userName); return res; } @@ -172,15 +172,15 @@ protected void testSingleLogout() { oauth.client("broker-app", "secret"); oauth.openLoginForm(); - Assert.assertTrue("Should be logged in", driver.getTitle().endsWith("AUTH_RESPONSE")); + Assertions.assertTrue(driver.getTitle().endsWith("AUTH_RESPONSE"), "Should be logged in"); logoutFromConsumerRealm(); AccountHelper.logout(adminClient.realm(bc.providerRealmName()), bc.getUserLogin()); loginPage.open(bc.consumerRealmName()); - Assert.assertTrue("Should be on " + bc.consumerRealmName() + " realm on login page", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/protocol/openid-connect/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/protocol/openid-connect/"), + "Should be on " + bc.consumerRealmName() + " realm on login page"); } protected void logoutFromConsumerRealm() { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractDefaultIdpTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractDefaultIdpTest.java index 0f422ea3d0ee..e22e4f6e86c1 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractDefaultIdpTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractDefaultIdpTest.java @@ -29,20 +29,20 @@ import org.keycloak.models.AuthenticationExecutionModel; import org.keycloak.models.AuthenticatorConfigModel; import org.keycloak.representations.idm.ClientRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.FlowUtil; import org.keycloak.testsuite.util.UIUtils; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test for scenarios where "Identity Provider Authenticator" is set with "default identity provider" directly redirecting to provider realm @@ -55,7 +55,7 @@ public void beforeBrokerTest() { // Require broker to show consent screen RealmResource brokeredRealm = adminClient.realm(bc.providerRealmName()); List clients = brokeredRealm.clients().findByClientId(bc.getIDPClientIdInProviderRealm()); - org.junit.Assert.assertEquals(1, clients.size()); + Assertions.assertEquals(1, clients.size()); ClientRepresentation brokerApp = clients.get(0); brokerApp.setConsentRequired(true); brokeredRealm.clients().get(brokerApp.getId()).update(brokerApp); @@ -72,8 +72,8 @@ public void testDefaultIdpNotSet() { waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the initial page and nothing should have happened", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "Driver should be on the initial page and nothing should have happened"); } @Test @@ -91,8 +91,8 @@ public void testDefaultIdpSet() { waitForPage(driver, "sign in to", true); // Make sure we got redirected to the remote IdP automatically - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); } protected void testDefaultIdpSetTriedAndReturnedError(String expectedErrorMessageOnLoginScreen) { @@ -110,8 +110,8 @@ protected void testDefaultIdpSetTriedAndReturnedError(String expectedErrorMessag waitForPage(driver, "sign in to", true); // Make sure we got redirected to the remote IdP automatically - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); // Attempt login log.debug("Logging in"); @@ -130,7 +130,7 @@ protected void testDefaultIdpSetTriedAndReturnedError(String expectedErrorMessag errorElement = driver.findElement(By.className("alert-error")); } - assertNotNull("Page should show an error message but it's missing", errorElement); + assertNotNull(errorElement, "Page should show an error message but it's missing"); // Login to IDP failed due consent denied. Error message is displayed on the username/password screen of the consumer realm assertEquals(expectedErrorMessageOnLoginScreen, UIUtils.getTextFromElement(errorElement)); @@ -150,10 +150,10 @@ protected void testLoginHintForwarded() { waitForPage(driver, "sign in to", true); // Make sure we got redirected to the remote IdP (provider) automatically - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); - Assert.assertTrue("Provider page should contain login_hint parameter", - driver.getCurrentUrl().contains("login_hint=" + urlEncodedUsername)); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); + Assertions.assertTrue(driver.getCurrentUrl().contains("login_hint=" + urlEncodedUsername), + "Provider page should contain login_hint parameter"); } protected void configureFlow(String defaultIdpValue) { @@ -179,7 +179,7 @@ protected void configureFlow(String defaultIdpValue) { .findFirst() .orElse(-1); - assertTrue("Identity Provider Redirector execution not found", index >= 0); + assertTrue(index >= 0, "Identity Provider Redirector execution not found"); FlowUtil.inCurrentRealm(session) .selectFlow(newFlowAlias) diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractFirstBrokerLoginTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractFirstBrokerLoginTest.java index c1124476e1e9..5bc73730a601 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractFirstBrokerLoginTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractFirstBrokerLoginTest.java @@ -26,7 +26,6 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.storage.UserStorageProvider; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.federation.UserMapStorageFactory; @@ -44,6 +43,7 @@ import org.jboss.arquillian.drone.api.annotation.Drone; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; @@ -63,9 +63,9 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test of various scenarios related to first broker login. @@ -95,9 +95,9 @@ public void testErrorExistingUserWithUpdateProfile() { logInWithBroker(bc); waitForPage(driver, "update account information", false); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); updateAccountInformationPage.updateAccountInformation("consumer", "consumer-user@redhat.com", "FirstName", "LastName"); @@ -129,18 +129,18 @@ public void testLinkAccountByReauthenticationWithPassword() { try { this.loginPage.findSocialButton(bc.getIDPAlias()); - Assert.fail("Not expected to see social button with " + bc.getIDPAlias()); + Assertions.fail("Not expected to see social button with " + bc.getIDPAlias()); } catch (NoSuchElementException expected) { } try { this.loginPage.clickRegister(); - Assert.fail("Not expected to see register link"); + Assertions.fail("Not expected to see register link"); } catch (NoSuchElementException expected) { } loginPage.login("password"); - Assert.assertTrue(appPage.isCurrent()); + Assertions.assertTrue(appPage.isCurrent()); assertNumFederatedIdentities(existingUser, 1); } @@ -168,18 +168,18 @@ public void testLinkAccountByReauthenticationWithUsernameAndPassword() { try { this.loginPage.findSocialButton(bc.getIDPAlias()); - Assert.fail("Not expected to see social button with " + bc.getIDPAlias()); + Assertions.fail("Not expected to see social button with " + bc.getIDPAlias()); } catch (NoSuchElementException expected) { } try { this.loginPage.clickRegister(); - Assert.fail("Not expected to see register link"); + Assertions.fail("Not expected to see register link"); } catch (NoSuchElementException expected) { } loginPage.login("foobar", "password"); - Assert.assertTrue(appPage.isCurrent()); + Assertions.assertTrue(appPage.isCurrent()); assertNumFederatedIdentities(existingUser, 0); assertNumFederatedIdentities(anotherUser, 1); @@ -203,18 +203,18 @@ public void testLinkAccountByReauthenticationNoExistingUser() { try { this.loginPage.findSocialButton(bc.getIDPAlias()); - Assert.fail("Not expected to see social button with " + bc.getIDPAlias()); + Assertions.fail("Not expected to see social button with " + bc.getIDPAlias()); } catch (NoSuchElementException expected) { } try { this.loginPage.clickRegister(); - Assert.fail("Not expected to see register link"); + Assertions.fail("Not expected to see register link"); } catch (NoSuchElementException expected) { } loginPage.login("consumer", "password"); - Assert.assertTrue(appPage.isCurrent()); + Assertions.assertTrue(appPage.isCurrent()); assertNumFederatedIdentities(existingUser, 1); } @@ -237,18 +237,18 @@ public void testLinkAccountByReauthenticationWithWrongPassword() { try { this.loginPage.findSocialButton(bc.getIDPAlias()); - Assert.fail("Not expected to see social button with " + bc.getIDPAlias()); + Assertions.fail("Not expected to see social button with " + bc.getIDPAlias()); } catch (NoSuchElementException expected) { } try { this.loginPage.clickRegister(); - Assert.fail("Not expected to see register link"); + Assertions.fail("Not expected to see register link"); } catch (NoSuchElementException expected) { } loginPage.login("consumer", "wrongpassword"); - Assert.assertTrue(loginPage.isCurrent(bc.consumerRealmName())); + Assertions.assertTrue(loginPage.isCurrent(bc.consumerRealmName())); assertNumFederatedIdentities(existingUser, 0); @@ -256,7 +256,7 @@ public void testLinkAccountByReauthenticationWithWrongPassword() { try { this.loginPage.clickRegister(); - Assert.fail("Not expected to see register link"); + Assertions.fail("Not expected to see register link"); } catch (NoSuchElementException expected) { } } finally { @@ -286,13 +286,13 @@ public void testLinkAccountByReauthenticationResetPassword() { try { this.loginPage.findSocialButton(bc.getIDPAlias()); - Assert.fail("Not expected to see social button with " + bc.getIDPAlias()); + Assertions.fail("Not expected to see social button with " + bc.getIDPAlias()); } catch (NoSuchElementException expected) { } try { this.loginPage.clickRegister(); - Assert.fail("Not expected to see register link"); + Assertions.fail("Not expected to see register link"); } catch (NoSuchElementException expected) { } @@ -319,13 +319,13 @@ public void testLinkAccountByReauthenticationResetPasswordNoExistingUser() { try { this.loginPage.findSocialButton(bc.getIDPAlias()); - Assert.fail("Not expected to see social button with " + bc.getIDPAlias()); + Assertions.fail("Not expected to see social button with " + bc.getIDPAlias()); } catch (NoSuchElementException expected) { } try { this.loginPage.clickRegister(); - Assert.fail("Not expected to see register link"); + Assertions.fail("Not expected to see register link"); } catch (NoSuchElementException expected) { } @@ -356,8 +356,8 @@ public void testLinkAccountByLogInAsUserUsingBrowserButtons() { log.debug("Clicking social " + bc.getIDPAlias()); loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); log.debug("Logging in"); // we need to force a login failure in order to be able to use back button to go back to login page at the provider @@ -396,7 +396,7 @@ public void testLinkAccountByLogInAsUserUsingBrowserButtons() { try { loginPage.findSocialButton(bc.getIDPAlias()); - Assert.fail("Not expected to see social button with " + bc.getIDPAlias()); + Assertions.fail("Not expected to see social button with " + bc.getIDPAlias()); } catch (NoSuchElementException expected) { } @@ -430,8 +430,8 @@ public void testUpdateEmailReviewProfileLinkingAccount() { log.debug("Clicking social " + bc.getIDPAlias()); loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); log.debug("Logging in"); loginPage.login(bc.getUserLogin(), bc.getUserPassword()); @@ -504,7 +504,7 @@ public void testLinkAccountByLogInAsUserAfterResettingPassword() throws Interrup this.passwordUpdatePage.assertCurrent(); this.passwordUpdatePage.changePassword("password", "password"); - Assert.assertTrue(appPage.isCurrent()); + Assertions.assertTrue(appPage.isCurrent()); assertNumFederatedIdentities(existingUser, 1); } @@ -539,13 +539,13 @@ public void testResetPasswordDuringFirstBrokerFlowWithoutExistingUserAuthenticat try { this.loginPage.findSocialButton(bc.getIDPAlias()); - Assert.fail("Not expected to see social button with " + bc.getIDPAlias()); + Assertions.fail("Not expected to see social button with " + bc.getIDPAlias()); } catch (NoSuchElementException expected) { } try { this.loginPage.clickRegister(); - Assert.fail("Not expected to see register link"); + Assertions.fail("Not expected to see register link"); } catch (NoSuchElementException expected) { } @@ -566,7 +566,7 @@ public void testResetPasswordDuringFirstBrokerFlowWithoutExistingUserAuthenticat this.passwordUpdatePage.assertCurrent(); this.passwordUpdatePage.changePassword("password", "password"); - Assert.assertTrue(appPage.isCurrent()); + Assertions.assertTrue(appPage.isCurrent()); assertNumFederatedIdentities(existingUser, 1); } @@ -679,9 +679,9 @@ public void testUserExistsFirstBrokerLoginFlowUpdateProfileOn() { logInWithBroker(bc); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); updateAccountInformationPage.updateAccountInformation("consumer", "consumer-user@redhat.com", "FirstName", "LastName"); @@ -703,9 +703,9 @@ public void testRequiredUpdatedPassword() { logInWithBroker(bc); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); updateAccountInformationPage.updateAccountInformation("FirstName", "LastName"); @@ -713,7 +713,7 @@ public void testRequiredUpdatedPassword() { waitForPage(driver, "update password", false); updatePasswordPage.updatePasswords("password", "password"); - Assert.assertTrue(appPage.isCurrent()); + Assertions.assertTrue(appPage.isCurrent()); } @@ -736,7 +736,7 @@ public void testFixDuplicationsByReviewProfile() { logInWithBroker(bc); waitForPage(driver, "update account information", false); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); updateAccountInformationPage.updateAccountInformation("FirstName", "LastName"); waitForPage(driver, "account already exists", false); @@ -745,7 +745,7 @@ public void testFixDuplicationsByReviewProfile() { idpConfirmLinkPage.clickReviewProfile(); waitForPage(driver, "update account information", false); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); updateAccountInformationPage.updateAccountInformation("consumer", "test@localhost.com", "FirstName", "LastName"); waitForPage(driver, "account already exists", false); @@ -754,14 +754,14 @@ public void testFixDuplicationsByReviewProfile() { idpConfirmLinkPage.clickReviewProfile(); waitForPage(driver, "update account information", false); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); updateAccountInformationPage.updateAccountInformation("test", "test@localhost.com", "FirstName", "LastName"); UserRepresentation userRepresentation = AccountHelper.getUserRepresentation(adminClient.realm(bc.consumerRealmName()), "test"); - Assert.assertEquals("FirstName", userRepresentation.getFirstName()); - Assert.assertEquals("LastName", userRepresentation.getLastName()); - Assert.assertEquals("test@localhost.com", userRepresentation.getEmail()); + Assertions.assertEquals("FirstName", userRepresentation.getFirstName()); + Assertions.assertEquals("LastName", userRepresentation.getLastName()); + Assertions.assertEquals("test@localhost.com", userRepresentation.getEmail()); } @@ -820,14 +820,14 @@ public void testRequiredRegistrationEmailAsUserName() { logInWithBroker(bc); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); try { updateAccountInformationPage.updateAccountInformation("test", "test@redhat.com", "FirstName", "LastName"); - Assert.fail("It is not expected to see username field"); + Assertions.fail("It is not expected to see username field"); } catch (NoSuchElementException ignore) { } @@ -854,9 +854,9 @@ public void testLinkAccountWithEmailVerified() { logInWithBroker(bc); waitForPage(driver, "update account information", false); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); updateAccountInformationPage.updateAccountInformation("Firstname", "Lastname"); @@ -899,9 +899,9 @@ public void testLinkAccountModifyingEmailLinkingByEmailNotAllowed() { logInWithBroker(bc); waitForPage(driver, "update account information", false); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); // update the email to the correct one log.debug("Updating info on updateAccount page"); @@ -915,7 +915,7 @@ public void testLinkAccountModifyingEmailLinkingByEmailNotAllowed() { assertEquals("Authenticate to link your account with " + bc.getIDPAlias(), loginPage.getInfoMessage()); loginPage.login("password"); - Assert.assertTrue(appPage.isCurrent()); + Assertions.assertTrue(appPage.isCurrent()); assertNumFederatedIdentities(linkedUserId, 1); } @@ -929,7 +929,7 @@ public void testLinkAccountReviewDisabled() throws Exception { .filter(execution -> IdpReviewProfileAuthenticatorFactory.PROVIDER_ID.equals(execution.getProviderId())) .findAny() .orElse(null); - Assert.assertNotNull("IdpReviewProfileAuthenticator execution not found", idpReviewProfileExec); + Assertions.assertNotNull(idpReviewProfileExec, "IdpReviewProfileAuthenticator execution not found"); idpReviewProfileExec.setRequirement(AuthenticationExecutionModel.Requirement.DISABLED.name()); consumerRealm.flows().updateExecutions("first broker login", idpReviewProfileExec); @@ -944,16 +944,16 @@ public void testLinkAccountReviewDisabled() throws Exception { // no review displayed and button in link not available waitForPage(driver, "account already exists", false); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); - Assert.assertFalse("Review Profile button is displayed", idpConfirmLinkPage.isReviewProfileDisplayed()); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); + Assertions.assertFalse(idpConfirmLinkPage.isReviewProfileDisplayed(), "Review Profile button is displayed"); idpConfirmLinkPage.clickLinkAccount(); //linking the account using password as email not configured assertEquals("Authenticate to link your account with " + bc.getIDPAlias(), loginPage.getInfoMessage()); loginPage.login("password"); - Assert.assertTrue(appPage.isCurrent()); + Assertions.assertTrue(appPage.isCurrent()); assertNumFederatedIdentities(linkedUserId, 1); } @@ -1017,8 +1017,8 @@ public void testSuccessfulAuthenticationWithoutUpdateProfile_emailNotProvided_em log.debug("Clicking social " + bc.getIDPAlias()); loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); log.debug("Logging in"); loginPage.login("no-email", "password"); @@ -1126,7 +1126,7 @@ public void testLinkAccountByEmailVerificationTwice() { //link account by email waitForPage(driver, "update account information", false); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); updateAccountInformationPage.updateAccountInformation("FirstName", "LastName"); waitForPage(driver, "account already exists", false); assertTrue(idpConfirmLinkPage.isCurrent()); @@ -1171,7 +1171,7 @@ public void testLinkAccountByEmailVerificationInAnotherBrowser() { //link account by email waitForPage(driver, "update account information", false); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); updateAccountInformationPage.updateAccountInformation("FirstName", "LastName"); waitForPage(driver, "account already exists", false); assertTrue(idpConfirmLinkPage.isCurrent()); @@ -1260,7 +1260,7 @@ public void testLinkAccountByEmailVerificationResendEmail() { //link account by email waitForPage(driver, "update account information", false); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); updateAccountInformationPage.updateAccountInformation("FirstName", "LastName"); waitForPage(driver, "account already exists", false); assertTrue(idpConfirmLinkPage.isCurrent()); @@ -1290,9 +1290,9 @@ public void testVerifyEmailInNewBrowserWithPreserveClient() { waitForPage(driver, "update account information", false); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); updateAccountInformationPage.updateAccountInformation("Firstname", "Lastname"); @@ -1335,8 +1335,8 @@ public void testEventsOnUpdateProfileNoEmailChange() { log.debug("Clicking social " + bc.getIDPAlias()); loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); log.debug("Logging in"); loginPage.login("no-first-name", "password"); @@ -1347,9 +1347,9 @@ public void testEventsOnUpdateProfileNoEmailChange() { UserRepresentation userRepresentation = AccountHelper.getUserRepresentation(adminClient.realm(bc.consumerRealmName()), "no-first-name"); - Assert.assertEquals("FirstName", userRepresentation.getFirstName()); - Assert.assertEquals("LastName", userRepresentation.getLastName()); - Assert.assertEquals("no-first-name@localhost.com", userRepresentation.getEmail()); + Assertions.assertEquals("FirstName", userRepresentation.getFirstName()); + Assertions.assertEquals("LastName", userRepresentation.getLastName()); + Assertions.assertEquals("no-first-name@localhost.com", userRepresentation.getEmail()); RealmRepresentation consumerRealmRep = adminClient.realm(bc.consumerRealmName()).toRepresentation(); @@ -1389,8 +1389,8 @@ public void testEventsOnUpdateProfileWithEmailChange() { log.debug("Clicking social " + bc.getIDPAlias()); loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); log.debug("Logging in"); loginPage.login("no-first-name", "password"); @@ -1401,10 +1401,10 @@ public void testEventsOnUpdateProfileWithEmailChange() { UserRepresentation userRepresentation = AccountHelper.getUserRepresentation(adminClient.realm(bc.consumerRealmName()), "no-first-name"); - Assert.assertEquals("FirstName", userRepresentation.getFirstName()); - Assert.assertEquals("LastName", userRepresentation.getLastName()); - Assert.assertEquals("new-email@localhost.com", userRepresentation.getEmail()); - Assert.assertEquals("no-first-name", userRepresentation.getUsername()); + Assertions.assertEquals("FirstName", userRepresentation.getFirstName()); + Assertions.assertEquals("LastName", userRepresentation.getLastName()); + Assertions.assertEquals("new-email@localhost.com", userRepresentation.getEmail()); + Assertions.assertEquals("no-first-name", userRepresentation.getUsername()); RealmRepresentation consumerRealmRep = adminClient.realm(bc.consumerRealmName()).toRepresentation(); @@ -1464,8 +1464,8 @@ public void testUpdateProfileIfMissingInformation() { log.debug("Clicking social " + bc.getIDPAlias()); loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); log.debug("Logging in"); loginPage.login("no-first-name", "password"); @@ -1476,9 +1476,9 @@ public void testUpdateProfileIfMissingInformation() { UserRepresentation userRepresentation = AccountHelper.getUserRepresentation(adminClient.realm(bc.consumerRealmName()), "no-first-name"); - Assert.assertEquals("FirstName", userRepresentation.getFirstName()); - Assert.assertEquals("LastName", userRepresentation.getLastName()); - Assert.assertEquals("no-first-name@localhost.com", userRepresentation.getEmail()); + Assertions.assertEquals("FirstName", userRepresentation.getFirstName()); + Assertions.assertEquals("LastName", userRepresentation.getLastName()); + Assertions.assertEquals("no-first-name@localhost.com", userRepresentation.getEmail()); AccountHelper.logout(adminClient.realm(bc.providerRealmName()), "no-first-name"); AccountHelper.logout(adminClient.realm(bc.consumerRealmName()), "no-first-name"); @@ -1490,8 +1490,8 @@ public void testUpdateProfileIfMissingInformation() { log.debug("Clicking social " + bc.getIDPAlias()); loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); log.debug("Logging in"); loginPage.login("no-last-name", "password"); @@ -1501,9 +1501,9 @@ public void testUpdateProfileIfMissingInformation() { userRepresentation = AccountHelper.getUserRepresentation(adminClient.realm(bc.consumerRealmName()), "no-last-name"); - Assert.assertEquals("FirstName", userRepresentation.getFirstName()); - Assert.assertEquals("LastName", userRepresentation.getLastName()); - Assert.assertEquals("no-last-name@localhost.com", userRepresentation.getEmail()); + Assertions.assertEquals("FirstName", userRepresentation.getFirstName()); + Assertions.assertEquals("LastName", userRepresentation.getLastName()); + Assertions.assertEquals("no-last-name@localhost.com", userRepresentation.getEmail()); AccountHelper.logout(adminClient.realm(bc.providerRealmName()), "no-last-name"); AccountHelper.logout(adminClient.realm(bc.consumerRealmName()), "no-last-name"); @@ -1516,8 +1516,8 @@ public void testUpdateProfileIfMissingInformation() { log.debug("Clicking social " + bc.getIDPAlias()); loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); log.debug("Logging in"); loginPage.login("no-email", "password"); @@ -1527,9 +1527,9 @@ public void testUpdateProfileIfMissingInformation() { userRepresentation = AccountHelper.getUserRepresentation(adminClient.realm(bc.consumerRealmName()), "no-email"); - Assert.assertEquals("FirstName", userRepresentation.getFirstName()); - Assert.assertEquals("LastName", userRepresentation.getLastName()); - Assert.assertEquals("no-email@localhost.com", userRepresentation.getEmail()); + Assertions.assertEquals("FirstName", userRepresentation.getFirstName()); + Assertions.assertEquals("LastName", userRepresentation.getLastName()); + Assertions.assertEquals("no-email@localhost.com", userRepresentation.getEmail()); } /** @@ -1546,16 +1546,16 @@ public void testUpdateProfileIfNotMissingInformation() { log.debug("Clicking social " + bc.getIDPAlias()); loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); log.debug("Logging in"); loginPage.login("all-info-set", "password"); UserRepresentation userRepresentation = AccountHelper.getUserRepresentation(adminClient.realm(bc.providerRealmName()), "all-info-set"); - Assert.assertEquals("FirstName", userRepresentation.getFirstName()); - Assert.assertEquals("LastName", userRepresentation.getLastName()); - Assert.assertEquals("all-info-set@localhost.com", userRepresentation.getEmail()); + Assertions.assertEquals("FirstName", userRepresentation.getFirstName()); + Assertions.assertEquals("LastName", userRepresentation.getLastName()); + Assertions.assertEquals("all-info-set@localhost.com", userRepresentation.getEmail()); } @@ -1573,9 +1573,9 @@ public void testWithoutUpdateProfile() { UserRepresentation userRepresentation = AccountHelper.getUserRepresentation(adminClient.realm(bc.consumerRealmName()), bc.getUserLogin()); - Assert.assertNull(userRepresentation.getFirstName()); - Assert.assertNull(userRepresentation.getLastName()); - Assert.assertEquals(bc.getUserEmail(), userRepresentation.getEmail()); + Assertions.assertNull(userRepresentation.getFirstName()); + Assertions.assertNull(userRepresentation.getLastName()); + Assertions.assertEquals(bc.getUserEmail(), userRepresentation.getEmail()); } @@ -1652,7 +1652,7 @@ public void testConfirmOverrideLink() { try (Response response = consumerRealm.users().get(createdUser) .addFederatedIdentity(bc.getIDPAlias(), identity)) { - assertEquals("status", 204, response.getStatus()); + assertEquals(204, response.getStatus(), "status"); } // login with the same username user but different user id from provider diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractKcSamlMetadataBrokerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractKcSamlMetadataBrokerTest.java index 4c5cdce6cd33..2980cfe8d462 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractKcSamlMetadataBrokerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractKcSamlMetadataBrokerTest.java @@ -39,7 +39,7 @@ import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -94,7 +94,7 @@ protected void doSamlPostLogin(int statusCode, String expectedString, SamlDocume .build() // first-broker flow: if valid request, it displays an update profile page on consumer realm .execute(currentResponse -> { - Assert.assertEquals(statusCode, currentResponse.getStatusLine().getStatusCode()); + Assertions.assertEquals(statusCode, currentResponse.getStatusLine().getStatusCode()); if (expectedString != null) { MatcherAssert.assertThat(currentResponse, bodyHC(Matchers.containsString(expectedString))); } @@ -119,7 +119,7 @@ protected void doSamlRedirectLogin(int statusCode, String expectedString) throws .build() // first-broker flow: if valid request, it displays an update profile page on consumer realm .execute(currentResponse -> { - Assert.assertEquals(statusCode, currentResponse.getStatusLine().getStatusCode()); + Assertions.assertEquals(statusCode, currentResponse.getStatusLine().getStatusCode()); MatcherAssert.assertThat(currentResponse, bodyHC(Matchers.containsString(expectedString))); }); } @@ -144,17 +144,17 @@ protected void rotateKeys(String realmName, String algorithm, String providerId) String realmId = realm.toRepresentation().getId(); ComponentRepresentation keys = createComponentRep(algorithm, providerId, realmId); try (Response response = realm.components().add(keys)) { - Assert.assertEquals(201, response.getStatus()); + Assertions.assertEquals(201, response.getStatus()); } String updatedActiveKid = realm.keys().getKeyMetadata().getActive().get(algorithm); - Assert.assertNotEquals(activeKid, updatedActiveKid); + Assertions.assertNotEquals(activeKid, updatedActiveKid); } protected void updateKeyProvider(String realmName, String providerId, boolean active, boolean enabled) { RealmResource realm = adminClient.realm(realmName); List components = realm.components().query(null, KeyProvider.class.getName(), providerId); - Assert.assertEquals("Key provider " + providerId + " not found.", 1, components.size()); + Assertions.assertEquals(1, components.size(), "Key provider " + providerId + " not found."); ComponentRepresentation key = components.iterator().next(); MultivaluedHashMap config = key.getConfig(); if (config == null) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractSamlLoginHintTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractSamlLoginHintTest.java index 97f04fa6733c..d2d89139fd97 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractSamlLoginHintTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractSamlLoginHintTest.java @@ -1,15 +1,15 @@ package org.keycloak.testsuite.broker; import org.keycloak.protocol.oidc.OIDCLoginProtocol; -import org.keycloak.testsuite.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test of various scenarios related to the use of login hint @@ -29,14 +29,14 @@ public void testPassLoginHintShouldSendSubjectAndPrefillUsername() { addLoginHintOnSocialButton(username); loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); log.debug("Logging in"); if (isLoginHintOptionEnabled()) { - assertEquals("Username input should contain the SAML subject", loginPage.getUsername(), username); + assertEquals(loginPage.getUsername(), username, "Username input should contain the SAML subject"); } else { - assertEquals("Username input should the SAML subject", loginPage.getUsername(), ""); + assertEquals(loginPage.getUsername(), "", "Username input should the SAML subject"); } } @@ -53,11 +53,11 @@ public void testPassEmptyLoginHintShouldNotSendSubjectAndShouldNotPrefillUsernam addLoginHintOnSocialButton(""); loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); log.debug("Logging in"); - assertEquals("Username input should not contain any username", loginPage.getUsername(), ""); + assertEquals(loginPage.getUsername(), "", "Username input should not contain any username"); } abstract boolean isLoginHintOptionEnabled(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractUsernameTemplateMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractUsernameTemplateMapperTest.java index 3508ccf3fb11..a12c1084de69 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractUsernameTemplateMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractUsernameTemplateMapperTest.java @@ -5,12 +5,12 @@ import org.keycloak.models.IdentityProviderMapperSyncMode; import org.keycloak.representations.idm.IdentityProviderRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.AccountHelper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; import static org.keycloak.testsuite.broker.KcOidcBrokerConfiguration.ATTRIBUTE_TO_MAP_NAME; @@ -86,9 +86,9 @@ protected void logInAsUserInIDPForFirstTime() { waitForPage(driver, "update account information", false); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); updateAccountInformationPage.updateAccountInformation(bc.getUserEmail(), "FirstName", "LastName"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AccountLinkTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AccountLinkTest.java index 10cbe58c0144..3a2bfea3bb26 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AccountLinkTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AccountLinkTest.java @@ -35,7 +35,6 @@ import org.keycloak.storage.StorageId; import org.keycloak.storage.UserStorageProvider; import org.keycloak.testsuite.AbstractKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.federation.PassThroughFederatedUserStorageProvider; import org.keycloak.testsuite.federation.PassThroughFederatedUserStorageProviderFactory; @@ -51,15 +50,16 @@ import org.junit.Before; import org.junit.Ignore; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.storage.UserStorageProviderModel.IMPORT_ENABLED; import static org.keycloak.testsuite.admin.AdminApiUtil.createUserAndResetPasswordWithAdminClient; import static org.keycloak.testsuite.admin.AdminApiUtil.createUserWithAdminClient; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Bill Burke @@ -204,7 +204,7 @@ public void testDeleteFederatedUserFederatedIdentityOnProviderRemoval() { userRepresentation.setEnabled(true); userRepresentation.setFederationLink(memProviderId); String userId = createUserWithAdminClient(realm, userRepresentation); - Assert.assertFalse(StorageId.isLocalStorage(userId)); + Assertions.assertFalse(StorageId.isLocalStorage(userId)); // Link identity provider and federated user FederatedIdentityRepresentation identity = FederatedIdentityBuilder.create() @@ -215,17 +215,17 @@ public void testDeleteFederatedUserFederatedIdentityOnProviderRemoval() { UserResource userResource = realm.users().get(userId); Response response = userResource.addFederatedIdentity(testIdpToDelete, identity); - Assert.assertEquals("status", 204, response.getStatus()); + Assertions.assertEquals(204, response.getStatus(), "status"); userResource = realm.users().get(userId); - Assert.assertFalse(userResource.getFederatedIdentity().isEmpty()); + Assertions.assertFalse(userResource.getFederatedIdentity().isEmpty()); // Delete the identity provider realm.identityProviders().get(testIdpToDelete).remove(); // Check that links to federated identity has been deleted userResource = realm.users().get(userId); - Assert.assertTrue(userResource.getFederatedIdentity().isEmpty()); + Assertions.assertTrue(userResource.getFederatedIdentity().isEmpty()); getTestingClient().server(CHILD_IDP).run((RunOnServer) session -> { RealmModel realm1 = session.getContext().getRealm(); @@ -251,7 +251,7 @@ protected void testAccountLink(String childUsername) { private void assertFederatedIdentity(String childUsername) { //Link the identity provider through Admin REST API Response response = AccountHelper.addIdentityProvider(adminClient.realm(CHILD_IDP), childUsername, adminClient.realm(PARENT_IDP), PARENT_USERNAME, PARENT_IDP); - Assert.assertEquals("status", 204, response.getStatus()); + Assertions.assertEquals(204, response.getStatus(), "status"); assertTrue(AccountHelper.isIdentityProviderLinked(adminClient.realm(CHILD_IDP), childUsername, PARENT_IDP)); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/BrokerRunOnServerUtil.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/BrokerRunOnServerUtil.java index 3ee1e0d48fc5..e83839f59ba2 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/BrokerRunOnServerUtil.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/BrokerRunOnServerUtil.java @@ -33,7 +33,7 @@ import org.keycloak.testsuite.runonserver.RunOnServer; import org.keycloak.testsuite.util.FlowUtil; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/BrokerWithLegacyIdTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/BrokerWithLegacyIdTest.java index f997b7ef9d1f..f7997bc3f2df 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/BrokerWithLegacyIdTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/BrokerWithLegacyIdTest.java @@ -36,7 +36,7 @@ import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_ALIAS; import static org.keycloak.testsuite.broker.oidc.LegacyIdIdentityProvider.LEGACY_ID; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vaclav Muzikar diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOIDCBrokerWithSignatureTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOIDCBrokerWithSignatureTest.java index 6a6d21c69e8c..0cd8f98332ce 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOIDCBrokerWithSignatureTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOIDCBrokerWithSignatureTest.java @@ -44,7 +44,6 @@ import org.keycloak.representations.idm.IdentityProviderRepresentation; import org.keycloak.representations.idm.KeysMetadataRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.broker.util.SimpleHttpDefault; import org.keycloak.testsuite.client.resources.TestingCacheResource; import org.keycloak.testsuite.updaters.ClientAttributeUpdater; @@ -54,13 +53,14 @@ import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.admin.AdminApiUtil.createUserWithAdminClient; import static org.keycloak.testsuite.admin.AdminApiUtil.resetUserPassword; import static org.keycloak.testsuite.broker.BrokerTestTools.getConsumerRoot; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; /** * @author Marek Posolda @@ -430,12 +430,12 @@ public void testClearKeysCache() throws Exception { IdentityProviderRepresentation idpRep = getIdentityProvider(); String expectedCacheKey = PublicKeyStorageUtils.getIdpModelCacheKey(consumerRealm().toRepresentation().getId(), idpRep.getInternalId()); TestingCacheResource cache = testingClient.testing(bc.consumerRealmName()).cache(InfinispanConnectionProvider.KEYS_CACHE_NAME); - Assert.assertTrue(cache.contains(expectedCacheKey)); + Assertions.assertTrue(cache.contains(expectedCacheKey)); // Clear cache and check nothing cached consumerRealm().clearKeysCache(); - Assert.assertFalse(cache.contains(expectedCacheKey)); - Assert.assertEquals(cache.size(), 0); + Assertions.assertFalse(cache.contains(expectedCacheKey)); + Assertions.assertEquals(cache.size(), 0); } @@ -455,7 +455,7 @@ public void testPublicKeyCacheInvalidatedWhenProviderUpdated() throws Exception IdentityProviderRepresentation idpRep = getIdentityProvider(); String expectedCacheKey = PublicKeyStorageUtils.getIdpModelCacheKey(consumerRealm().toRepresentation().getId(), idpRep.getInternalId()); TestingCacheResource cache = testingClient.testing(bc.consumerRealmName()).cache(InfinispanConnectionProvider.KEYS_CACHE_NAME); - Assert.assertTrue(cache.contains(expectedCacheKey)); + Assertions.assertTrue(cache.contains(expectedCacheKey)); // Update identityProvider to some bad JWKS_URL OIDCIdentityProviderConfigRep cfg = new OIDCIdentityProviderConfigRep(idpRep); @@ -463,7 +463,7 @@ public void testPublicKeyCacheInvalidatedWhenProviderUpdated() throws Exception updateIdentityProvider(idpRep); // Check that key is not cached anymore - Assert.assertFalse(cache.contains(expectedCacheKey)); + Assertions.assertFalse(cache.contains(expectedCacheKey)); // Check that user is not able to login with IDP setTimeOffset(20); @@ -533,7 +533,7 @@ public void testMultipleKeysWithSameKid() throws Exception { // Check that user is able to login with ES256 logInAsUserInIDPForFirstTime(); - Assert.assertTrue(appPage.isCurrent()); + Assertions.assertTrue(appPage.isCurrent()); AccountHelper.logout(adminClient.realm(bc.consumerRealmName()), bc.getUserLogin()); logInAsUserInIDP(); @@ -590,7 +590,7 @@ private void createHSKey(String algorithm, String size, String secret) { } String updatedActiveKid = providerRealm().keys().getKeyMetadata().getActive().get(algorithm); - Assert.assertNotNull(updatedActiveKid); + Assertions.assertNotNull(updatedActiveKid); } private RealmResource providerRealm() { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerAcrParameterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerAcrParameterTest.java index 7c2f360f7d11..75580e4b6372 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerAcrParameterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerAcrParameterTest.java @@ -4,7 +4,8 @@ import org.keycloak.admin.client.resource.UsersResource; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; + +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; @@ -30,11 +31,11 @@ protected void loginUser() { waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); - Assert.assertTrue(ACR_VALUES + "=" + ACR_3 + " should be part of the url", - driver.getCurrentUrl().contains(ACR_VALUES + "=" + ACR_3)); + Assertions.assertTrue(driver.getCurrentUrl().contains(ACR_VALUES + "=" + ACR_3), + ACR_VALUES + "=" + ACR_3 + " should be part of the url"); log.debug("Logging in"); loginPage.login(bc.getUserLogin(), bc.getUserPassword()); @@ -42,8 +43,8 @@ protected void loginUser() { waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); @@ -52,7 +53,7 @@ protected void loginUser() { UsersResource consumerUsers = adminClient.realm(bc.consumerRealmName()).users(); int userCount = consumerUsers.count(); - Assert.assertTrue("There must be at least one user", userCount > 0); + Assertions.assertTrue(userCount > 0, "There must be at least one user"); List users = consumerUsers.search("", 0, userCount); @@ -64,7 +65,7 @@ protected void loginUser() { } } - Assert.assertTrue("There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName(), - isUserFound); + Assertions.assertTrue(isUserFound, + "There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerEventTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerEventTest.java index bc0a802bb3b6..ccdfdd2c5bcb 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerEventTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerEventTest.java @@ -27,9 +27,9 @@ import org.keycloak.userprofile.UserProfileContext; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_ALIAS; @@ -195,16 +195,16 @@ private void loginUserAfterError() { BrokerTestTools.waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); List users = consumerRealm.users().search(bc.getUserLogin()); - Assert.assertEquals("There must be one user", 1, users.size()); + Assertions.assertEquals(1, users.size(), "There must be one user"); UserRepresentation consumerUser = users.iterator().next(); - Assert.assertEquals(bc.getUserEmail(), consumerUser.getEmail()); + Assertions.assertEquals(bc.getUserEmail(), consumerUser.getEmail()); checkFirstLoginEvents(providerRealm, consumerRealm, providerUser.getId(), consumerUser.getId()); } @@ -237,8 +237,8 @@ public void loginWithExistingUser() { loginPage.open(bc.consumerRealmName()); logInWithBroker(bc); - Assert.assertTrue(driver.getCurrentUrl().contains("/auth/realms/master/app")); - Assert.assertEquals(userCount, adminClient.realm(bc.consumerRealmName()).users().count()); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/master/app")); + Assertions.assertEquals(userCount, adminClient.realm(bc.consumerRealmName()).users().count()); checkLoginEvents(providerRealm, consumerRealm, providerUser.getId(), consumerUser.getId()); } @@ -265,8 +265,8 @@ public void loginWithExistingUserAfterError() { // now perform the login via the broker logInWithBroker(bc); - Assert.assertTrue(driver.getCurrentUrl().contains("/auth/realms/master/app")); - Assert.assertEquals(userCount, adminClient.realm(bc.consumerRealmName()).users().count()); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/master/app")); + Assertions.assertEquals(userCount, adminClient.realm(bc.consumerRealmName()).users().count()); checkLoginEvents(providerRealm, consumerRealm, providerUser.getId(), consumerUser.getId()); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerFrontendUrlTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerFrontendUrlTest.java index 7df514670691..29faa2f71914 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerFrontendUrlTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerFrontendUrlTest.java @@ -19,7 +19,7 @@ import static org.keycloak.testsuite.broker.BrokerTestConstants.REALM_CONS_NAME; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public final class KcOidcBrokerFrontendUrlTest extends AbstractBrokerTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerHiddenIdpHintTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerHiddenIdpHintTest.java index e46bb0250f6a..6f0033be708c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerHiddenIdpHintTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerHiddenIdpHintTest.java @@ -20,9 +20,9 @@ import org.keycloak.models.IdentityProviderSyncMode; import org.keycloak.representations.idm.IdentityProviderRepresentation; -import org.keycloak.testsuite.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_ALIAS; import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_PROVIDER_ID; @@ -64,14 +64,14 @@ public void testSuccessfulRedirectToProviderHiddenOnLoginPage() { String url = driver.getCurrentUrl() + "&kc_idp_hint=" + bc.getIDPAlias(); driver.navigate().to(url); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); log.debug("Logging in"); loginPage.login(bc.getUserLogin(), bc.getUserPassword()); // authenticated and redirected to app - Assert.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerIdpHintTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerIdpHintTest.java index 7959ac124e6f..f65dbbeca67c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerIdpHintTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerIdpHintTest.java @@ -20,9 +20,9 @@ import org.keycloak.admin.client.resource.RealmResource; import org.keycloak.representations.idm.ClientRepresentation; -import org.keycloak.testsuite.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; @@ -47,14 +47,14 @@ public void testSuccessfulRedirect() { String url = driver.getCurrentUrl() + "&kc_idp_hint=" + bc.getIDPAlias(); driver.navigate().to(url); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); log.debug("Logging in"); loginPage.login(bc.getUserLogin(), bc.getUserPassword()); // authenticated and redirected to app - Assert.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); } // KEYCLOAK-5260 @@ -67,22 +67,22 @@ public void testSuccessfulRedirectToProviderAfterLoginPageShown() { String urlWithHint = driver.getCurrentUrl() + "&kc_idp_hint=" + bc.getIDPAlias(); driver.navigate().to(urlWithHint); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); // do the same thing a second time driver.navigate().to(urlWithHint); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); // redirect shouldn't happen oauth.clientId("broker-app"); loginPage.open(bc.consumerRealmName()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the consumer realm page", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "Driver should be on the consumer realm page"); } @Test @@ -95,7 +95,7 @@ public void testInvalidIdentityProviderHint() { waitForPage(driver, "sign in to", true); // Still on consumer login page - Assert.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); } @Test @@ -103,7 +103,7 @@ public void testIdpHintWithErrorResponseReturnsToLoginPage() { // Configure broker client to require consent so we can test error scenario RealmResource providerRealm = adminClient.realm(bc.providerRealmName()); List clients = providerRealm.clients().findByClientId(bc.getIDPClientIdInProviderRealm()); - Assert.assertEquals(1, clients.size()); + Assertions.assertEquals(1, clients.size()); ClientRepresentation brokerClient = clients.get(0); brokerClient.setConsentRequired(true); providerRealm.clients().get(brokerClient.getId()).update(brokerClient); @@ -119,8 +119,8 @@ public void testIdpHintWithErrorResponseReturnsToLoginPage() { // Should be redirected to provider realm waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); log.debug("Logging in"); loginPage.login(bc.getUserLogin(), bc.getUserPassword()); @@ -131,11 +131,11 @@ public void testIdpHintWithErrorResponseReturnsToLoginPage() { // Should return to consumer login page (not infinite loop back to IdP) waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be back on consumer login page after denial", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "Driver should be back on consumer login page after denial"); - Assert.assertTrue("Error message should be displayed", - driver.getPageSource().contains("Access denied")); + Assertions.assertTrue(driver.getPageSource().contains("Access denied"), + "Error message should be displayed"); } finally { // Restore consent setting brokerClient.setConsentRequired(false); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerIdpLinkActionTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerIdpLinkActionTest.java index 429f8ba23764..bd4006f95bb2 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerIdpLinkActionTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerIdpLinkActionTest.java @@ -40,7 +40,6 @@ import org.keycloak.representations.idm.RoleRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.services.messages.Messages; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.pages.IdpLinkActionPage; @@ -48,11 +47,13 @@ import org.keycloak.testsuite.util.oauth.OAuthClient; import org.keycloak.utils.BrokerUtil; +import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.jboss.arquillian.graphene.page.Page; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_ALIAS; @@ -262,7 +263,7 @@ public void testAccountLinkingConsentRejectedAtIdp() throws Exception { public void testAccountLinkingDifferentUserLinked() throws Exception { // Link IDP to user "user2" Response response = AccountHelper.addIdentityProvider(adminClient.realm(bc.consumerRealmName()), "user2", adminClient.realm(bc.providerRealmName()), bc.getUserLogin(), bc.getIDPAlias()); - Assert.assertEquals(204, response.getStatus()); + Assertions.assertEquals(204, response.getStatus()); // Linking the user "user1" to same IDP should fail loginToConsumer(); @@ -278,8 +279,8 @@ public void testAccountLinkingDifferentUserLinked() throws Exception { grantPage.accept(); errorPage.assertCurrent(); - Assert.assertEquals("Federated identity returned by " + bc.getIDPAlias() + " is already linked to another user.", errorPage.getError()); - Assert.assertEquals(bc.createConsumerClients().get(0).getBaseUrl(), errorPage.getBackToApplicationLink()); + Assertions.assertEquals("Federated identity returned by " + bc.getIDPAlias() + " is already linked to another user.", errorPage.getError()); + Assertions.assertEquals(bc.createConsumerClients().get(0).getBaseUrl(), errorPage.getBackToApplicationLink()); // Check that user is not linked to the IDP assertUserLinkedToIDP(false); @@ -408,7 +409,7 @@ public void testConsumerReauthentication() throws Exception { // Link IDP to user "user1" Response response = AccountHelper.addIdentityProvider(adminClient.realm(bc.consumerRealmName()), "user1", adminClient.realm(bc.providerRealmName()), bc.getUserLogin(), bc.getIDPAlias()); - Assert.assertEquals(204, response.getStatus()); + Assertions.assertEquals(204, response.getStatus()); setTimeOffset(2); @@ -424,7 +425,7 @@ public void testConsumerReauthentication() throws Exception { // Should be redirected back to "consumer" login loginPage.assertCurrent(bc.consumerRealmName()); - Assert.assertEquals("Access denied when authenticating with kc-oidc-idp", loginPage.getError()); + Assertions.assertEquals("Access denied when authenticating with kc-oidc-idp", loginPage.getError()); assertEvents((providerRealmId, providerUserId, consumerRealmId, consumerUserId, consumerUsername) -> { // Provider login - rejected consent screen @@ -467,12 +468,12 @@ private static String getKcActionParamForLinkIdp(String providerAlias) { private void assertKcActionParams(String expectedKcAction, String expectedKcActionStatus) throws Exception { MultivaluedHashMap params = UriUtils.decodeQueryString(new URL(driver.getCurrentUrl()).getQuery()); - Assert.assertEquals(expectedKcAction, params.getFirst(Constants.KC_ACTION)); - Assert.assertEquals(expectedKcActionStatus, params.getFirst(Constants.KC_ACTION_STATUS)); + Assertions.assertEquals(expectedKcAction, params.getFirst(Constants.KC_ACTION)); + Assertions.assertEquals(expectedKcActionStatus, params.getFirst(Constants.KC_ACTION_STATUS)); } private void assertUserLinkedToIDP(boolean expectedLinked) { - Assert.assertThat(expectedLinked, is(AccountHelper.isIdentityProviderLinked(adminClient.realm(bc.consumerRealmName()), "user1", bc.getIDPAlias()))); + MatcherAssert.assertThat(expectedLinked, is(AccountHelper.isIdentityProviderLinked(adminClient.realm(bc.consumerRealmName()), "user1", bc.getIDPAlias()))); } @FunctionalInterface diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerJWETest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerJWETest.java index 2eb9d7e43f42..8c42e6bccd94 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerJWETest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerJWETest.java @@ -53,8 +53,8 @@ import static java.util.Optional.ofNullable; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** *

Tests the broker using a JWE encrypted token for id token and user info. The test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLdapReadOnlyTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLdapReadOnlyTest.java index a5eef6750805..c37b629828d0 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLdapReadOnlyTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLdapReadOnlyTest.java @@ -30,7 +30,7 @@ import static org.keycloak.models.utils.ModelToRepresentation.toRepresentationWithoutConfig; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public final class KcOidcBrokerLdapReadOnlyTest extends AbstractInitializedBaseBrokerTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLdapTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLdapTest.java index c119b71a5575..9cd111f98ea5 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLdapTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLdapTest.java @@ -31,10 +31,10 @@ import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.util.LDAPRule; -import org.junit.Assert; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; public final class KcOidcBrokerLdapTest extends AbstractInitializedBaseBrokerTest { @@ -61,7 +61,7 @@ public void testUpdateProfileOnFirstLogin() { loginPage.open(bc.consumerRealmName()); logInWithBroker(bc); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "f", "l"); - Assert.assertFalse(errorPage.isCurrent()); + Assertions.assertFalse(errorPage.isCurrent()); } private ComponentRepresentation getUserStorageConfiguration(String providerName, String providerId) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLoginHintTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLoginHintTest.java index dee6117322f5..3365fd08acca 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLoginHintTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLoginHintTest.java @@ -9,11 +9,11 @@ import org.keycloak.models.IdentityProviderSyncMode; import org.keycloak.representations.idm.IdentityProviderRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.updaters.Creator; import org.keycloak.testsuite.util.UserBuilder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_ALIAS; import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_PROVIDER_ID; @@ -22,7 +22,7 @@ import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; import static org.keycloak.testsuite.util.WaitUtils.waitForPageToLoad; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class KcOidcBrokerLoginHintTest extends AbstractBrokerTest { @@ -56,11 +56,11 @@ protected void loginUser() { waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); - Assert.assertTrue("User identifiant should be fullfilled", - loginPage.getUsername().equalsIgnoreCase(USER_EMAIL)); + Assertions.assertTrue(loginPage.getUsername().equalsIgnoreCase(USER_EMAIL), + "User identifiant should be fullfilled"); log.debug("Logging in"); loginPage.login(bc.getUserPassword()); @@ -68,8 +68,8 @@ protected void loginUser() { waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); @@ -77,7 +77,7 @@ protected void loginUser() { UsersResource consumerUsers = adminClient.realm(bc.consumerRealmName()).users(); int userCount = consumerUsers.count(); - Assert.assertTrue("There must be at least one user", userCount > 0); + Assertions.assertTrue(userCount > 0, "There must be at least one user"); List users = consumerUsers.search("", 0, userCount); @@ -89,8 +89,8 @@ protected void loginUser() { } } - Assert.assertTrue("There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName(), - isUserFound); + Assertions.assertTrue(isUserFound, + "There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName()); } @Test @@ -118,7 +118,7 @@ public void loginHintWithExistingUser() { idpConfirmLinkPage.clickLinkAccount(); loginPage.login(bc.getUserPassword()); - assertTrue("Test user should be successfully logged in.", driver.getTitle().contains("AUTH_RESPONSE")); + assertTrue(driver.getTitle().contains("AUTH_RESPONSE"), "Test user should be successfully logged in."); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLogoutFrontChannelTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLogoutFrontChannelTest.java index 794529c307c5..93a3b23938cb 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLogoutFrontChannelTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLogoutFrontChannelTest.java @@ -21,9 +21,9 @@ import static org.keycloak.testsuite.broker.BrokerTestTools.getConsumerRoot; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public class KcOidcBrokerLogoutFrontChannelTest extends AbstractKcOidcBrokerLogoutTest { @Rule public AssertEvents events = new AssertEvents(this); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLogoutTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLogoutTest.java index 756b7f7a09ac..d3ad9f4f43b2 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLogoutTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLogoutTest.java @@ -17,16 +17,16 @@ import org.keycloak.testsuite.util.WaitUtils; import org.keycloak.testsuite.util.oauth.AccessTokenResponse; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestConstants.REALM_CONS_NAME; import static org.keycloak.testsuite.broker.BrokerTestConstants.REALM_PROV_NAME; import static org.keycloak.testsuite.broker.BrokerTestTools.getConsumerRoot; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class KcOidcBrokerLogoutTest extends AbstractKcOidcBrokerLogoutTest { @@ -271,8 +271,8 @@ public void testFrontChannelLogoutRequestsSendingOnlyClientIdWithFrontChannelLog WaitUtils.waitForPageToLoad(); logoutConfirmPage.isCurrent(); - Assert.assertTrue(driver.getPageSource().contains("You are logging out from following apps")); - Assert.assertTrue(driver.getPageSource().contains("broker-app")); + Assertions.assertTrue(driver.getPageSource().contains("You are logging out from following apps")); + Assertions.assertTrue(driver.getPageSource().contains("broker-app")); oauth.clientId("account"); oauth.redirectUri(getConsumerRoot() + "/auth/realms/" + REALM_PROV_NAME + "/account"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerNoLoginHintTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerNoLoginHintTest.java index 9635054abc04..71c19b94dfa1 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerNoLoginHintTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerNoLoginHintTest.java @@ -8,9 +8,9 @@ import org.keycloak.models.IdentityProviderSyncMode; import org.keycloak.representations.idm.IdentityProviderRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; import org.apache.commons.lang3.StringUtils; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_ALIAS; import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_PROVIDER_ID; @@ -50,11 +50,11 @@ protected void loginUser() { waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); - Assert.assertTrue("User identifiant should not be fullfilled", - StringUtils.isBlank(loginPage.getUsername())); + Assertions.assertTrue(StringUtils.isBlank(loginPage.getUsername()), + "User identifiant should not be fullfilled"); log.debug("Logging in"); loginPage.login(bc.getUserLogin(), bc.getUserPassword()); @@ -62,8 +62,8 @@ protected void loginUser() { waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); @@ -71,7 +71,7 @@ protected void loginUser() { UsersResource consumerUsers = adminClient.realm(bc.consumerRealmName()).users(); int userCount = consumerUsers.count(); - Assert.assertTrue("There must be at least one user", userCount > 0); + Assertions.assertTrue(userCount > 0, "There must be at least one user"); List users = consumerUsers.search("", 0, userCount); @@ -83,7 +83,7 @@ protected void loginUser() { } } - Assert.assertTrue("There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName(), - isUserFound); + Assertions.assertTrue(isUserFound, + "There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerNonceParameterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerNonceParameterTest.java index 0a2ec1f43cbc..c8faba23fca3 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerNonceParameterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerNonceParameterTest.java @@ -22,8 +22,8 @@ import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.keycloak.testsuite.util.oauth.AuthorizationEndpointResponse; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestTools.getConsumerRoot; @@ -70,11 +70,11 @@ protected void loginUser() { AccessTokenResponse response = oauth.doAccessTokenRequest(code); IDToken idToken = toIdToken(response.getIdToken()); - Assert.assertEquals("123456", idToken.getNonce()); + Assertions.assertEquals("123456", idToken.getNonce()); String federatedIdTokenString = (String) idToken.getOtherClaims().get(OIDCIdentityProvider.FEDERATED_ID_TOKEN); - Assert.assertNotNull(federatedIdTokenString); + Assertions.assertNotNull(federatedIdTokenString); IDToken federatedIdToken = toIdToken(federatedIdTokenString); - Assert.assertNotNull(federatedIdToken.getNonce()); + Assertions.assertNotNull(federatedIdToken.getNonce()); } @Test @@ -96,11 +96,11 @@ public void testNonceNotSet() { AccessTokenResponse response = oauth.doAccessTokenRequest(code); IDToken idToken = toIdToken(response.getIdToken()); - Assert.assertNull(idToken.getNonce()); + Assertions.assertNull(idToken.getNonce()); String federatedIdTokenString = (String) idToken.getOtherClaims().get(OIDCIdentityProvider.FEDERATED_ID_TOKEN); - Assert.assertNotNull(federatedIdTokenString); + Assertions.assertNotNull(federatedIdTokenString); IDToken federatedIdToken = toIdToken(federatedIdTokenString); - Assert.assertNull(federatedIdToken.getNonce()); + Assertions.assertNull(federatedIdToken.getNonce()); } protected IDToken toIdToken(String encoded) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerParameterForwardTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerParameterForwardTest.java index cc40410014d6..549c7959ce23 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerParameterForwardTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerParameterForwardTest.java @@ -11,7 +11,8 @@ import org.keycloak.protocol.oidc.OIDCLoginProtocol; import org.keycloak.representations.idm.IdentityProviderRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; + +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_ALIAS; import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_PROVIDER_ID; @@ -98,7 +99,7 @@ protected void loginUser() { UsersResource consumerUsers = adminClient.realm(bc.consumerRealmName()).users(); int userCount = consumerUsers.count(); - Assert.assertTrue("There must be at least one user", userCount > 0); + Assertions.assertTrue(userCount > 0, "There must be at least one user"); List users = consumerUsers.search("", 0, userCount); @@ -110,8 +111,8 @@ protected void loginUser() { } } - Assert.assertTrue("There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName(), - isUserFound); + Assertions.assertTrue(isUserFound, + "There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerPassMaxAgeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerPassMaxAgeTest.java index aee4c12d3c90..16485dbd7c58 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerPassMaxAgeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerPassMaxAgeTest.java @@ -7,11 +7,11 @@ import org.keycloak.models.IdentityProviderModel; import org.keycloak.models.IdentityProviderSyncMode; import org.keycloak.representations.idm.IdentityProviderRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.broker.oidc.TestKeycloakOidcIdentityProviderFactory; import org.junit.Ignore; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_ALIAS; import static org.keycloak.testsuite.broker.BrokerTestTools.createIdentityProvider; @@ -65,8 +65,8 @@ public void loginWithExistingUser() { loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); loginPage.login(bc.getUserLogin(), bc.getUserPassword()); @@ -79,14 +79,14 @@ public void loginWithExistingUser() { // we should now see the login page of the consumer waitForPage(driver, "sign in to", true); loginPage.assertCurrent(bc.consumerRealmName()); - Assert.assertTrue("Driver should be on the consumer realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/protocol/openid-connect/auth")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/protocol/openid-connect/auth"), + "Driver should be on the consumer realm page right now"); loginPage.clickSocial(bc.getIDPAlias()); // we should see the login page of the provider, since the max_age was propagated waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); loginPage.assertCurrent(bc.providerRealmName()); // reauthenticate with password @@ -107,8 +107,8 @@ public void testEnforceReAuthenticationWhenMaxAgeIsSet() { loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); loginPage.login(bc.getUserLogin(), bc.getUserPassword()); @@ -129,14 +129,14 @@ public void testEnforceReAuthenticationWhenMaxAgeIsSet() { // we should now see the login page of the consumer waitForPage(driver, "sign in to", true); loginPage.assertCurrent(bc.consumerRealmName()); - Assert.assertTrue("Driver should be on the consumer realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/protocol/openid-connect/auth")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/protocol/openid-connect/auth"), + "Driver should be on the consumer realm page right now"); loginPage.clickSocial(bc.getIDPAlias()); // we should see the login page of the provider, since the max_age was propagated waitForPage(driver, "sign in to", true); loginPage.getError(); - Assert.assertEquals("Unexpected error when authenticating with identity provider", + Assertions.assertEquals("Unexpected error when authenticating with identity provider", loginPage.getInstruction()); testSingleLogout(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerPromptNoneRedirectTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerPromptNoneRedirectTest.java index 846726f51180..d3cdc7318b09 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerPromptNoneRedirectTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerPromptNoneRedirectTest.java @@ -23,12 +23,12 @@ import org.keycloak.models.IdentityProviderSyncMode; import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.AccountHelper; import org.keycloak.testsuite.util.UserBuilder; import org.junit.Ignore; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.admin.AdminApiUtil.createUserWithAdminClient; import static org.keycloak.testsuite.admin.AdminApiUtil.resetUserPassword; @@ -38,7 +38,7 @@ import static org.keycloak.testsuite.broker.BrokerTestTools.getProviderRoot; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * This class tests the propagation of the {@code prompt=none} request parameter to a default IDP (if one has been specified) @@ -80,7 +80,7 @@ public void testSuccessfulRedirectToProviderWithPromptNone() { /* no need to log in again, the idp should have been able to identify that the user is already logged in and the authenticated user should have been established in the consumer realm. Lastly, user must be redirected to the account app as expected. */ - Assert.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/account")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/account")); /* let's try logging out from the consumer realm and then send an auth request with only prompt=none. The absence of a default idp should result in a login required error because the user is not authenticated in the consumer realm and the request won't be propagated @@ -93,7 +93,7 @@ public void testSuccessfulRedirectToProviderWithPromptNone() { waitForPage(driver, "sign in to", true); url = driver.getCurrentUrl() + "&prompt=none"; driver.navigate().to(url); - Assert.assertTrue(driver.getCurrentUrl().contains(bc.providerRealmName() + "/account/?error=login_required")); + Assertions.assertTrue(driver.getCurrentUrl().contains(bc.providerRealmName() + "/account/?error=login_required")); } /** @@ -112,7 +112,7 @@ public void testUnauthenticatedUserReturnsLoginRequired() throws Exception { waitForPage(driver, "sign in to", true); String url = driver.getCurrentUrl() + "&prompt=none&kc_idp_hint=" + bc.getIDPAlias(); driver.navigate().to(url); - Assert.assertTrue(driver.getCurrentUrl().contains("/app/auth?error=login_required")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/app/auth?error=login_required")); } /** @@ -216,7 +216,7 @@ protected void checkAuthWithPromptNoneReturnsInteractionRequired() { waitForPage(driver, "sign in to", true); String url = driver.getCurrentUrl() + "&kc_idp_hint=" + bc.getIDPAlias() + "&prompt=none"; driver.navigate().to(url); - Assert.assertTrue(driver.getCurrentUrl().contains(bc.providerRealmName() + "/account/?error=interaction_required")); + Assertions.assertTrue(driver.getCurrentUrl().contains(bc.providerRealmName() + "/account/?error=interaction_required")); } /** @@ -228,11 +228,11 @@ protected void authenticateDirectlyInIDP() { loginPage.open(bc.providerRealmName()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); loginPage.login(bc.getUserLogin(), bc.getUserPassword()); - Assert.assertTrue( + Assertions.assertTrue( driver.getCurrentUrl().contains( "/auth/realms/" + bc.providerRealmName() + "/")); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerPromptParameterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerPromptParameterTest.java index 591c7998f06d..f77d53dd489a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerPromptParameterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerPromptParameterTest.java @@ -7,7 +7,8 @@ import org.keycloak.models.IdentityProviderSyncMode; import org.keycloak.protocol.oidc.OIDCLoginProtocol; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; + +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; @@ -34,14 +35,14 @@ protected void loginUser() { waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); - Assert.assertFalse(OIDCLoginProtocol.PROMPT_PARAM + "=" + PROMPT_LOGIN + " should not be part of the url", - driver.getCurrentUrl().contains(OIDCLoginProtocol.PROMPT_PARAM + "=" + PROMPT_LOGIN)); + Assertions.assertFalse(driver.getCurrentUrl().contains(OIDCLoginProtocol.PROMPT_PARAM + "=" + PROMPT_LOGIN), + OIDCLoginProtocol.PROMPT_PARAM + "=" + PROMPT_LOGIN + " should not be part of the url"); - Assert.assertTrue(OIDCLoginProtocol.PROMPT_PARAM + "=" + PROMPT_CONSENT + " should be part of the url", - driver.getCurrentUrl().contains(OIDCLoginProtocol.PROMPT_PARAM + "=" + PROMPT_CONSENT)); + Assertions.assertTrue(driver.getCurrentUrl().contains(OIDCLoginProtocol.PROMPT_PARAM + "=" + PROMPT_CONSENT), + OIDCLoginProtocol.PROMPT_PARAM + "=" + PROMPT_CONSENT + " should be part of the url"); log.debug("Logging in"); loginPage.login(bc.getUserLogin(), bc.getUserPassword()); @@ -49,8 +50,8 @@ protected void loginUser() { waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); @@ -59,7 +60,7 @@ protected void loginUser() { UsersResource consumerUsers = adminClient.realm(bc.consumerRealmName()).users(); int userCount = consumerUsers.count(); - Assert.assertTrue("There must be at least one user", userCount > 0); + Assertions.assertTrue(userCount > 0, "There must be at least one user"); List users = consumerUsers.search("", 0, userCount); @@ -71,8 +72,8 @@ protected void loginUser() { } } - Assert.assertTrue("There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName(), - isUserFound); + Assertions.assertTrue(isUserFound, + "There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName()); } private class KcOidcBrokerConfiguration2 extends KcOidcBrokerConfiguration { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerTest.java index acc77588950d..46df7d27febe 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerTest.java @@ -46,7 +46,6 @@ import org.keycloak.representations.idm.RoleRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.services.managers.AuthenticationManager; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.broker.util.SimpleHttpDefault; import org.keycloak.testsuite.util.AccountHelper; @@ -61,6 +60,7 @@ import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_ALIAS; import static org.keycloak.testsuite.broker.BrokerTestConstants.REALM_PROV_NAME; @@ -75,7 +75,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Final class as it's not intended to be overriden. Feel free to remove "final" if you really know what you are doing. @@ -212,8 +212,8 @@ private void loginFetchingUserFromUserEndpoint(boolean loginIsDenied) { } updateAccountInformationPage.assertCurrent(); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); @@ -221,7 +221,7 @@ private void loginFetchingUserFromUserEndpoint(boolean loginIsDenied) { UsersResource consumerUsers = adminClient.realm(bc.consumerRealmName()).users(); int userCount = consumerUsers.count(); - Assert.assertTrue("There must be at least one user", userCount > 0); + Assertions.assertTrue(userCount > 0, "There must be at least one user"); List users = consumerUsers.search("", 0, userCount); @@ -233,8 +233,8 @@ private void loginFetchingUserFromUserEndpoint(boolean loginIsDenied) { } } - Assert.assertTrue("There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName(), - isUserFound); + Assertions.assertTrue(isUserFound, + "There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName()); } finally { brokerApp.getAttributes().put(OIDCConfigAttributes.USER_INFO_RESPONSE_SIGNATURE_ALG, null); brokerApp.getAttributes().put("validateSignature", Boolean.FALSE.toString()); @@ -274,8 +274,8 @@ public void loginFetchingUserFromUserEndpointWithClaimMapper() { UserRepresentation user = getFederatedIdentity(); - Assert.assertEquals(1, user.getAttributes().size()); - Assert.assertEquals("hard-coded", user.getAttributes().get("hard-coded").get(0)); + Assertions.assertEquals(1, user.getAttributes().size()); + Assertions.assertEquals("hard-coded", user.getAttributes().get("hard-coded").get(0)); } @@ -387,7 +387,7 @@ public void testIdPNotFound() { assertThat(error, notNullValue()); assertThat(error.getError(), is("Identity Provider [" + notExistingIdP + "] not found.")); } catch (IOException ex) { - Assert.fail("Cannot create HTTP client. Details: " + ex.getMessage()); + Assertions.fail("Cannot create HTTP client. Details: " + ex.getMessage()); } } @@ -577,7 +577,7 @@ public void loginWithClaimFilter() { UserRepresentation user = getFederatedIdentity(); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); } @Test @@ -593,7 +593,7 @@ public void loginWithClaimRegexpFilter() { UserRepresentation user = getFederatedIdentity(); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); } @Test @@ -605,7 +605,7 @@ public void denyLoginWithClaimFilter() { WaitUtils.waitForPageToLoad(); loginFetchingUserFromUserEndpoint(true); - Assert.assertEquals("The ID token issued by the identity provider does not match the configured essential claim. Please contact your administrator.", + Assertions.assertEquals("The ID token issued by the identity provider does not match the configured essential claim. Please contact your administrator.", loginPage.getInstruction()); @@ -797,7 +797,7 @@ public void checkUpdatedEmailAttributeIdPSameValueDifferentCase() throws Excepti UserResource consumerUserResource = consumerRealmResource.users().get(consumerUserID); checkFederatedIdentityLink(consumerUserResource, providerUserID, USERNAME); - Assert.assertFalse(consumerUserResource.toRepresentation().isEmailVerified()); + Assertions.assertFalse(consumerUserResource.toRepresentation().isEmailVerified()); AccountHelper.logout(adminClient.realm(bc.consumerRealmName()), USERNAME); AccountHelper.logout(adminClient.realm(bc.providerRealmName()), USERNAME); @@ -806,7 +806,7 @@ public void checkUpdatedEmailAttributeIdPSameValueDifferentCase() throws Excepti consumerUser = consumerUserResource.toRepresentation(); consumerUser.setEmailVerified(true); consumerUserResource.update(consumerUser); - Assert.assertTrue(consumerUserResource.toRepresentation().isEmailVerified()); + Assertions.assertTrue(consumerUserResource.toRepresentation().isEmailVerified()); // Change the client scope for email to set the hardcoded email in capitals ProtocolMapperRepresentation hardcodedEmail = new ProtocolMapperRepresentation(); @@ -838,7 +838,7 @@ public void checkUpdatedEmailAttributeIdPSameValueDifferentCase() throws Excepti checkFederatedIdentityLink(consumerUserResource, providerUserID, USERNAME); // the email should be verified as it's just a different case - Assert.assertTrue(consumerUserResource.toRepresentation().isEmailVerified()); + Assertions.assertTrue(consumerUserResource.toRepresentation().isEmailVerified()); } finally { providerUsersResource.delete(providerUserID).close(); } @@ -883,7 +883,7 @@ private void updateIdPSyncMode(IdentityProviderRepresentation idProvider, Identi private UserRepresentation getFederatedIdentity() { List users = realmsResouce().realm(bc.consumerRealmName()).users().search(bc.getUserLogin()); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); return users.get(0); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerTokenExchangeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerTokenExchangeTest.java index 2b99f2e06a16..94ffbba19fb0 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerTokenExchangeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerTokenExchangeTest.java @@ -58,7 +58,6 @@ import org.keycloak.representations.idm.authorization.ClientPolicyRepresentation; import org.keycloak.services.resources.admin.fgap.AdminPermissionManagement; import org.keycloak.services.resources.admin.fgap.AdminPermissions; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.arquillian.annotation.EnableFeature; import org.keycloak.testsuite.arquillian.annotation.EnableFeatures; @@ -70,6 +69,7 @@ import org.keycloak.util.BasicAuthHelper; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_ALIAS; import static org.keycloak.testsuite.util.ProtocolMapperUtil.createHardcodedClaim; @@ -297,7 +297,7 @@ public void testSupportedTokenTypesWhenValidatingSubjectToken() throws Exception oauth.logoutForm().idTokenHint(idTokenString) .postLogoutRedirectUri(oauth.APP_AUTH_ROOT).open(); String logoutToken = testingClient.testApp().getBackChannelRawLogoutToken(); - Assert.assertNotNull(logoutToken); + Assertions.assertNotNull(logoutToken); Client httpClient = AdminClientUtil.createResteasyClient(); try { @@ -343,7 +343,7 @@ public void testIgnoredTokenTypesValidationWhenExplicitlyConfigured() throws Exc oauth.logoutForm().idTokenHint(idTokenString) .postLogoutRedirectUri(oauth.APP_AUTH_ROOT).open(); String logoutToken = testingClient.testApp().getBackChannelRawLogoutToken(); - Assert.assertNotNull(logoutToken); + Assertions.assertNotNull(logoutToken); Client httpClient = AdminClientUtil.createResteasyClient(); try { @@ -384,7 +384,7 @@ public void testInternalExternalTokenExchangeStoredToken() throws Exception { private static void setupRealm(KeycloakSession session) { RealmModel realm = session.getContext().getRealm(); IdentityProviderModel idp = session.identityProviders().getByAlias(IDP_OIDC_ALIAS); - org.junit.Assert.assertNotNull(idp); + Assertions.assertNotNull(idp); ClientModel client = realm.addClient("test-app"); client.setClientId("test-app"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerTransientSessionsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerTransientSessionsTest.java index bdb0a8feadc5..3080effc4657 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerTransientSessionsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerTransientSessionsTest.java @@ -55,7 +55,6 @@ import org.keycloak.representations.idm.RoleRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.representations.idm.UserSessionRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.arquillian.annotation.EnableFeature; import org.keycloak.testsuite.broker.util.SimpleHttpDefault; @@ -79,6 +78,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestConstants.REALM_CONS_NAME; import static org.keycloak.testsuite.broker.BrokerTestConstants.REALM_PROV_NAME; @@ -98,10 +98,10 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Final class as it's not intended to be overriden. Feel free to remove "final" if you really know what you are doing. @@ -247,8 +247,8 @@ private void loginFetchingUserFromUserEndpoint(boolean loginIsDenied) { } updateAccountInformationPage.assertCurrent(); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); @@ -256,7 +256,7 @@ private void loginFetchingUserFromUserEndpoint(boolean loginIsDenied) { List consumerUsers = getConsumerUserRepresentations().collect(Collectors.toList()); int userCount = consumerUsers.size(); - Assert.assertTrue("There must be at least one user", userCount > 0); + Assertions.assertTrue(userCount > 0, "There must be at least one user"); boolean isUserFound = false; for (UserRepresentation user : consumerUsers) { @@ -266,8 +266,8 @@ private void loginFetchingUserFromUserEndpoint(boolean loginIsDenied) { } } - Assert.assertTrue("There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName(), - isUserFound); + Assertions.assertTrue(isUserFound, + "There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName()); } finally { brokerApp.getAttributes().put(OIDCConfigAttributes.USER_INFO_RESPONSE_SIGNATURE_ALG, null); brokerApp.getAttributes().put("validateSignature", Boolean.FALSE.toString()); @@ -307,8 +307,8 @@ public void loginFetchingUserFromUserEndpointWithClaimMapper() { UserRepresentation user = getFederatedIdentity(); - Assert.assertEquals(1, user.getAttributes().size()); - Assert.assertEquals("hard-coded", user.getAttributes().get("hard-coded").get(0)); + Assertions.assertEquals(1, user.getAttributes().size()); + Assertions.assertEquals("hard-coded", user.getAttributes().get("hard-coded").get(0)); } @Test @@ -380,7 +380,7 @@ public void testIdPNotFound() { assertThat(error, notNullValue()); assertThat(error.getError(), is("Identity Provider [" + notExistingIdP + "] not found.")); } catch (IOException ex) { - Assert.fail("Cannot create HTTP client. Details: " + ex.getMessage()); + Assertions.fail("Cannot create HTTP client. Details: " + ex.getMessage()); } } @@ -397,7 +397,7 @@ public void loginWithClaimFilter() { UserRepresentation user = getFederatedIdentity(); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); } @Test @@ -413,7 +413,7 @@ public void loginWithClaimRegexpFilter() { UserRepresentation user = getFederatedIdentity(); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); } @Test @@ -425,7 +425,7 @@ public void denyLoginWithClaimFilter() { WaitUtils.waitForPageToLoad(); loginFetchingUserFromUserEndpoint(true); - Assert.assertEquals("The ID token issued by the identity provider does not match the configured essential claim. Please contact your administrator.", + Assertions.assertEquals("The ID token issued by the identity provider does not match the configured essential claim. Please contact your administrator.", loginPage.getInstruction()); @@ -480,7 +480,7 @@ public void testSingleSignOn() { oauth.clientId(CONSUMER_BROKER_APP_CLIENT_ID); oauth.openLoginForm(); - Assert.assertTrue("Should be logged in", driver.getTitle().endsWith("AUTH_RESPONSE")); + Assertions.assertTrue(driver.getTitle().endsWith("AUTH_RESPONSE"), "Should be logged in"); } // Based on ConsentsTest.testConsents, modified to use consumer realm instead @@ -511,7 +511,7 @@ public void testConsents() throws Exception { assertThat("There should be one consent", consents, hasSize(1)); Map consent = consents.get(0); - Assert.assertEquals("Consent should be given to " + CONSUMER_BROKER_APP_CLIENT_ID, CONSUMER_BROKER_APP_CLIENT_ID, consent.get("clientId")); + Assertions.assertEquals(CONSUMER_BROKER_APP_CLIENT_ID, consent.get("clientId"), "Consent should be given to " + CONSUMER_BROKER_APP_CLIENT_ID); // list sessions. Single client should be in user session List sessions = userResource.getUserSessions(); @@ -565,8 +565,8 @@ public void testUserInfoEndpoint() throws Exception { // Check that tokenIntrospection can be invoked JsonNode jsonNode = oauth.doIntrospectionAccessTokenRequest(tokenResponse.getAccessToken()).asJsonNode(); - org.junit.Assert.assertEquals(true, jsonNode.get("active").asBoolean()); - org.junit.Assert.assertEquals(bc.getUserEmail(), jsonNode.get("email").asText()); + Assertions.assertEquals(true, jsonNode.get("active").asBoolean()); + Assertions.assertEquals(bc.getUserEmail(), jsonNode.get("email").asText()); } private EventRepresentation loginWithBrokerUsingOAuthClient(String consumerClientId) { @@ -630,7 +630,7 @@ public void offlineTokenBrowserFlow() throws Exception { AccessTokenResponse response = oauth.doRefreshTokenRequest(newRefreshTokenString); RefreshToken newRefreshToken = oauth.parseRefreshToken(newRefreshTokenString); - org.junit.Assert.assertEquals(400, response.getStatusCode()); + Assertions.assertEquals(400, response.getStatusCode()); assertEquals("invalid_grant", response.getError()); events.expectRefresh(offlineToken.getId(), newRefreshToken.getSessionState()) @@ -662,17 +662,17 @@ private String testRefreshWithOfflineToken(AccessToken oldToken, RefreshToken of AccessTokenResponse response = oauth.doRefreshTokenRequest(offlineTokenString); AccessToken refreshedToken = oauth.verifyToken(response.getAccessToken()); - org.junit.Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); // Assert new refreshToken in the response String newRefreshToken = response.getRefreshToken(); - org.junit.Assert.assertNotNull(newRefreshToken); - org.junit.Assert.assertNotEquals(oldToken.getId(), refreshedToken.getId()); + Assertions.assertNotNull(newRefreshToken); + Assertions.assertNotEquals(oldToken.getId(), refreshedToken.getId()); // Assert scope parameter contains "offline_access" assertTrue(response.getScope().contains(OAuth2Constants.OFFLINE_ACCESS)); - org.junit.Assert.assertEquals(userId, refreshedToken.getSubject()); + Assertions.assertEquals(userId, refreshedToken.getSubject()); assertTrue(refreshedToken.getRealmAccess().isUserInRole(Constants.OFFLINE_ACCESS_ROLE)); @@ -683,7 +683,7 @@ private String testRefreshWithOfflineToken(AccessToken oldToken, RefreshToken of .removeDetail(Details.UPDATED_REFRESH_TOKEN_ID) .detail(Details.REFRESH_TOKEN_TYPE, TokenUtil.TOKEN_TYPE_OFFLINE) .assertEvent(); - org.junit.Assert.assertNotEquals(oldToken.getId(), refreshEvent.getDetails().get(Details.TOKEN_ID)); + Assertions.assertNotEquals(oldToken.getId(), refreshEvent.getDetails().get(Details.TOKEN_ID)); setTimeOffset(0); return newRefreshToken; diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerUiLocalesDisabledTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerUiLocalesDisabledTest.java index 2863bdca507f..a17c31dbd8f3 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerUiLocalesDisabledTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerUiLocalesDisabledTest.java @@ -7,7 +7,8 @@ import org.keycloak.models.IdentityProviderSyncMode; import org.keycloak.representations.idm.IdentityProviderRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; + +import org.junit.jupiter.api.Assertions; import static java.util.Locale.ENGLISH; @@ -72,7 +73,7 @@ protected void loginUser() { UsersResource consumerUsers = adminClient.realm(bc.consumerRealmName()).users(); int userCount = consumerUsers.count(); - Assert.assertTrue("There must be at least one user", userCount > 0); + Assertions.assertTrue(userCount > 0, "There must be at least one user"); List users = consumerUsers.search("", 0, userCount); @@ -84,7 +85,7 @@ protected void loginUser() { } } - Assert.assertTrue("There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName(), - isUserFound); + Assertions.assertTrue(isUserFound, + "There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerUiLocalesEnabledTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerUiLocalesEnabledTest.java index fcf8c67860f5..f4479e61e22d 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerUiLocalesEnabledTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerUiLocalesEnabledTest.java @@ -7,7 +7,8 @@ import org.keycloak.models.IdentityProviderSyncMode; import org.keycloak.representations.idm.IdentityProviderRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; + +import org.junit.jupiter.api.Assertions; import static java.util.Locale.ENGLISH; @@ -71,7 +72,7 @@ protected void loginUser() { UsersResource consumerUsers = adminClient.realm(bc.consumerRealmName()).users(); int userCount = consumerUsers.count(); - Assert.assertTrue("There must be at least one user", userCount > 0); + Assertions.assertTrue(userCount > 0, "There must be at least one user"); List users = consumerUsers.search("", 0, userCount); @@ -83,7 +84,7 @@ protected void loginUser() { } } - Assert.assertTrue("There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName(), - isUserFound); + Assertions.assertTrue(isUserFound, + "There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerUiLocalesWithIdpHintTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerUiLocalesWithIdpHintTest.java index d1d0b2430383..e3e86acbe7ef 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerUiLocalesWithIdpHintTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerUiLocalesWithIdpHintTest.java @@ -8,7 +8,8 @@ import org.keycloak.models.IdentityProviderSyncMode; import org.keycloak.representations.idm.IdentityProviderRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; + +import org.junit.jupiter.api.Assertions; import static org.keycloak.OAuth2Constants.UI_LOCALES_PARAM; import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_ALIAS; @@ -72,7 +73,7 @@ protected void loginUser() { UsersResource consumerUsers = adminClient.realm(bc.consumerRealmName()).users(); int userCount = consumerUsers.count(); - Assert.assertTrue("There must be at least one user", userCount > 0); + Assertions.assertTrue(userCount > 0, "There must be at least one user"); List users = consumerUsers.search("", 0, userCount); @@ -84,7 +85,7 @@ protected void loginUser() { } } - Assert.assertTrue("There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName(), - isUserFound); + Assertions.assertTrue(isUserFound, + "There must be user " + bc.getUserLogin() + " in realm " + bc.consumerRealmName()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerWithConsentTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerWithConsentTest.java index c92e4709815c..b2292265439c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerWithConsentTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerWithConsentTest.java @@ -7,14 +7,14 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.util.InfinispanTestTimeServiceRule; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerRunOnServerUtil.removeBrokerExpiredSessions; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class KcOidcBrokerWithConsentTest extends AbstractInitializedBaseBrokerTest { @@ -32,7 +32,7 @@ public void beforeBrokerTest() { // Require broker to show consent screen RealmResource brokeredRealm = adminClient.realm(bc.providerRealmName()); List clients = brokeredRealm.clients().findByClientId("brokerapp"); - org.junit.Assert.assertEquals(1, clients.size()); + Assertions.assertEquals(1, clients.size()); ClientRepresentation brokerApp = clients.get(0); brokerApp.setConsentRequired(true); brokeredRealm.clients().get(brokerApp.getId()).update(brokerApp); @@ -69,7 +69,7 @@ public void testConsentDeniedWithExpiredClientSession() { grantPage.cancel(); // Assert login page with "You took too long to login..." message - org.junit.Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); + Assertions.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); } finally { invokeTimeOffset(0); @@ -96,7 +96,7 @@ public void testConsentDeniedWithExpiredAndClearedClientSession() { grantPage.cancel(); // Assert login page with "You took too long to login..." message - Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); + Assertions.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); } finally { invokeTimeOffset(0); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginDetectExistingUserTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginDetectExistingUserTest.java index d4e961d149c3..28c86295a966 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginDetectExistingUserTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginDetectExistingUserTest.java @@ -18,9 +18,9 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public class KcOidcFirstBrokerLoginDetectExistingUserTest extends AbstractInitializedBaseBrokerTest { @@ -44,7 +44,7 @@ public void beforeBrokerTest() { authMgmtResource.createFlow(authenticationFlowRepresentation); AuthenticationFlowRepresentation authenticationFlowRepresentation1 = getFlow(authMgmtResource, detectExistingFlowAlias); - assertNotNull("The authentication flow must exist", authenticationFlowRepresentation1); + assertNotNull(authenticationFlowRepresentation1, "The authentication flow must exist"); String flowId = authenticationFlowRepresentation1.getId(); // retrieves the id of the newly created flow @@ -59,7 +59,7 @@ public void beforeBrokerTest() { identityProviderRepresentation.getConfig().put(IdentityProviderModel.SYNC_MODE, IdentityProviderSyncMode.FORCE.toString()); identityConsumerResource.update(identityProviderRepresentation); - assertEquals("Two executions must have been created", 2, getFlow(authMgmtResource, detectExistingFlowAlias).getAuthenticationExecutions().size()); + assertEquals(2, getFlow(authMgmtResource, detectExistingFlowAlias).getAuthenticationExecutions().size(), "Two executions must have been created"); } private void addExecution(AuthenticationManagementResource authMgmtResource, String flowId, String providerId, int priority) { @@ -131,8 +131,8 @@ public void loginWhenUserExistsOnConsumer() { UserRepresentation userRepresentation = AccountHelper.getUserRepresentation( adminClient.realm(bc.consumerRealmName()), username); - assertEquals("Email is not correct", userRepresentation.getEmail(), email); - assertEquals("Firstname is not correct", userRepresentation.getFirstName(), firstname); - assertEquals("Lastname is not correct", userRepresentation.getLastName(), lastname); + assertEquals(userRepresentation.getEmail(), email, "Email is not correct"); + assertEquals(userRepresentation.getFirstName(), firstname, "Firstname is not correct"); + assertEquals(userRepresentation.getLastName(), lastname, "Lastname is not correct"); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginNewAuthTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginNewAuthTest.java index 0a2d91286b09..c5101d762a1b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginNewAuthTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginNewAuthTest.java @@ -14,11 +14,12 @@ import org.jboss.arquillian.graphene.page.Page; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests first-broker-login flow with new authenticators. @@ -58,11 +59,11 @@ public void testReAuthenticateWithPasswordAndConditionalOTP_otpNotRequested() { loginWithBrokerAndConfirmLinkAccount(); // Assert on the page with password form - Assert.assertTrue(passwordPage.isCurrent("consumer")); + Assertions.assertTrue(passwordPage.isCurrent("consumer")); // Try bad password first passwordPage.login("bad-password"); - Assert.assertEquals("Invalid password.", passwordPage.getPasswordError()); + Assertions.assertEquals("Invalid password.", passwordPage.getPasswordError()); // Try good password passwordPage.login("password"); @@ -88,7 +89,7 @@ public void testReAuthenticateWithPasswordAndConditionalOTP_otpRequested() { loginWithBrokerAndConfirmLinkAccount(); // Login with password - Assert.assertTrue(passwordPage.isCurrent("consumer")); + Assertions.assertTrue(passwordPage.isCurrent("consumer")); passwordPage.login("password"); // Assert on TOTP page. Login with TOTP @@ -112,11 +113,11 @@ public void testReAuthenticateWithPasswordOrOTP_otpNotConfigured_passwordUsed() loginWithBrokerAndConfirmLinkAccount(); // Assert that user can't see credentials combobox. Password is the only available credentials. - Assert.assertTrue(passwordPage.isCurrent("consumer")); + Assertions.assertTrue(passwordPage.isCurrent("consumer")); passwordPage.assertTryAnotherWayLinkAvailability(false); // Login with password - Assert.assertTrue(passwordPage.isCurrent("consumer")); + Assertions.assertTrue(passwordPage.isCurrent("consumer")); passwordPage.login("password"); assertUserAuthenticatedInConsumer(consumerRealmUserId); @@ -138,7 +139,7 @@ public void testReAuthenticateWithPasswordOrOTP_otpConfigured_passwordUsed() { loginWithBrokerAndConfirmLinkAccount(); // Assert that user can choose between Password and OTP as available credentials. Password should be selected by default. - Assert.assertTrue(passwordPage.isCurrent("consumer")); + Assertions.assertTrue(passwordPage.isCurrent("consumer")); passwordPage.assertTryAnotherWayLinkAvailability(true); // Just click "Try another way" to verify that both Password and OTP are available. But go back to Password then @@ -149,7 +150,7 @@ public void testReAuthenticateWithPasswordOrOTP_otpConfigured_passwordUsed() { selectAuthenticatorPage.selectLoginMethod(SelectAuthenticatorPage.PASSWORD); // Login with password - Assert.assertTrue(passwordPage.isCurrent("consumer")); + Assertions.assertTrue(passwordPage.isCurrent("consumer")); passwordPage.login("password"); assertUserAuthenticatedInConsumer(consumerRealmUserId); @@ -173,7 +174,7 @@ public void testReAuthenticateWithPasswordOrOTP_otpConfigured_otpUsed() { loginWithBrokerAndConfirmLinkAccount(); // Assert that user can see credentials combobox. Password and OTP are available credentials. Password should be selected. - Assert.assertTrue(passwordPage.isCurrent("consumer")); + Assertions.assertTrue(passwordPage.isCurrent("consumer")); passwordPage.assertTryAnotherWayLinkAvailability(true); // Click "Try another way", Select OTP and assert OTP form present diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginTest.java index 741c83ff166b..3a2fc1cc9d4f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcFirstBrokerLoginTest.java @@ -15,7 +15,6 @@ import org.keycloak.representations.idm.IdentityProviderRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.broker.oidc.TestKeycloakOidcIdentityProviderFactory; import org.keycloak.testsuite.forms.RegisterWithUserProfileTest; import org.keycloak.testsuite.forms.VerifyProfileTest; @@ -31,6 +30,7 @@ import org.apache.commons.lang3.StringUtils; import org.jboss.arquillian.graphene.page.Page; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; @@ -50,10 +50,10 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Marek Posolda @@ -191,7 +191,7 @@ public void testLinkAccountByReauthenticationWithDifferentBroker() { loginPage.open(bc.consumerRealmName()); logInWithBroker(samlBrokerConfig); - Assert.assertTrue(appPage.isCurrent()); + Assertions.assertTrue(appPage.isCurrent()); AccountHelper.logout(adminClient.realm(bc.consumerRealmName()), bc.getUserLogin()); AccountHelper.logout(adminClient.realm(bc.providerRealmName()), bc.getUserLogin()); @@ -209,7 +209,7 @@ public void testLinkAccountByReauthenticationWithDifferentBroker() { try { this.loginPage.findSocialButton(bc.getIDPAlias()); - org.junit.Assert.fail("Not expected to see social button with " + samlBrokerConfig.getIDPAlias()); + Assertions.fail("Not expected to see social button with " + samlBrokerConfig.getIDPAlias()); } catch (NoSuchElementException expected) { } @@ -271,7 +271,7 @@ public void testFilterMultipleBrokerWhenReauthenticating() { try { this.loginPage.findSocialButton(bc.getIDPAlias()); - org.junit.Assert.fail("Not expected to see social button with " + bc.getIDPAlias()); + Assertions.fail("Not expected to see social button with " + bc.getIDPAlias()); } catch (NoSuchElementException expected) { } @@ -317,7 +317,7 @@ public void testNestedFirstBrokerFlow() { try { this.loginPage.findSocialButton(bc.getIDPAlias()); - org.junit.Assert.fail("Not expected to see social button with " + samlBrokerConfig.getIDPAlias()); + Assertions.fail("Not expected to see social button with " + samlBrokerConfig.getIDPAlias()); } catch (NoSuchElementException expected) { } @@ -389,8 +389,8 @@ public void testEditUsername() { log.debug("Clicking social " + bc.getIDPAlias()); loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); log.debug("Logging in"); loginPage.login("no-first-name", "password"); @@ -405,9 +405,9 @@ public void testEditUsername() { UserRepresentation userRepresentation = AccountHelper.getUserRepresentation(adminClient.realm(bc.consumerRealmName()), "new-username"); - Assert.assertEquals("First Name", userRepresentation.getFirstName()); - Assert.assertEquals("Last Name", userRepresentation.getLastName()); - Assert.assertEquals("no-first-name@localhost.com", userRepresentation.getEmail()); + Assertions.assertEquals("First Name", userRepresentation.getFirstName()); + Assertions.assertEquals("Last Name", userRepresentation.getLastName()); + Assertions.assertEquals("no-first-name@localhost.com", userRepresentation.getEmail()); } @@ -432,8 +432,8 @@ public void shouldOfferOidcOptionOnLoginPageAfterUserTriedToLogInButDecidedNotTo log.debug("Clicking social " + bc.getIDPAlias()); loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); log.debug("Logging in"); loginPage.login("idp-cancel-test", "password"); @@ -446,7 +446,7 @@ public void shouldOfferOidcOptionOnLoginPageAfterUserTriedToLogInButDecidedNotTo assertEquals(urlWhenBackFromRegistrationPage, urlWhenWentBackFromIdpLogin); log.debug("Should not fail here... We're still not logged in, so the IDP should be shown on the login page."); - assertTrue("We should be on the login page.", driver.getPageSource().contains("Sign in to your account")); + assertTrue(driver.getPageSource().contains("Sign in to your account"), "We should be on the login page."); final var socialButton = this.loginPage.findSocialButton(bc.getIDPAlias()); } @@ -472,11 +472,11 @@ public void testDisplayName() { //assert field names // i18n replaced - org.junit.Assert.assertEquals("First name", updateAccountInformationPage.getLabelForField("firstName")); + Assertions.assertEquals("First name", updateAccountInformationPage.getLabelForField("firstName")); // attribute name used if no display name set - org.junit.Assert.assertEquals("lastName", updateAccountInformationPage.getLabelForField("lastName")); + Assertions.assertEquals("lastName", updateAccountInformationPage.getLabelForField("lastName")); // direct value in display name - org.junit.Assert.assertEquals("Department", updateAccountInformationPage.getLabelForField("department")); + Assertions.assertEquals("Department", updateAccountInformationPage.getLabelForField("department")); } @Test @@ -705,7 +705,7 @@ public void testDynamicUserProfileReview_attributeNotRequiredAndSelectedByScopeC waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); - org.junit.Assert.assertTrue(updateAccountInformationPage.isDepartmentPresent()); + Assertions.assertTrue(updateAccountInformationPage.isDepartmentPresent()); updateAccountInformationPage.updateAccountInformation( "attributeNotRequiredAndSelectedByScopeCanBeIgnored", "attributeNotRequiredAndSelectedByScopeCanBeIgnored@email", "FirstAA", "LastAA"); UserRepresentation user = VerifyProfileTest.getUserByUsername(testRealm(),"attributeNotRequiredAndSelectedByScopeCanBeIgnored"); @@ -734,7 +734,7 @@ public void testDynamicUserProfileReview_attributeNotRequiredAndSelectedByScopeC waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); - org.junit.Assert.assertTrue(updateAccountInformationPage.isDepartmentPresent()); + Assertions.assertTrue(updateAccountInformationPage.isDepartmentPresent()); updateAccountInformationPage.updateAccountInformation( "attributeNotRequiredAndSelectedByScopeCanBeSet", "attributeNotRequiredAndSelectedByScopeCanBeSet@email", "FirstAA", "LastAA","Department AA"); UserRepresentation user = VerifyProfileTest.getUserByUsername(testRealm(),"attributeNotRequiredAndSelectedByScopeCanBeSet"); @@ -875,7 +875,7 @@ public void testLinkAccountAndVerifyEmailUsingDifferentBrowser() { loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); loginPage.login(bc.getUserPassword()); - Assert.assertTrue(appPage.isCurrent()); + Assertions.assertTrue(appPage.isCurrent()); } public void addDepartmentScopeIntoRealm() { @@ -908,10 +908,10 @@ public void testSsoLoginWithCustomAttributeWithDefaultValue() { logInWithBroker(bc); waitForPage(driver, "update account information", false); - Assert.assertTrue("Should be on update profile page", updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(updateAccountInformationPage.isCurrent(), "Should be on update profile page"); updateAccountInformationPage.updateAccountInformation("Test", "User"); - Assert.assertTrue("User should be logged in successfully after profile update", appPage.isCurrent()); + Assertions.assertTrue(appPage.isCurrent(), "User should be logged in successfully after profile update"); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcMultipleTabsBrokerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcMultipleTabsBrokerTest.java index e00a657fb9fe..66f83c40636a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcMultipleTabsBrokerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcMultipleTabsBrokerTest.java @@ -37,9 +37,9 @@ import org.keycloak.testsuite.util.oauth.OAuthClient; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import static org.keycloak.testsuite.AssertEvents.DEFAULT_REDIRECT_URI; @@ -81,20 +81,20 @@ public void testAuthenticationExpiredWithMoreBrowserTabs_clickIdpLoginInTab1Afte // Open new tab 2 tabUtil.newTab(oauth.loginForm().build()); assertThat(tabUtil.getCountOfTabs(), Matchers.equalTo(2)); - Assert.assertTrue(loginPage.isCurrent("consumer")); + Assertions.assertTrue(loginPage.isCurrent("consumer")); getLogger().infof("URL in tab2: %s", driver.getCurrentUrl()); setTimeOffset(7200000); // Finish login in tab2 loginPage.clickSocial(bc.getIDPAlias()); - Assert.assertEquals(loginPage.getError(), "Your login attempt timed out. Login will start from the beginning."); + Assertions.assertEquals(loginPage.getError(), "Your login attempt timed out. Login will start from the beginning."); logInWithBroker(bc); waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); - Assert.assertTrue("We must be on consumer realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on consumer realm right now"); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); appPage.assertCurrent(); @@ -121,20 +121,20 @@ public void testAuthenticationExpiredWithMoreBrowserTabs_loginExpiredInBothConsu // Open login page in tab 2 tabUtil.newTab(oauth.loginForm().build()); assertThat(tabUtil.getCountOfTabs(), Matchers.equalTo(2)); - Assert.assertTrue(loginPage.isCurrent("consumer")); + Assertions.assertTrue(loginPage.isCurrent("consumer")); getLogger().infof("URL in tab2: %s", driver.getCurrentUrl()); setTimeOffset(7200000); // Finish login in tab2 loginPage.clickSocial(bc.getIDPAlias()); - Assert.assertEquals(loginPage.getError(), "Your login attempt timed out. Login will start from the beginning."); + Assertions.assertEquals(loginPage.getError(), "Your login attempt timed out. Login will start from the beginning."); logInWithBroker(bc); waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); - Assert.assertTrue("We must be on consumer realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on consumer realm right now"); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); appPage.assertCurrent(); events.clear(); @@ -198,20 +198,20 @@ public void testAuthenticationExpiredWithMoreBrowserTabs_loginExpiredInBothConsu // Open login page in tab 2 tabUtil.newTab(oauth.loginForm().build()); assertThat(tabUtil.getCountOfTabs(), Matchers.equalTo(2)); - Assert.assertTrue(loginPage.isCurrent("consumer")); + Assertions.assertTrue(loginPage.isCurrent("consumer")); getLogger().infof("URL in tab2: %s", driver.getCurrentUrl()); setTimeOffset(7200000); // Finish login in tab2 loginPage.clickSocial(bc.getIDPAlias()); - Assert.assertEquals(loginPage.getError(), "Your login attempt timed out. Login will start from the beginning."); + Assertions.assertEquals(loginPage.getError(), "Your login attempt timed out. Login will start from the beginning."); logInWithBroker(bc); waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); - Assert.assertTrue("We must be on consumer realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on consumer realm right now"); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); appPage.assertCurrent(); events.clear(); @@ -249,7 +249,7 @@ public void testAuthenticationExpiredWithMoreBrowserTabs_loginExpiredInBothConsu // Being on "You are already logged-in" now. No way to redirect to client due "clientData" are null in "state" of OIDC IDP as OIDC IDP requires short state parameter loginPage.assertCurrent("consumer"); - Assert.assertEquals("You are already logged in.", loginPage.getInstruction()); + Assertions.assertEquals("You are already logged in.", loginPage.getInstruction()); } finally { // Revert config idpRep.getConfig().put(OAuth2IdentityProviderConfig.REQUIRES_SHORT_STATE_PARAMETER, "false"); @@ -275,7 +275,7 @@ public void testAuthenticationExpiredWithMoreBrowserTabs_loginExpiredInProvider( // Open login page in tab 2 tabUtil.newTab(oauth.loginForm().build()); assertThat(tabUtil.getCountOfTabs(), Matchers.equalTo(2)); - Assert.assertTrue(loginPage.isCurrent("consumer")); + Assertions.assertTrue(loginPage.isCurrent("consumer")); getLogger().infof("URL in tab2: %s", driver.getCurrentUrl()); setTimeOffset(3600); @@ -285,8 +285,8 @@ public void testAuthenticationExpiredWithMoreBrowserTabs_loginExpiredInProvider( waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); - Assert.assertTrue("We must be on consumer realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on consumer realm right now"); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); appPage.assertCurrent(); events.clear(); @@ -320,8 +320,8 @@ public void testAuthenticationExpiredWithMoreBrowserTabs_loginExpiredInProvider( .assertEvent(); // We were redirected back to IDP where user is asked to re-authenticate (due prompt=login being sent to OIDC IDP in authz request) - Assert.assertEquals("Please re-authenticate to continue", loginPage.getInfoMessage()); - Assert.assertTrue("We must be on provider realm right now",driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertEquals("Please re-authenticate to continue", loginPage.getInfoMessage()); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"),"We must be on provider realm right now"); loginPage.login(bc.getUserPassword()); // Login finished on IDP (provider) as well as on "consumer" realm after being redirected there from "provider" @@ -332,8 +332,8 @@ public void testAuthenticationExpiredWithMoreBrowserTabs_loginExpiredInProvider( .detail(Details.REDIRECT_URI, Matchers.equalTo(OAuthClient.AUTH_SERVER_ROOT + "/realms/" + bc.consumerRealmName() + "/broker/" + bc.getIDPAlias() + "/endpoint")) .assertEvent(); - Assert.assertEquals(EventType.CODE_TO_TOKEN.name(), events.poll().getType()); - Assert.assertEquals(EventType.USER_INFO_REQUEST.name(), events.poll().getType()); + Assertions.assertEquals(EventType.CODE_TO_TOKEN.name(), events.poll().getType()); + Assertions.assertEquals(EventType.USER_INFO_REQUEST.name(), events.poll().getType()); events.expectLogin() .realm(getConsumerRealmId()) @@ -345,8 +345,8 @@ public void testAuthenticationExpiredWithMoreBrowserTabs_loginExpiredInProvider( // Being redirected back to consumer and then back to client right away. Authentication session on "consumer" realm is still valid, so no error here. appPage.assertCurrent(); AuthorizationEndpointResponse authzResponse = oauth.parseLoginResponse(); - org.keycloak.testsuite.Assert.assertNotNull(authzResponse.getCode()); - org.keycloak.testsuite.Assert.assertNull(authzResponse.getError()); + Assertions.assertNotNull(authzResponse.getCode()); + Assertions.assertNull(authzResponse.getError()); } } @@ -354,8 +354,8 @@ public void testAuthenticationExpiredWithMoreBrowserTabs_loginExpiredInProvider( private void assertOnAppPageWithAlreadyLoggedInError() { appPage.assertCurrent(); // Page "You are already logged in." should not be here AuthorizationEndpointResponse authzResponse = oauth.parseLoginResponse(); - org.keycloak.testsuite.Assert.assertEquals(OAuthErrorException.TEMPORARILY_UNAVAILABLE, authzResponse.getError()); - org.keycloak.testsuite.Assert.assertEquals(Constants.AUTHENTICATION_EXPIRED_MESSAGE, authzResponse.getErrorDescription()); + Assertions.assertEquals(OAuthErrorException.TEMPORARILY_UNAVAILABLE, authzResponse.getError()); + Assertions.assertEquals(Constants.AUTHENTICATION_EXPIRED_MESSAGE, authzResponse.getErrorDescription()); } private String getProviderRealmId() { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlAttributeConsumingServiceIndexTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlAttributeConsumingServiceIndexTest.java index 284ec665de8a..d8d6d7dc4260 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlAttributeConsumingServiceIndexTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlAttributeConsumingServiceIndexTest.java @@ -12,8 +12,8 @@ import org.keycloak.testsuite.util.SamlClient.Binding; import org.keycloak.testsuite.util.SamlClientBuilder; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.w3c.dom.Document; import org.w3c.dom.Node; @@ -51,7 +51,7 @@ public void testAttributeConsumingServiceIndexNotSet() throws Exception { // Find the AuthnRequest AttributeConsumingServiceIndex attribute Node attrNode = document.getDocumentElement().getAttributes().getNamedItem("AttributeConsumingServiceIndex"); - Assert.assertEquals("Unexpected AttributeConsumingServiceIndex attribute value", null, attrNode); + Assertions.assertEquals(null, attrNode, "Unexpected AttributeConsumingServiceIndex attribute value"); } catch (Exception ex) { @@ -86,7 +86,7 @@ public void testAttributeConsumingServiceIndexSet() throws Exception { // Find the AuthnRequest AttributeConsumingServiceIndex attribute String attrValue = document.getDocumentElement().getAttributes().getNamedItem("AttributeConsumingServiceIndex").getNodeValue(); - Assert.assertEquals("Unexpected AttributeConsumingServiceIndex attribute value", "15", attrValue); + Assertions.assertEquals("15", attrValue, "Unexpected AttributeConsumingServiceIndex attribute value"); } catch (Exception ex) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlBrokerArtifactBindingTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlBrokerArtifactBindingTest.java index 2e61ab68743b..da90587e1fc0 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlBrokerArtifactBindingTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlBrokerArtifactBindingTest.java @@ -6,7 +6,6 @@ import org.keycloak.broker.saml.SAMLIdentityProviderConfig; import org.keycloak.crypto.Algorithm; import org.keycloak.protocol.saml.SamlConfigAttributes; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.updaters.ClientAttributeUpdater; import org.keycloak.testsuite.updaters.IdentityProviderAttributeUpdater; import org.keycloak.testsuite.util.KeyUtils; @@ -14,6 +13,7 @@ import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; +import org.junit.jupiter.api.Assertions; public final class KcSamlBrokerArtifactBindingTest extends AbstractInitializedBaseBrokerTest { @@ -166,7 +166,7 @@ private void login(boolean success) { appPage.assertCurrent(); } else { errorPage.assertCurrent(); - Assert.assertEquals("Invalid signature in response from identity provider.", errorPage.getError()); + Assertions.assertEquals("Invalid signature in response from identity provider.", errorPage.getError()); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlBrokerLoginHintWithOptionEnabledTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlBrokerLoginHintWithOptionEnabledTest.java index 116428da68f3..1c8bc790c4df 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlBrokerLoginHintWithOptionEnabledTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlBrokerLoginHintWithOptionEnabledTest.java @@ -1,12 +1,12 @@ package org.keycloak.testsuite.broker; -import org.keycloak.testsuite.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class KcSamlBrokerLoginHintWithOptionEnabledTest extends AbstractSamlLoginHintTest { @@ -24,11 +24,11 @@ public void testPassLoginHintWithXmlCharShouldEncodeIt() { addLoginHintOnSocialButton(fishyLoginHint); loginPage.clickSocial(bc.getIDPAlias()); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); log.debug("Logging in"); - assertEquals("Username input should contain the SAML subject", loginPage.getUsername(), fishyLoginHint); + assertEquals(loginPage.getUsername(), fishyLoginHint, "Username input should contain the SAML subject"); } @Override diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlCustomEntityIdBrokerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlCustomEntityIdBrokerTest.java index 116e3aecff1e..bd699d9ed455 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlCustomEntityIdBrokerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlCustomEntityIdBrokerTest.java @@ -12,8 +12,8 @@ import org.keycloak.testsuite.util.SamlClient.Binding; import org.keycloak.testsuite.util.SamlClientBuilder; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -52,7 +52,7 @@ public void testCustomEntityNotSet() throws Exception { // Find the Issuer element Element issuerElement = DocumentUtil.getDirectChildElement(document.getDocumentElement(), ASSERTION_NSURI.get(), "Issuer"); - Assert.assertEquals("Unexpected Issuer element value", getAuthServerRoot() + "realms/consumer", issuerElement.getTextContent()); + Assertions.assertEquals(getAuthServerRoot() + "realms/consumer", issuerElement.getTextContent(), "Unexpected Issuer element value"); } catch (Exception ex) { @@ -87,7 +87,7 @@ public void testCustomEntityIdSet() throws Exception { // Find the Issuer element Element issuerElement = DocumentUtil.getDirectChildElement(document.getDocumentElement(), ASSERTION_NSURI.get(), "Issuer"); - Assert.assertEquals("Unexpected Issuer element value", "http://my.custom.entity.id", issuerElement.getTextContent()); + Assertions.assertEquals("http://my.custom.entity.id", issuerElement.getTextContent(), "Unexpected Issuer element value"); } catch (Exception ex) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlForceAuthnBrokerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlForceAuthnBrokerTest.java index 58209cc9b665..3c21becc0a47 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlForceAuthnBrokerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlForceAuthnBrokerTest.java @@ -29,8 +29,8 @@ import org.keycloak.testsuite.util.SamlClient.Binding; import org.keycloak.testsuite.util.SamlClientBuilder; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.w3c.dom.Document; import static org.keycloak.testsuite.broker.BrokerTestTools.getConsumerRoot; @@ -70,7 +70,7 @@ public void testForceAuthnNotSentInRequest() throws Exception { { // Find the AuthnRequest ForceAuthN attribute String attrValue = document.getDocumentElement().getAttributes().getNamedItem("ForceAuthn").getNodeValue(); - Assert.assertEquals("Unexpected ForceAuthn attribute value", "false", attrValue); + Assertions.assertEquals("false", attrValue, "Unexpected ForceAuthn attribute value"); } catch (Exception ex) { @@ -108,7 +108,7 @@ public void testForceAuthnSentInRequest() throws Exception { { // Find the AuthnRequest ForceAuthN attribute String attrValue = document.getDocumentElement().getAttributes().getNamedItem("ForceAuthn").getNodeValue(); - Assert.assertEquals("Unexpected ForceAuthn attribute value", "true", attrValue); + Assertions.assertEquals("true", attrValue, "Unexpected ForceAuthn attribute value"); } catch (Exception ex) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlIdPInitiatedSsoTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlIdPInitiatedSsoTest.java index 884cc47df5bb..1b918836ede9 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlIdPInitiatedSsoTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlIdPInitiatedSsoTest.java @@ -41,7 +41,6 @@ import org.keycloak.saml.processing.core.saml.v2.constants.X500SAMLProfileConstants; import org.keycloak.saml.processing.core.saml.v2.util.AssertionUtil; import org.keycloak.testsuite.AbstractKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.pages.ErrorPage; import org.keycloak.testsuite.pages.LoginPage; import org.keycloak.testsuite.pages.PageUtils; @@ -54,6 +53,7 @@ import org.jboss.arquillian.graphene.page.Page; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedCondition; @@ -71,9 +71,9 @@ import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @@ -169,7 +169,7 @@ public void testProviderIdpInitiatedLogin() throws Exception { waitForPage("update account information", false); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); assertThat("We must be on consumer realm right now", driver.getCurrentUrl(), containsString("/auth/realms/" + REALM_CONS_NAME + "/")); @@ -179,12 +179,12 @@ public void testProviderIdpInitiatedLogin() throws Exception { UsersResource consumerUsers = adminClient.realm(REALM_CONS_NAME).users(); int userCount = consumerUsers.count(); - Assert.assertTrue("There must be at least one user", userCount > 0); + Assertions.assertTrue(userCount > 0, "There must be at least one user"); List users = consumerUsers.search("", 0, userCount); boolean isUserFound = users.stream().anyMatch(user -> user.getUsername().equals(CONSUMER_CHOSEN_USERNAME) && user.getEmail().equals("test@localhost")); - Assert.assertTrue("There must be user " + CONSUMER_CHOSEN_USERNAME + " in realm " + REALM_CONS_NAME, isUserFound); + Assertions.assertTrue(isUserFound, "There must be user " + CONSUMER_CHOSEN_USERNAME + " in realm " + REALM_CONS_NAME); assertThat(driver.findElement(By.tagName("a")).getAttribute("id"), containsString("account")); } @@ -203,7 +203,7 @@ public void testDisabledBroker() throws Exception { waitForPage("update account information", false); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); assertThat("We must be on consumer realm right now", driver.getCurrentUrl(), containsString("/auth/realms/" + REALM_CONS_NAME + "/")); @@ -578,7 +578,7 @@ public void testDisabledClient() { waitForPage("update account information", false); - Assert.assertTrue(updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(updateAccountInformationPage.isCurrent()); assertThat("We must be on consumer realm right now", driver.getCurrentUrl(), containsString("/auth/realms/" + REALM_CONS_NAME + "/")); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlMetadataSignedAndEncryptedBrokerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlMetadataSignedAndEncryptedBrokerTest.java index 584a80fceb97..970025752e78 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlMetadataSignedAndEncryptedBrokerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlMetadataSignedAndEncryptedBrokerTest.java @@ -48,9 +48,9 @@ import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.w3c.dom.Document; /** @@ -237,7 +237,7 @@ private void doSamlLoginError(SamlClient.Binding binding) throws ProcessingExcep .processSamlResponse(binding).build() // AuthnRequest to producer IdP .execute(currentResponse -> { // the login page should present an error because signature is invalid - Assert.assertEquals(Status.BAD_REQUEST.getStatusCode(), currentResponse.getStatusLine().getStatusCode()); + Assertions.assertEquals(Status.BAD_REQUEST.getStatusCode(), currentResponse.getStatusLine().getStatusCode()); }); events.expect(EventType.LOGIN_ERROR) diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlMetadataSignedBrokerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlMetadataSignedBrokerTest.java index 167f3b46c4c7..f4268cb5b3f1 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlMetadataSignedBrokerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlMetadataSignedBrokerTest.java @@ -37,8 +37,8 @@ import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @@ -153,7 +153,7 @@ public void testRedirectLogin() throws Exception { // manually refresh after 1d plus 20s (15s more min refresh is 10s) setTimeOffset(24*60*60 + 20); - Assert.assertTrue(adminClient.realm(bc.consumerRealmName()).identityProviders().get(bc.getIDPAlias()).reloadKeys()); + Assertions.assertTrue(adminClient.realm(bc.consumerRealmName()).identityProviders().get(bc.getIDPAlias()).reloadKeys()); doSamlRedirectLogin(Status.OK.getStatusCode(), "Update Account Information"); } } @@ -191,7 +191,7 @@ public void testRedirectLoginCacheDuration() throws Exception { // manually refresh after 1d plus 20s (15s more min refresh is 10s) setTimeOffset(3600 + 20); - Assert.assertTrue(adminClient.realm(bc.consumerRealmName()).identityProviders().get(bc.getIDPAlias()).reloadKeys()); + Assertions.assertTrue(adminClient.realm(bc.consumerRealmName()).identityProviders().get(bc.getIDPAlias()).reloadKeys()); doSamlRedirectLogin(Status.OK.getStatusCode(), "Update Account Information"); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlMultipleTabsBrokerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlMultipleTabsBrokerTest.java index c89a304b2631..11326874d646 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlMultipleTabsBrokerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlMultipleTabsBrokerTest.java @@ -30,9 +30,9 @@ import org.keycloak.testsuite.util.oauth.OAuthClient; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; @@ -73,20 +73,20 @@ public void testAuthenticationExpiredWithMoreBrowserTabs_loginExpiredInBothConsu // Open login page in tab 2 tabUtil.newTab(oauth.loginForm().build()); assertThat(tabUtil.getCountOfTabs(), Matchers.equalTo(2)); - Assert.assertTrue(loginPage.isCurrent("consumer")); + Assertions.assertTrue(loginPage.isCurrent("consumer")); getLogger().infof("URL in tab2: %s", driver.getCurrentUrl()); setTimeOffset(7200000); // Finish login in tab2 loginPage.clickSocial(bc.getIDPAlias()); - Assert.assertEquals(loginPage.getError(), "Your login attempt timed out. Login will start from the beginning."); + Assertions.assertEquals(loginPage.getError(), "Your login attempt timed out. Login will start from the beginning."); logInWithBroker(bc); waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); - Assert.assertTrue("We must be on consumer realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on consumer realm right now"); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); appPage.assertCurrent(); events.clear(); @@ -120,7 +120,7 @@ public void testAuthenticationExpiredWithMoreBrowserTabs_loginExpiredInBothConsu // Being on "You are already logged-in" now. No way to redirect to client due "clientData" are null in RelayState of SAML IDP loginPage.assertCurrent("consumer"); - Assert.assertEquals("You are already logged in.", loginPage.getInstruction()); + Assertions.assertEquals("You are already logged in.", loginPage.getInstruction()); } } @@ -142,7 +142,7 @@ public void testAuthenticationExpiredWithMoreBrowserTabs_loginExpiredInProvider( // Open login page in tab 2 tabUtil.newTab(oauth.loginForm().build()); assertThat(tabUtil.getCountOfTabs(), Matchers.equalTo(2)); - Assert.assertTrue(loginPage.isCurrent("consumer")); + Assertions.assertTrue(loginPage.isCurrent("consumer")); getLogger().infof("URL in tab2: %s", driver.getCurrentUrl()); setTimeOffset(3600); @@ -152,8 +152,8 @@ public void testAuthenticationExpiredWithMoreBrowserTabs_loginExpiredInProvider( waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); - Assert.assertTrue("We must be on consumer realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on consumer realm right now"); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); appPage.assertCurrent(); events.clear(); @@ -204,8 +204,8 @@ public void testAuthenticationExpiredWithMoreBrowserTabs_loginExpiredInProvider( // Authentication session on "consumer" realm is still valid, so no error here. appPage.assertCurrent(); AuthorizationEndpointResponse authzResponse = oauth.parseLoginResponse(); - org.keycloak.testsuite.Assert.assertNotNull(authzResponse.getCode()); - org.keycloak.testsuite.Assert.assertNull(authzResponse.getError()); + Assertions.assertNotNull(authzResponse.getCode()); + Assertions.assertNull(authzResponse.getError()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlParseIdPDescriptorTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlParseIdPDescriptorTest.java index b16423daaee5..5238f1fc059b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlParseIdPDescriptorTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlParseIdPDescriptorTest.java @@ -34,8 +34,8 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @@ -56,17 +56,17 @@ public void testIdPDescriptorParsing() throws IOException { output.addFormData("providerId", "saml", MediaType.TEXT_PLAIN_TYPE); output.addFormData("file", descriptor, MediaType.TEXT_XML_TYPE); Map response = adminClient.realm("test").identityProviders().importFrom(output); - Assert.assertNotNull(response.get(SAMLIdentityProviderConfig.SIGNING_CERTIFICATE_KEY)); - Assert.assertEquals(authServerPage.toString() + "/realms/test", response.get(SAMLIdentityProviderConfig.IDP_ENTITY_ID)); - Assert.assertEquals("true", response.get(SAMLIdentityProviderConfig.VALIDATE_SIGNATURE)); - Assert.assertEquals("true", response.get(SAMLIdentityProviderConfig.POST_BINDING_LOGOUT)); - Assert.assertEquals("true", response.get(SAMLIdentityProviderConfig.POST_BINDING_RESPONSE)); - Assert.assertEquals("true", response.get(SAMLIdentityProviderConfig.POST_BINDING_AUTHN_REQUEST)); - Assert.assertEquals("true", response.get(SAMLIdentityProviderConfig.WANT_AUTHN_REQUESTS_SIGNED)); - Assert.assertEquals(JBossSAMLURIConstants.NAMEID_FORMAT_PERSISTENT.get(), response.get("nameIDPolicyFormat")); - Assert.assertEquals(authServerPage.toString() + "/realms/test/protocol/saml", response.get(SAMLIdentityProviderConfig.SINGLE_SIGN_ON_SERVICE_URL)); - Assert.assertEquals(authServerPage.toString() + "/realms/test/protocol/saml", response.get(SAMLIdentityProviderConfig.SINGLE_LOGOUT_SERVICE_URL)); - Assert.assertEquals(authServerPage.toString() + "/realms/test/protocol/saml/resolve", response.get(SAMLIdentityProviderConfig.ARTIFACT_RESOLUTION_SERVICE_URL)); + Assertions.assertNotNull(response.get(SAMLIdentityProviderConfig.SIGNING_CERTIFICATE_KEY)); + Assertions.assertEquals(authServerPage.toString() + "/realms/test", response.get(SAMLIdentityProviderConfig.IDP_ENTITY_ID)); + Assertions.assertEquals("true", response.get(SAMLIdentityProviderConfig.VALIDATE_SIGNATURE)); + Assertions.assertEquals("true", response.get(SAMLIdentityProviderConfig.POST_BINDING_LOGOUT)); + Assertions.assertEquals("true", response.get(SAMLIdentityProviderConfig.POST_BINDING_RESPONSE)); + Assertions.assertEquals("true", response.get(SAMLIdentityProviderConfig.POST_BINDING_AUTHN_REQUEST)); + Assertions.assertEquals("true", response.get(SAMLIdentityProviderConfig.WANT_AUTHN_REQUESTS_SIGNED)); + Assertions.assertEquals(JBossSAMLURIConstants.NAMEID_FORMAT_PERSISTENT.get(), response.get("nameIDPolicyFormat")); + Assertions.assertEquals(authServerPage.toString() + "/realms/test/protocol/saml", response.get(SAMLIdentityProviderConfig.SINGLE_SIGN_ON_SERVICE_URL)); + Assertions.assertEquals(authServerPage.toString() + "/realms/test/protocol/saml", response.get(SAMLIdentityProviderConfig.SINGLE_LOGOUT_SERVICE_URL)); + Assertions.assertEquals(authServerPage.toString() + "/realms/test/protocol/saml/resolve", response.get(SAMLIdentityProviderConfig.ARTIFACT_RESOLUTION_SERVICE_URL)); // modify it with WantAuthnRequestsSigned=false descriptor = descriptor.replaceFirst("WantAuthnRequestsSigned=\"true\"", "WantAuthnRequestsSigned=\"false\""); @@ -74,8 +74,8 @@ public void testIdPDescriptorParsing() throws IOException { output.addFormData("providerId", "saml", MediaType.TEXT_PLAIN_TYPE); output.addFormData("file", descriptor, MediaType.TEXT_XML_TYPE); response = adminClient.realm("test").identityProviders().importFrom(output); - Assert.assertEquals("false", response.get(SAMLIdentityProviderConfig.WANT_AUTHN_REQUESTS_SIGNED)); - Assert.assertEquals("true", response.get(SAMLIdentityProviderConfig.VALIDATE_SIGNATURE)); + Assertions.assertEquals("false", response.get(SAMLIdentityProviderConfig.WANT_AUTHN_REQUESTS_SIGNED)); + Assertions.assertEquals("true", response.get(SAMLIdentityProviderConfig.VALIDATE_SIGNATURE)); } private String readSamlIdPDescriptor() throws IOException { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlSpDescriptorTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlSpDescriptorTest.java index f4e59c77f83b..afa26b40a50b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlSpDescriptorTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlSpDescriptorTest.java @@ -36,8 +36,8 @@ import com.google.common.collect.ImmutableMap; import org.apache.tools.ant.filters.StringInputStream; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.util.KeyUtils.generateNewRealmKey; @@ -47,7 +47,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class KcSamlSpDescriptorTest extends AbstractBrokerTest { @@ -206,8 +206,8 @@ public void testAttributeConsumingServiceAttributeRoleMapperInSpMetadataWithServ public void testKeysDescriptors() throws IOException, ParsingException, URISyntaxException { // No keys by default SPSSODescriptorType spDescriptor = getExportedSamlProvider(); - Assert.assertNotNull("KeyDescriptor is null", spDescriptor.getKeyDescriptor()); - Assert.assertEquals("KeyDescriptor.size", 0, spDescriptor.getKeyDescriptor().size()); + Assertions.assertNotNull(spDescriptor.getKeyDescriptor(), "KeyDescriptor is null"); + Assertions.assertEquals(0, spDescriptor.getKeyDescriptor().size(), "KeyDescriptor.size"); // Enable signing for IDP. Only signing key is present try (Closeable idpUpdater = new IdentityProviderAttributeUpdater(identityProviderResource) @@ -215,10 +215,10 @@ public void testKeysDescriptors() throws IOException, ParsingException, URISynta .update()) { spDescriptor = getExportedSamlProvider(); - Assert.assertEquals("KeyDescriptor.size", 1, spDescriptor.getKeyDescriptor().size()); + Assertions.assertEquals(1, spDescriptor.getKeyDescriptor().size(), "KeyDescriptor.size"); Map certs = convertCerts(spDescriptor); - Assert.assertEquals(1, certs.size()); - Assert.assertNotNull(certs.get("signing")); + Assertions.assertEquals(1, certs.size()); + Assertions.assertNotNull(certs.get("signing")); } // Enable signing and encryption. Both keys are present and mapped to same realm key @@ -228,14 +228,14 @@ public void testKeysDescriptors() throws IOException, ParsingException, URISynta .update()) { spDescriptor = getExportedSamlProvider(); - Assert.assertEquals("KeyDescriptor.size", 2, spDescriptor.getKeyDescriptor().size()); + Assertions.assertEquals(2, spDescriptor.getKeyDescriptor().size(), "KeyDescriptor.size"); Map certs = convertCerts(spDescriptor); - Assert.assertEquals(2, certs.size()); + Assertions.assertEquals(2, certs.size()); String signingCert = certs.get("signing"); String encCert = certs.get("encryption"); - Assert.assertNotNull(signingCert); - Assert.assertNotNull(encCert); - Assert.assertNotEquals(signingCert, encCert); + Assertions.assertNotNull(signingCert); + Assertions.assertNotNull(encCert); + Assertions.assertNotEquals(signingCert, encCert); hasEncAlgorithms(spDescriptor, SAMLEncryptionAlgorithms.RSA_OAEP.getXmlEncIdentifiers()); } @@ -247,14 +247,14 @@ public void testKeysDescriptors() throws IOException, ParsingException, URISynta .update()) { spDescriptor = getExportedSamlProvider(); - Assert.assertEquals("KeyDescriptor.size", 2, spDescriptor.getKeyDescriptor().size()); + Assertions.assertEquals(2, spDescriptor.getKeyDescriptor().size(), "KeyDescriptor.size"); Map certs = convertCerts(spDescriptor); - Assert.assertEquals(2, certs.size()); + Assertions.assertEquals(2, certs.size()); String signingCert = certs.get("signing"); String encCert = certs.get("encryption"); - Assert.assertNotNull(signingCert); - Assert.assertNotNull(encCert); - Assert.assertNotEquals(signingCert, encCert); + Assertions.assertNotNull(signingCert); + Assertions.assertNotNull(encCert); + Assertions.assertNotEquals(signingCert, encCert); hasEncAlgorithms(spDescriptor, SAMLEncryptionAlgorithms.RSA_OAEP.getXmlEncIdentifiers()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlUsernameTemplateMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlUsernameTemplateMapperTest.java index c8ff78953b46..80439e3379fc 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlUsernameTemplateMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcSamlUsernameTemplateMapperTest.java @@ -9,11 +9,11 @@ import org.keycloak.representations.idm.IdentityProviderMapperRepresentation; import org.keycloak.representations.idm.IdentityProviderRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.WaitUtils; import com.google.common.collect.ImmutableMap; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.broker.saml.mappers.UsernameTemplateMapper.PROVIDER_ID; @@ -72,19 +72,19 @@ public void testLoginWithMissingMappedAttributeShouldFail() { logInAsUserInIDP(); WaitUtils.waitForPageToLoad(); - Assert.assertTrue("Should be on update profile page", updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(updateAccountInformationPage.isCurrent(), "Should be on update profile page"); // try to update the account info with only the first and last name (no username provided here). updateAccountInformationPage.updateAccountInformation("John", "Doe"); // we should still be in the update profile page, with an error asking to provide the username - Assert.assertTrue("Should still be on update profile page", updateAccountInformationPage.isCurrent()); - Assert.assertTrue("Should show error about missing username", driver.getPageSource().contains("Please specify username")); + Assertions.assertTrue(updateAccountInformationPage.isCurrent(), "Should still be on update profile page"); + Assertions.assertTrue(driver.getPageSource().contains("Please specify username"), "Should show error about missing username"); // no user should be present in the realm with an empty or null username List users = adminClient.realm(bc.consumerRealmName()).users().list(); for (UserRepresentation user : users) { - Assert.assertNotNull("Username should not be null", user.getUsername()); - Assert.assertFalse("Username should not be empty", user.getUsername().trim().isEmpty()); + Assertions.assertNotNull(user.getUsername(), "Username should not be null"); + Assertions.assertFalse(user.getUsername().trim().isEmpty(), "Username should not be empty"); } } @@ -113,19 +113,19 @@ public void testLoginWithPartiallyMissingAttributeInTemplate() { logInAsUserInIDP(); WaitUtils.waitForPageToLoad(); - Assert.assertTrue("Should be on update profile page", updateAccountInformationPage.isCurrent()); + Assertions.assertTrue(updateAccountInformationPage.isCurrent(), "Should be on update profile page"); // try to update with only first and last name (no username) - should fail updateAccountInformationPage.updateAccountInformation("John", "Doe"); - Assert.assertTrue("Should still be on update profile page", updateAccountInformationPage.isCurrent()); - Assert.assertTrue("Should show error about missing username", driver.getPageSource().contains("Please specify username")); + Assertions.assertTrue(updateAccountInformationPage.isCurrent(), "Should still be on update profile page"); + Assertions.assertTrue(driver.getPageSource().contains("Please specify username"), "Should show error about missing username"); // now provide a username and verify the user is created updateAccountInformationPage.updateAccountInformation("valid-username", "user@example.com", "John", "Doe"); - Assert.assertFalse("Should not be on update profile page", updateAccountInformationPage.isCurrent()); + Assertions.assertFalse(updateAccountInformationPage.isCurrent(), "Should not be on update profile page"); UserRepresentation user = adminClient.realm(bc.consumerRealmName()).users().search("valid-username").get(0); - Assert.assertNotNull(user); - Assert.assertEquals("valid-username", user.getUsername()); + Assertions.assertNotNull(user); + Assertions.assertEquals("valid-username", user.getUsername()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/OAuth2BrokerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/OAuth2BrokerTest.java index 8fddb39cb02c..f64a6cf52f0f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/OAuth2BrokerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/OAuth2BrokerTest.java @@ -17,10 +17,10 @@ import org.keycloak.representations.idm.IdentityProviderRepresentation; import org.keycloak.representations.idm.ProtocolMapperRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; import org.junit.Ignore; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * Final class as it's not intended to be overriden. Feel free to remove "final" if you really know what you are doing. @@ -70,18 +70,18 @@ public void testLoginDefaultConfiguration() { logInWithBroker(bc); updateAccountInformationPage.assertCurrent(); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); List users = adminClient.realm(bc.consumerRealmName()).users().search(bc.getUserLogin()); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); UserRepresentation user = users.get(0); - Assert.assertEquals(bc.getUserLogin(), user.getUsername()); - Assert.assertEquals(bc.getUserEmail(), user.getEmail()); - Assert.assertEquals("Firstname", user.getFirstName()); - Assert.assertEquals("Lastname", user.getLastName()); + Assertions.assertEquals(bc.getUserLogin(), user.getUsername()); + Assertions.assertEquals(bc.getUserEmail(), user.getEmail()); + Assertions.assertEquals("Firstname", user.getFirstName()); + Assertions.assertEquals("Lastname", user.getLastName()); } @Test @@ -98,12 +98,12 @@ public void testFetchUserProfileClaims() { logInWithBroker(bc); List users = adminClient.realm(bc.consumerRealmName()).users().search("username-claim"); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); UserRepresentation user = users.get(0); - Assert.assertEquals("username-claim", user.getUsername()); - Assert.assertEquals("email-claim@keycloak.org", user.getEmail()); - Assert.assertEquals("my", user.getFirstName()); - Assert.assertEquals("user", user.getLastName()); + Assertions.assertEquals("username-claim", user.getUsername()); + Assertions.assertEquals("email-claim@keycloak.org", user.getEmail()); + Assertions.assertEquals("my", user.getFirstName()); + Assertions.assertEquals("user", user.getLastName()); } @Test @@ -118,9 +118,9 @@ private void assertMandatorySetting(String key, String errorMessage) { try { broker.getConfig().remove(key); brokerResource.update(broker); - Assert.fail(key + " must be mandatory"); + Assertions.fail(key + " must be mandatory"); } catch (BadRequestException bre) { - Assert.assertTrue(bre.getResponse().readEntity(String.class).contains(errorMessage)); + Assertions.assertTrue(bre.getResponse().readEntity(String.class).contains(errorMessage)); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/SocialLoginTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/SocialLoginTest.java index 6d94bd6593d2..f0e0b661ef5d 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/SocialLoginTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/SocialLoginTest.java @@ -65,11 +65,11 @@ import org.jboss.arquillian.graphene.Graphene; import org.jboss.arquillian.graphene.page.Page; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; @@ -92,10 +92,10 @@ import static org.keycloak.testsuite.broker.SocialLoginTest.Provider.STACKOVERFLOW; import static org.keycloak.testsuite.broker.SocialLoginTest.Provider.TWITTER; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stian Thorgersen @@ -600,7 +600,7 @@ private AccessTokenResponse checkFeature(int expectedStatusCode, String username .param(OAuth2Constants.REQUESTED_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE) .param(OAuth2Constants.REQUESTED_ISSUER, currentTestProvider.id()) )); - Assert.assertEquals(expectedStatusCode, response.getStatus()); + Assertions.assertEquals(expectedStatusCode, response.getStatus()); if (expectedStatusCode == Response.Status.OK.getStatusCode()) return response.readEntity(AccessTokenResponse.class); else @@ -614,7 +614,7 @@ private AccessTokenResponse checkFeature(int expectedStatusCode, String username protected void testTokenExchange() { List users = adminClient.realm(REALM).users().search(null, null, null); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); String username = users.get(0).getUsername(); checkFeature(400, username); @@ -625,15 +625,15 @@ protected void testTokenExchange() { try { AccessTokenResponse tokenResponse = checkFeature(200, username); - Assert.assertNotNull(tokenResponse); + Assertions.assertNotNull(tokenResponse); String socialToken = tokenResponse.getToken(); - Assert.assertNotNull(socialToken); + Assertions.assertNotNull(socialToken); // remove all users removeUser(); users = adminClient.realm(REALM).users().search(null, null, null); - Assert.assertEquals(0, users.size()); + Assertions.assertEquals(0, users.size()); // now try external exchange where we trust social provider and import the external token. Response response = getExchangeUrl(httpClient).request() @@ -645,19 +645,19 @@ protected void testTokenExchange() { .param(OAuth2Constants.SUBJECT_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE) .param(OAuth2Constants.SUBJECT_ISSUER, currentTestProvider.id()) )); - Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); response.close(); users = adminClient.realm(REALM).users().search(null, null, null); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); - Assert.assertEquals(username, users.get(0).getUsername()); + Assertions.assertEquals(username, users.get(0).getUsername()); // remove all users removeUser(); users = adminClient.realm(REALM).users().search(null, null, null); - Assert.assertEquals(0, users.size()); + Assertions.assertEquals(0, users.size()); ///// Test that we can update social token from session with stored tokens turned off. @@ -676,7 +676,7 @@ protected void testTokenExchange() { .param(OAuth2Constants.SUBJECT_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE) .param(OAuth2Constants.SUBJECT_ISSUER, currentTestProvider.id()) )); - Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); tokenResponse = response.readEntity(AccessTokenResponse.class); String keycloakToken = tokenResponse.getToken(); response.close(); @@ -692,11 +692,11 @@ protected void testTokenExchange() { .param(OAuth2Constants.REQUESTED_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE) .param(OAuth2Constants.REQUESTED_ISSUER, currentTestProvider.id()) )); - Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); tokenResponse = response.readEntity(AccessTokenResponse.class); response.close(); - Assert.assertEquals(socialToken, tokenResponse.getToken()); + Assertions.assertEquals(socialToken, tokenResponse.getToken()); // turn on store token idp = adminClient.realm(REALM).identityProviders().get(currentTestProvider.id).toRepresentation(); idp.setStoreToken(true); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/UsernameTemplateMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/UsernameTemplateMapperTest.java index c33efc120d3e..737815042924 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/UsernameTemplateMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/UsernameTemplateMapperTest.java @@ -15,7 +15,7 @@ import static org.keycloak.testsuite.broker.BrokerTestTools.getConsumerRoot; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class UsernameTemplateMapperTest extends AbstractBaseBrokerTest { @@ -84,9 +84,9 @@ public void userAttributeShouldBeDerivedFromIdpSubClaim() { UserRepresentation user = adminClient.realm(bc.consumerRealmName()).users().search(bc.getUserEmail(), 0, 1).get(0); - assertEquals("Should render idpSub as mappedSub attribute", idpUserId, user.getAttributes().get("mappedSub").get(0)); + assertEquals(idpUserId, user.getAttributes().get("mappedSub").get(0), "Should render idpSub as mappedSub attribute"); String username = user.getUsername(); - assertEquals("Should render alias:sub as Username", bc.getIDPAlias() + "_" + idpUserId, username); + assertEquals(bc.getIDPAlias() + "_" + idpUserId, username, "Should render alias:sub as Username"); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/AbstractCliTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/AbstractCliTest.java index 941d310e0c44..f702b3d58ed3 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/AbstractCliTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/AbstractCliTest.java @@ -8,7 +8,7 @@ import org.keycloak.testsuite.arquillian.AuthServerTestEnricher; import org.keycloak.testsuite.cli.exec.AbstractExec; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; /** * @author Marko Strukelj @@ -42,7 +42,7 @@ public void assertExitCodeAndStdErrSize(AbstractExec exe, int exitCode, int stdE } public void assertExitCodeAndStreamSizes(AbstractExec exe, int exitCode, int stdOutLineCount, int stdErrLineCount) { - Assert.assertEquals("exitCode == " + exitCode, exitCode, exe.exitCode()); + Assertions.assertEquals(exitCode, exe.exitCode(), "exitCode == " + exitCode); if (stdOutLineCount != -1) { assertLineCount("STDOUT: " + exe.stdoutString(), exe.stdoutLines(), stdOutLineCount); } @@ -63,7 +63,7 @@ private void assertLineCount(String label, List lines, int count) { return; } } - Assert.assertTrue(label + " has " + lines.size() + " lines (expected: " + count + ")", lines.size() == count); + Assertions.assertTrue(lines.size() == count, label + " has " + lines.size() + " lines (expected: " + count + ")"); } private boolean isFipsDisabled() { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/AbstractAdmCliTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/AbstractAdmCliTest.java index 17567369d0ba..bff718413d9e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/AbstractAdmCliTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/AbstractAdmCliTest.java @@ -27,7 +27,7 @@ import org.keycloak.testsuite.util.UserBuilder; import org.keycloak.util.JsonSerialization; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.cli.KcAdmExec.WORK_DIR; @@ -134,13 +134,13 @@ void assertFieldsEqualWithExclusions(ConfigData config1, ConfigData config2, Str HashSet exclusions = new HashSet<>(Arrays.asList(excluded)); if (!exclusions.contains("serverUrl")) { - Assert.assertEquals("serverUrl", config1.getServerUrl(), config2.getServerUrl()); + Assertions.assertEquals(config1.getServerUrl(), config2.getServerUrl(), "serverUrl"); } if (!exclusions.contains("realm")) { - Assert.assertEquals("realm", config1.getRealm(), config2.getRealm()); + Assertions.assertEquals(config1.getRealm(), config2.getRealm(), "realm"); } if (!exclusions.contains("truststore")) { - Assert.assertEquals("truststore", config1.getTruststore(), config2.getTruststore()); + Assertions.assertEquals(config1.getTruststore(), config2.getTruststore(), "truststore"); } if (!exclusions.contains("endpoints")) { Map> endp1 = config1.getEndpoints(); @@ -156,7 +156,7 @@ void assertFieldsEqualWithExclusions(ConfigData config1, ConfigData config2, Str String serverUrl = ent1.getKey(); String endpskey = "endpoints." + serverUrl; if (!exclusions.contains(endpskey)) { - Assert.assertEquals(endpskey, ent1.getKey(), ent2.getKey()); + Assertions.assertEquals(ent1.getKey(), ent2.getKey(), endpskey); Map realms1 = ent1.getValue(); Map realms2 = ent2.getValue(); @@ -171,7 +171,7 @@ void assertFieldsEqualWithExclusions(ConfigData config1, ConfigData config2, Str String realm = rent1.getKey(); String rkey = endpskey + "." + realm; if (!exclusions.contains(endpskey)) { - Assert.assertEquals(rkey, rent1.getKey(), rent2.getKey()); + Assertions.assertEquals(rent1.getKey(), rent2.getKey(), rkey); RealmConfigData rdata1 = rent1.getValue(); RealmConfigData rdata2 = rent2.getValue(); @@ -195,52 +195,52 @@ void assertFieldsEqualWithExclusions(String server, String realm, RealmConfigDat String ekey = pfix + "serverUrl"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.serverUrl(), data2.serverUrl()); + Assertions.assertEquals(data1.serverUrl(), data2.serverUrl(), ekey); } ekey = pfix + "realm"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.realm(), data2.realm()); + Assertions.assertEquals(data1.realm(), data2.realm(), ekey); } ekey = pfix + "clientId"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.getClientId(), data2.getClientId()); + Assertions.assertEquals(data1.getClientId(), data2.getClientId(), ekey); } ekey = pfix + "token"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.getToken(), data2.getToken()); + Assertions.assertEquals(data1.getToken(), data2.getToken(), ekey); } ekey = pfix + "refreshToken"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.getRefreshToken(), data2.getRefreshToken()); + Assertions.assertEquals(data1.getRefreshToken(), data2.getRefreshToken(), ekey); } ekey = pfix + "expiresAt"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.getExpiresAt(), data2.getExpiresAt()); + Assertions.assertEquals(data1.getExpiresAt(), data2.getExpiresAt(), ekey); } ekey = pfix + "refreshExpiresAt"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.getRefreshExpiresAt(), data2.getRefreshExpiresAt()); + Assertions.assertEquals(data1.getRefreshExpiresAt(), data2.getRefreshExpiresAt(), ekey); } ekey = pfix + "secret"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.getSecret(), data2.getSecret()); + Assertions.assertEquals(data1.getSecret(), data2.getSecret(), ekey); } ekey = pfix + "signingToken"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.getSigningToken(), data2.getSigningToken()); + Assertions.assertEquals(data1.getSigningToken(), data2.getSigningToken(), ekey); } ekey = pfix + "sigExpiresAt"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.getSigExpiresAt(), data2.getSigExpiresAt()); + Assertions.assertEquals(data1.getSigExpiresAt(), data2.getSigExpiresAt(), ekey); } } @@ -253,14 +253,14 @@ void testCRUDWithOnTheFlyAuth(String serverUrl, String credentials, String extra KcAdmExec exe = execute("create clients --no-config --server " + serverUrl + " --realm test " + credentials + " " + extraOptions + " -s clientId=test-client -o"); - Assert.assertEquals("exitCode == 0", 0, exe.exitCode()); - Assert.assertTrue("login message expected. But the messages are: " + exe.stderrLines(), exe.stderrLines().stream().anyMatch(message -> message.equals(loginMessage))); + Assertions.assertEquals(0, exe.exitCode(), "exitCode == 0"); + Assertions.assertTrue(exe.stderrLines().stream().anyMatch(message -> message.equals(loginMessage)), "login message expected. But the messages are: " + exe.stderrLines()); ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("clientId", "test-client", client.getClientId()); + Assertions.assertEquals("test-client", client.getClientId(), "clientId"); long lastModified2 = configFile.exists() ? configFile.lastModified() : 0; - Assert.assertEquals("config file not modified", lastModified, lastModified2); + Assertions.assertEquals(lastModified, lastModified2, "config file not modified"); @@ -270,10 +270,10 @@ void testCRUDWithOnTheFlyAuth(String serverUrl, String credentials, String extra assertExitCodeAndStdErrSize(exe, 0, 1); ClientRepresentation client2 = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("clientId", "test-client", client2.getClientId()); + Assertions.assertEquals("test-client", client2.getClientId(), "clientId"); lastModified2 = configFile.exists() ? configFile.lastModified() : 0; - Assert.assertEquals("config file not modified", lastModified, lastModified2); + Assertions.assertEquals(lastModified, lastModified2, "config file not modified"); @@ -284,11 +284,11 @@ void testCRUDWithOnTheFlyAuth(String serverUrl, String credentials, String extra assertExitCodeAndStdErrSize(exe, 0, 1); ClientRepresentation client4 = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("clientId", "test-client", client4.getClientId()); - Assert.assertFalse("enabled", client4.isEnabled()); + Assertions.assertEquals("test-client", client4.getClientId(), "clientId"); + Assertions.assertFalse(client4.isEnabled(), "enabled"); lastModified2 = configFile.exists() ? configFile.lastModified() : 0; - Assert.assertEquals("config file not modified", lastModified, lastModified2); + Assertions.assertEquals(lastModified, lastModified2, "config file not modified"); @@ -299,7 +299,7 @@ void testCRUDWithOnTheFlyAuth(String serverUrl, String credentials, String extra assertExitCodeAndStreamSizes(exe, 0, 0, 1 - linecountOffset); lastModified2 = configFile.exists() ? configFile.lastModified() : 0; - Assert.assertEquals("config file not modified", lastModified, lastModified2); + Assertions.assertEquals(lastModified, lastModified2, "config file not modified"); @@ -309,10 +309,10 @@ void testCRUDWithOnTheFlyAuth(String serverUrl, String credentials, String extra assertExitCodeAndStreamSizes(exe, 1, 0, 2 - linecountOffset); String resourceUri = serverUrl + "/admin/realms/test/clients/" + client.getId(); - Assert.assertEquals("error message", "Resource not found for url: " + resourceUri, exe.stderrLines().get(exe.stderrLines().size() - 1)); + Assertions.assertEquals("Resource not found for url: " + resourceUri, exe.stderrLines().get(exe.stderrLines().size() - 1), "error message"); lastModified2 = configFile.exists() ? configFile.lastModified() : 0; - Assert.assertEquals("config file not modified", lastModified, lastModified2); + Assertions.assertEquals(lastModified, lastModified2, "config file not modified"); } File initTempFile(String extension) throws IOException { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmCreateTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmCreateTest.java index 0fa713d21a88..ead22a6a2d1d 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmCreateTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmCreateTest.java @@ -12,8 +12,8 @@ import org.keycloak.testsuite.util.TempFileResource; import org.keycloak.util.JsonSerialization; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.cli.KcAdmExec.execute; @@ -56,7 +56,7 @@ public void testCreateIDPWithoutSyncMode() throws IOException { } // If the sync mode is not present on creating the idp, it will never be stored automatically. However, the model will always report behaviour as "LEGACY", so no errors should occur. - Assert.assertNull(realmResource.identityProviders().get("idpAlias").toRepresentation().getConfig().get(IdentityProviderModel.SYNC_MODE)); + Assertions.assertNull(realmResource.identityProviders().get("idpAlias").toRepresentation().getConfig().get(IdentityProviderModel.SYNC_MODE)); } @Test @@ -97,20 +97,20 @@ public void testCreateThoroughly() throws IOException { assertExitCodeAndStdErrSize(exe, 0, 0); ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertNotNull("id", client.getId()); - Assert.assertEquals("clientId", "my_client", client.getClientId()); - Assert.assertEquals("enabled", true, client.isEnabled()); - Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris()); - Assert.assertEquals("serviceAccountsEnabled", true, client.isServiceAccountsEnabled()); - Assert.assertEquals("name", "My Client App", client.getName()); - Assert.assertEquals("implicitFlowEnabled", false, client.isImplicitFlowEnabled()); - Assert.assertEquals("publicClient", true, client.isPublicClient()); + Assertions.assertNotNull(client.getId(), "id"); + Assertions.assertEquals("my_client", client.getClientId(), "clientId"); + Assertions.assertEquals(true, client.isEnabled(), "enabled"); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris(), "redirectUris"); + Assertions.assertEquals(true, client.isServiceAccountsEnabled(), "serviceAccountsEnabled"); + Assertions.assertEquals("My Client App", client.getName(), "name"); + Assertions.assertEquals(false, client.isImplicitFlowEnabled(), "implicitFlowEnabled"); + Assertions.assertEquals(true, client.isPublicClient(), "publicClient"); // note there is no server-side check if protocol is supported - Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8980/myapp"), client.getWebOrigins()); - Assert.assertEquals("consentRequired", false, client.isConsentRequired()); - Assert.assertEquals("baseUrl", "http://localhost:8980/myapp", client.getBaseUrl()); - Assert.assertEquals("bearerOnly", true, client.isStandardFlowEnabled()); - Assert.assertNull("mappers are not empty", client.getProtocolMappers()); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp"), client.getWebOrigins(), "webOrigins"); + Assertions.assertEquals(false, client.isConsentRequired(), "consentRequired"); + Assertions.assertEquals("http://localhost:8980/myapp", client.getBaseUrl(), "baseUrl"); + Assertions.assertEquals(true, client.isStandardFlowEnabled(), "bearerOnly"); + Assertions.assertNull(client.getProtocolMappers(), "mappers are not empty"); // create configuration from file as a template and override clientId and other attributes ... output an object exe = execute("create clients --config '" + configFile.getName() + "' -o -f '" + tmpFile.getName() + @@ -121,20 +121,20 @@ public void testCreateThoroughly() throws IOException { assertExitCodeAndStdErrSize(exe, 0, 0); ClientRepresentation client2 = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertNotNull("id", client2.getId()); - Assert.assertEquals("clientId", "my_client2", client2.getClientId()); - Assert.assertEquals("enabled", false, client2.isEnabled()); - Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8980/myapp2/*"), client2.getRedirectUris()); - Assert.assertEquals("serviceAccountsEnabled", true, client2.isServiceAccountsEnabled()); - Assert.assertEquals("name", "My Client App II", client2.getName()); - Assert.assertEquals("implicitFlowEnabled", false, client2.isImplicitFlowEnabled()); - Assert.assertEquals("publicClient", true, client2.isPublicClient()); - Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8980/myapp2"), client2.getWebOrigins()); - Assert.assertEquals("consentRequired", false, client2.isConsentRequired()); - Assert.assertEquals("baseUrl", "http://localhost:8980/myapp2", client2.getBaseUrl()); - Assert.assertEquals("rootUrl", "http://localhost:8980/myapp2", client2.getRootUrl()); - Assert.assertEquals("bearerOnly", true, client2.isStandardFlowEnabled()); - Assert.assertNull("mappers are not empty", client2.getProtocolMappers()); + Assertions.assertNotNull(client2.getId(), "id"); + Assertions.assertEquals("my_client2", client2.getClientId(), "clientId"); + Assertions.assertEquals(false, client2.isEnabled(), "enabled"); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp2/*"), client2.getRedirectUris(), "redirectUris"); + Assertions.assertEquals(true, client2.isServiceAccountsEnabled(), "serviceAccountsEnabled"); + Assertions.assertEquals("My Client App II", client2.getName(), "name"); + Assertions.assertEquals(false, client2.isImplicitFlowEnabled(), "implicitFlowEnabled"); + Assertions.assertEquals(true, client2.isPublicClient(), "publicClient"); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp2"), client2.getWebOrigins(), "webOrigins"); + Assertions.assertEquals(false, client2.isConsentRequired(), "consentRequired"); + Assertions.assertEquals("http://localhost:8980/myapp2", client2.getBaseUrl(), "baseUrl"); + Assertions.assertEquals("http://localhost:8980/myapp2", client2.getRootUrl(), "rootUrl"); + Assertions.assertEquals(true, client2.isStandardFlowEnabled(), "bearerOnly"); + Assertions.assertNull(client2.getProtocolMappers(), "mappers are not empty"); } // simple create, output an id @@ -146,7 +146,7 @@ public void testCreateThoroughly() throws IOException { exe = execute("create clients --config '" + configFile.getName() + "' -s clientId=my_client4"); assertExitCodeAndStreamSizes(exe, 0, 0, 1); - Assert.assertTrue("only id returned", exe.stderrLines().get(exe.stderrLines().size() - 1).startsWith("Created new client with id '")); + Assertions.assertTrue(exe.stderrLines().get(exe.stderrLines().size() - 1).startsWith("Created new client with id '"), "only id returned"); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmSessionTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmSessionTest.java index 94ba0b6500b6..69aeed489322 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmSessionTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmSessionTest.java @@ -12,16 +12,16 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.node.ObjectNode; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.cli.KcAdmExec.execute; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Marko Strukelj @@ -45,7 +45,7 @@ public void test() throws IOException { KcAdmExec exe = execute("create realms --config '" + configFile.getName() + "' -s realm=demorealm -s enabled=true"); assertExitCodeAndStreamSizes(exe, 0, 0, 1); - Assert.assertTrue(exe.stderrLines().get(exe.stderrLines().size() - 1).startsWith("Created ")); + Assertions.assertTrue(exe.stderrLines().get(exe.stderrLines().size() - 1).startsWith("Created ")); // create user exe = execute("create users --config '" + configFile.getName() + "' -r demorealm -s username=testuser -s firstName=testuser -s lastName=testuser -s email=testuser@keycloak.org -s enabled=true -i"); @@ -90,7 +90,7 @@ public void test() throws IOException { assertExitCodeAndStdErrSize(exe, 0, 0); ObjectNode role = loadJson(exe.stdout(), ObjectNode.class); - Assert.assertEquals("testrole", role.get("name").asText()); + Assertions.assertEquals("testrole", role.get("name").asText()); String roleId = role.get("id").asText(); // get realm roles again @@ -111,7 +111,7 @@ public void test() throws IOException { exe = execute("create clients/" + idOfClient + "/roles --config '" + configFile.getName() + "' -s name=clientrole -s 'description=Test client role'"); assertExitCodeAndStreamSizes(exe, 0, 0, 1); - Assert.assertTrue(exe.stderrLines().get(exe.stderrLines().size() - 1).startsWith("Created ")); + Assertions.assertTrue(exe.stderrLines().get(exe.stderrLines().size() - 1).startsWith("Created ")); // make sure client role has been created exe = execute("get-roles --config '" + configFile.getName() + "' --cclientid testclient"); @@ -119,7 +119,7 @@ public void test() throws IOException { assertExitCodeAndStdErrSize(exe, 0, 0); roles = loadJson(exe.stdout(), LIST_OF_JSON); assertThat("expected one role", roles.size(), equalTo(1)); - Assert.assertEquals("clientrole", roles.get(0).get("name").asText()); + Assertions.assertEquals("clientrole", roles.get(0).get("name").asText()); // add created role to user - we are realm admin so we can add role to ourself exe = execute("add-roles --config '" + configFile.getName() + "' --uusername testuser --cclientid testclient --rolename clientrole"); @@ -132,25 +132,25 @@ public void test() throws IOException { assertExitCodeAndStdErrSize(exe, 0, 0); ObjectNode node = loadJson(exe.stdout(), ObjectNode.class); - Assert.assertNotNull(node.get("realmMappings")); + Assertions.assertNotNull(node.get("realmMappings")); List realmMappings = StreamSupport.stream(node.get("realmMappings").spliterator(), false) .map(o -> o.get("name").asText()).sorted().collect(Collectors.toList()); - Assert.assertEquals(Arrays.asList("default-roles-demorealm"), realmMappings); + Assertions.assertEquals(Arrays.asList("default-roles-demorealm"), realmMappings); ObjectNode clientRoles = (ObjectNode) node.get("clientMappings"); //List fields = asSortedList(clientRoles.fieldNames()); List fields = StreamSupport.stream(clientRoles.spliterator(), false) .map(o -> o.get("client").asText()).sorted().collect(Collectors.toList()); - Assert.assertEquals(Arrays.asList("realm-management", "testclient"), fields); + Assertions.assertEquals(Arrays.asList("realm-management", "testclient"), fields); realmMappings = StreamSupport.stream(clientRoles.get("realm-management").get("mappings").spliterator(), false) .map(o -> o.get("name").asText()).sorted().collect(Collectors.toList()); - Assert.assertEquals(Arrays.asList("realm-admin"), realmMappings); + Assertions.assertEquals(Arrays.asList("realm-admin"), realmMappings); realmMappings = StreamSupport.stream(clientRoles.get("testclient").get("mappings").spliterator(), false) .map(o -> o.get("name").asText()).sorted().collect(Collectors.toList()); - Assert.assertEquals(Arrays.asList("clientrole"), realmMappings); + Assertions.assertEquals(Arrays.asList("clientrole"), realmMappings); @@ -165,11 +165,11 @@ public void test() throws IOException { assertExitCodeAndStdErrSize(exe, 0, 0); node = loadJson(exe.stdout(), ObjectNode.class); - Assert.assertNotNull(node.get("realmMappings")); + Assertions.assertNotNull(node.get("realmMappings")); realmMappings = StreamSupport.stream(node.get("realmMappings").spliterator(), false) .map(o -> o.get("name").asText()).sorted().collect(Collectors.toList()); - Assert.assertEquals(Arrays.asList("default-roles-demorealm", "testrole"), realmMappings); + Assertions.assertEquals(Arrays.asList("default-roles-demorealm", "testrole"), realmMappings); // create a group exe = execute("create groups --config '" + configFile.getName() + "' -s name=TestUsers -i"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmTest.java index 5f0123c614d7..a3a707601449 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmTest.java @@ -16,8 +16,8 @@ import org.keycloak.testsuite.util.TempFileResource; import org.keycloak.util.JsonSerialization; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.client.admin.cli.KcAdmMain.CMD; import static org.keycloak.client.cli.util.OsUtil.EOL; @@ -36,7 +36,7 @@ public void testBadCommand() { KcAdmExec exe = execute("nonexistent"); assertExitCodeAndStreamSizes(exe, 2, 0, 3); - Assert.assertEquals("stderr first line", "Unmatched argument at index 0: 'nonexistent'", exe.stderrLines().get(0)); + Assertions.assertEquals("Unmatched argument at index 0: 'nonexistent'", exe.stderrLines().get(0), "stderr first line"); } @@ -50,10 +50,10 @@ public void testNoArgs() { assertExitCodeAndStdErrSize(exe, 2, 0); List lines = exe.stdoutLines(); - Assert.assertTrue("stdout output not empty", lines.size() > 0); - Assert.assertEquals("stdout first line", "Keycloak Admin CLI", lines.get(0)); - Assert.assertEquals("stdout one but last line", "Use '" + CMD + " help ' for more information about a given command.", lines.get(lines.size() - 2)); - Assert.assertEquals("stdout last line", "", lines.get(lines.size() - 1)); + Assertions.assertTrue(lines.size() > 0, "stdout output not empty"); + Assertions.assertEquals("Keycloak Admin CLI", lines.get(0), "stdout first line"); + Assertions.assertEquals("Use '" + CMD + " help ' for more information about a given command.", lines.get(lines.size() - 2), "stdout one but last line"); + Assertions.assertEquals("", lines.get(lines.size() - 1), "stdout last line"); /* @@ -61,42 +61,42 @@ public void testNoArgs() { */ exe = KcAdmExec.execute("config"); assertExitCodeAndStreamSizes(exe, 2, 8, 0); - Assert.assertEquals("error message", - "Usage: " + CMD + " config SUB_COMMAND [ARGUMENTS]", - exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " config SUB_COMMAND [ARGUMENTS]", + exe.stdoutLines().get(0), + "error message"); exe = KcAdmExec.execute("config credentials"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", " " + CMD + " config credentials --server SERVER_URL --realm REALM --user USER [--password PASSWORD] [ARGUMENTS]", exe.stdoutLines().get(1)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals(" " + CMD + " config credentials --server SERVER_URL --realm REALM --user USER [--password PASSWORD] [ARGUMENTS]", exe.stdoutLines().get(1), "help message"); exe = KcAdmExec.execute("config truststore"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", "Usage: " + CMD + " config truststore [TRUSTSTORE | --delete] [--trustpass PASSWORD] [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals("Usage: " + CMD + " config truststore [TRUSTSTORE | --delete] [--trustpass PASSWORD] [ARGUMENTS]", exe.stdoutLines().get(0), "help message"); exe = KcAdmExec.execute("create"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", "Usage: " + CMD + " create ENDPOINT_URI [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals("Usage: " + CMD + " create ENDPOINT_URI [ARGUMENTS]", exe.stdoutLines().get(0), "help message"); //Assert.assertEquals("error message", "No file nor attribute values specified", exe.stderrLines().get(0)); exe = KcAdmExec.execute("get"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", "Usage: " + CMD + " get ENDPOINT_URI [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals("Usage: " + CMD + " get ENDPOINT_URI [ARGUMENTS]", exe.stdoutLines().get(0), "help message"); //Assert.assertEquals("error message", "CLIENT not specified", exe.stderrLines().get(0)); exe = KcAdmExec.execute("update"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", "Usage: " + CMD + " update ENDPOINT_URI [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals("Usage: " + CMD + " update ENDPOINT_URI [ARGUMENTS]", exe.stdoutLines().get(0), "help message"); //Assert.assertEquals("error message", "No file nor attribute values specified", exe.stderrLines().get(0)); exe = KcAdmExec.execute("delete"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", "Usage: " + CMD + " delete ENDPOINT_URI [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals("Usage: " + CMD + " delete ENDPOINT_URI [ARGUMENTS]", exe.stdoutLines().get(0), "help message"); //Assert.assertEquals("error message", "CLIENT not specified", exe.stderrLines().get(0)); //exe = KcAdmExec.execute("get-roles"); @@ -114,28 +114,28 @@ public void testNoArgs() { exe = KcAdmExec.execute("add-roles"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", "Usage: " + CMD + " add-roles (--uusername USERNAME | --uid ID) [--cclientid CLIENT_ID | --cid ID] (--rolename NAME | --roleid ID)+ [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals("Usage: " + CMD + " add-roles (--uusername USERNAME | --uid ID) [--cclientid CLIENT_ID | --cid ID] (--rolename NAME | --roleid ID)+ [ARGUMENTS]", exe.stdoutLines().get(0), "help message"); //Assert.assertEquals("error message", "CLIENT not specified", exe.stderrLines().get(0)); exe = KcAdmExec.execute("remove-roles"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", "Usage: " + CMD + " remove-roles (--uusername USERNAME | --uid ID) [--cclientid CLIENT_ID | --cid ID] (--rolename NAME | --roleid ID)+ [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals("Usage: " + CMD + " remove-roles (--uusername USERNAME | --uid ID) [--cclientid CLIENT_ID | --cid ID] (--rolename NAME | --roleid ID)+ [ARGUMENTS]", exe.stdoutLines().get(0), "help message"); exe = KcAdmExec.execute("set-password"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", "Usage: " + CMD + " set-password (--username USERNAME | --userid ID) [--new-password PASSWORD] [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals("Usage: " + CMD + " set-password (--username USERNAME | --userid ID) [--new-password PASSWORD] [ARGUMENTS]", exe.stdoutLines().get(0), "help message"); //Assert.assertEquals("error message", "CLIENT not specified", exe.stderrLines().get(0)); exe = KcAdmExec.execute("help"); assertExitCodeAndStdErrSize(exe, 0, 0); lines = exe.stdoutLines(); - Assert.assertTrue("stdout output not empty", lines.size() > 0); - Assert.assertEquals("stdout first line", "Keycloak Admin CLI", lines.get(0)); - Assert.assertEquals("stdout one but last line", "Use '" + KcAdmExec.CMD + " help ' for more information about a given command.", lines.get(lines.size() - 2)); - Assert.assertEquals("stdout last line", "", lines.get(lines.size() - 1)); + Assertions.assertTrue(lines.size() > 0, "stdout output not empty"); + Assertions.assertEquals("Keycloak Admin CLI", lines.get(0), "stdout first line"); + Assertions.assertEquals("Use '" + KcAdmExec.CMD + " help ' for more information about a given command.", lines.get(lines.size() - 2), "stdout one but last line"); + Assertions.assertEquals("", lines.get(lines.size() - 1), "stdout last line"); } @Test @@ -145,55 +145,55 @@ public void testHelpGlobalOption() { */ KcAdmExec exe = KcAdmExec.execute("--help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Keycloak Admin CLI", exe.stdoutLines().get(0)); + Assertions.assertEquals("Keycloak Admin CLI", exe.stdoutLines().get(0), "stdout first line"); exe = KcAdmExec.execute("create --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Usage: " + CMD + " create ENDPOINT_URI [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " create ENDPOINT_URI [ARGUMENTS]", exe.stdoutLines().get(0), "stdout first line"); exe = KcAdmExec.execute("get --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Usage: " + CMD + " get ENDPOINT_URI [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " get ENDPOINT_URI [ARGUMENTS]", exe.stdoutLines().get(0), "stdout first line"); exe = KcAdmExec.execute("update --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Usage: " + CMD + " update ENDPOINT_URI [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " update ENDPOINT_URI [ARGUMENTS]", exe.stdoutLines().get(0), "stdout first line"); exe = KcAdmExec.execute("delete --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Usage: " + CMD + " delete ENDPOINT_URI [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " delete ENDPOINT_URI [ARGUMENTS]", exe.stdoutLines().get(0), "stdout first line"); exe = KcAdmExec.execute("get-roles --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Usage: " + CMD + " get-roles [--cclientid CLIENT_ID | --cid ID] [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " get-roles [--cclientid CLIENT_ID | --cid ID] [ARGUMENTS]", exe.stdoutLines().get(0), "stdout first line"); exe = KcAdmExec.execute("add-roles --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Usage: " + CMD + " add-roles (--uusername USERNAME | --uid ID) [--cclientid CLIENT_ID | --cid ID] (--rolename NAME | --roleid ID)+ [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " add-roles (--uusername USERNAME | --uid ID) [--cclientid CLIENT_ID | --cid ID] (--rolename NAME | --roleid ID)+ [ARGUMENTS]", exe.stdoutLines().get(0), "stdout first line"); exe = KcAdmExec.execute("remove-roles --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Usage: " + CMD + " remove-roles (--uusername USERNAME | --uid ID) [--cclientid CLIENT_ID | --cid ID] (--rolename NAME | --roleid ID)+ [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " remove-roles (--uusername USERNAME | --uid ID) [--cclientid CLIENT_ID | --cid ID] (--rolename NAME | --roleid ID)+ [ARGUMENTS]", exe.stdoutLines().get(0), "stdout first line"); exe = KcAdmExec.execute("set-password --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Usage: " + CMD + " set-password (--username USERNAME | --userid ID) [--new-password PASSWORD] [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " set-password (--username USERNAME | --userid ID) [--new-password PASSWORD] [ARGUMENTS]", exe.stdoutLines().get(0), "stdout first line"); exe = KcAdmExec.execute("config --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Usage: " + CMD + " config SUB_COMMAND [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " config SUB_COMMAND [ARGUMENTS]", exe.stdoutLines().get(0), "stdout first line"); exe = KcAdmExec.execute("config credentials --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout line", - " " + CMD + " config credentials --server SERVER_URL --realm REALM --user USER [--password PASSWORD] [ARGUMENTS]", - exe.stdoutLines().get(1)); + Assertions.assertEquals(" " + CMD + " config credentials --server SERVER_URL --realm REALM --user USER [--password PASSWORD] [ARGUMENTS]", + exe.stdoutLines().get(1), + "stdout line"); exe = KcAdmExec.execute("config truststore --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", - "Usage: " + CMD + " config truststore [TRUSTSTORE | --delete] [--trustpass PASSWORD] [ARGUMENTS]", - exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " config truststore [TRUSTSTORE | --delete] [--trustpass PASSWORD] [ARGUMENTS]", + exe.stdoutLines().get(0), + "stdout first line"); } @Test @@ -204,7 +204,7 @@ public void testBadOptionInPlaceOfCommand() { KcAdmExec exe = KcAdmExec.execute("--nonexistent"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("stderr first line", "Unknown option: '--nonexistent'", exe.stderrLines().get(0)); + Assertions.assertEquals("Unknown option: '--nonexistent'", exe.stderrLines().get(0), "stderr first line"); } @Test @@ -216,14 +216,14 @@ public void testBadOption() { KcAdmExec exe = KcAdmExec.execute("get users --nonexistent"); assertExitCodeAndStreamSizes(exe, 2, 0, 3); - Assert.assertEquals("stderr first line", "Unknown option: '--nonexistent'", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " get --help' for more information on the available options.", exe.stderrLines().get(2)); + Assertions.assertEquals("Unknown option: '--nonexistent'", exe.stderrLines().get(0), "stderr first line"); + Assertions.assertEquals("Try '" + CMD + " get --help' for more information on the available options.", exe.stderrLines().get(2), "try help"); exe = KcAdmExec.execute("set-password --nonexistent"); assertExitCodeAndStreamSizes(exe, 2, 0, 3); - Assert.assertEquals("stderr first line", "Unknown option: '--nonexistent'", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " set-password --help' for more information on the available options.", exe.stderrLines().get(2)); + Assertions.assertEquals("Unknown option: '--nonexistent'", exe.stderrLines().get(0), "stderr first line"); + Assertions.assertEquals("Try '" + CMD + " set-password --help' for more information on the available options.", exe.stderrLines().get(2), "try help"); } @Test @@ -231,7 +231,7 @@ public void testBadOverlappingOption() { KcAdmExec exe = KcAdmExec.execute("config credentials --server http://localhost:8080 --realm master --username admin --password admin"); assertExitCodeAndStreamSizes(exe, 2, 0, 3); - Assert.assertEquals("stderr first line", "Unknown options: '--username', 'admin'", exe.stderrLines().get(0)); + Assertions.assertEquals("Unknown options: '--username', 'admin'", exe.stderrLines().get(0), "stderr first line"); } @Test @@ -252,8 +252,8 @@ public void testCredentialsNoServerWithDefaultConfig() { KcAdmExec exe = KcAdmExec.execute("config credentials --realm master --user admin --password admin"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("stderr first line", "Required option not specified: --server", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " config credentials --help' for more information on the available options.", exe.stderrLines().get(1)); + Assertions.assertEquals("Required option not specified: --server", exe.stderrLines().get(0), "stderr first line"); + Assertions.assertEquals("Try '" + CMD + " config credentials --help' for more information on the available options.", exe.stderrLines().get(1), "try help"); } @Test @@ -264,8 +264,8 @@ public void testCredentialsNoRealmWithDefaultConfig() { KcAdmExec exe = KcAdmExec.execute("config credentials --server " + serverUrl + " --user admin --password admin"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("stderr first line", "Required option not specified: --realm", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " config credentials --help' for more information on the available options.", exe.stderrLines().get(1)); + Assertions.assertEquals("Required option not specified: --realm", exe.stderrLines().get(0), "stderr first line"); + Assertions.assertEquals("Try '" + CMD + " config credentials --help' for more information on the available options.", exe.stderrLines().get(1), "try help"); } @Test @@ -276,8 +276,8 @@ public void testCredentialsWithNoConfig() { KcAdmExec exe = KcAdmExec.execute("config credentials --no-config --server " + serverUrl + " --realm master --user admin --password admin"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("stderr first line", "Unsupported option: --no-config", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " config credentials --help' for more information on the available options.", exe.stderrLines().get(1)); + Assertions.assertEquals("Unsupported option: --no-config", exe.stderrLines().get(0), "stderr first line"); + Assertions.assertEquals("Try '" + CMD + " config credentials --help' for more information on the available options.", exe.stderrLines().get(1), "try help"); } @Test @@ -288,7 +288,7 @@ public void testUserLoginWithDefaultConfig() { KcAdmExec exe = KcAdmExec.execute("config credentials --server " + serverUrl + " --realm master --user admin --password admin"); assertExitCodeAndStreamSizes(exe, 0, 0, 1); - Assert.assertEquals("stderr first line", "Logging into " + serverUrl + " as user admin of realm master", exe.stderrLines().get(0)); + Assertions.assertEquals("Logging into " + serverUrl + " as user admin of realm master", exe.stderrLines().get(0), "stderr first line"); } @Test @@ -296,7 +296,7 @@ public void testUserLoginWithAngleBrackets() { KcAdmExec exe = KcAdmExec.execute("config credentials --server " + serverUrl + " --realm test --user 'special>>character' --password ''"); assertExitCodeAndStreamSizes(exe, 0, 0, 1); - Assert.assertEquals("stderr first line", "Logging into " + serverUrl + " as user special>>character of realm test", exe.stderrLines().get(0)); + Assertions.assertEquals("Logging into " + serverUrl + " as user special>>character of realm test", exe.stderrLines().get(0), "stderr first line"); } @Test @@ -319,7 +319,7 @@ public void testUserLoginWithDefaultConfigInteractive() throws IOException { exe.waitCompletion(); assertExitCodeAndStreamSizes(exe, 0, 1, 1); - Assert.assertEquals("stderr first line", "Logging into " + serverUrl + " as user admin of realm master", exe.stderrLines().get(0)); + Assertions.assertEquals("Logging into " + serverUrl + " as user admin of realm master", exe.stderrLines().get(0), "stderr first line"); /* @@ -335,8 +335,8 @@ public void testUserLoginWithDefaultConfigInteractive() throws IOException { exe = KcAdmExec.execute("config credentials --server " + serverUrl + " --realm master --user admin < '" + tmpFile.getName() + "'"); assertExitCodeAndStreamSizes(exe, 0, 1, 1); - Assert.assertTrue("Enter password prompt", exe.stdoutLines().get(0).startsWith("Enter password: ")); - Assert.assertEquals("stderr first line", "Logging into " + serverUrl + " as user admin of realm master", exe.stderrLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().get(0).startsWith("Enter password: "), "Enter password prompt"); + Assertions.assertEquals("Logging into " + serverUrl + " as user admin of realm master", exe.stderrLines().get(0), "stderr first line"); } finally { tmpFile.delete(); @@ -364,7 +364,7 @@ public void testClientLoginWithDefaultConfigInteractive() throws IOException { exe.waitCompletion(); assertExitCodeAndStreamSizes(exe, 0, 1, 1); - Assert.assertEquals("stderr first line", "Logging into " + serverUrl + " as service-account-admin-cli-secret of realm test", exe.stderrLines().get(0)); + Assertions.assertEquals("Logging into " + serverUrl + " as service-account-admin-cli-secret of realm test", exe.stderrLines().get(0), "stderr first line"); /* * Run the test one more time with stdin redirect @@ -381,8 +381,8 @@ public void testClientLoginWithDefaultConfigInteractive() throws IOException { .execute(); assertExitCodeAndStreamSizes(exe, 0, 1, 1); - Assert.assertTrue("Enter client secret prompt", exe.stdoutLines().get(0).startsWith("Enter client secret: ")); - Assert.assertEquals("stderr first line", "Logging into " + serverUrl + " as service-account-admin-cli-secret of realm test", exe.stderrLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().get(0).startsWith("Enter client secret: "), "Enter client secret prompt"); + Assertions.assertEquals("Logging into " + serverUrl + " as service-account-admin-cli-secret of realm test", exe.stderrLines().get(0), "stderr first line"); } finally { tmpFile.delete(); } @@ -401,23 +401,23 @@ public void testUserLoginWithCustomConfig() { " --user admin --password admin --config '" + configFile.getName() + "'"); assertExitCodeAndStreamSizes(exe, 0, 0, 1); - Assert.assertEquals("stderr first line", "Logging into " + serverUrl + " as user admin of realm master", exe.stderrLines().get(0)); + Assertions.assertEquals("Logging into " + serverUrl + " as user admin of realm master", exe.stderrLines().get(0), "stderr first line"); // make sure the config file exists, and has the right content ConfigData config = handler.loadConfig(); - Assert.assertEquals("serverUrl", serverUrl, config.getServerUrl()); - Assert.assertEquals("realm", "master", config.getRealm()); + Assertions.assertEquals(serverUrl, config.getServerUrl(), "serverUrl"); + Assertions.assertEquals("master", config.getRealm(), "realm"); RealmConfigData realmcfg = config.sessionRealmConfigData(); - Assert.assertNotNull("realm config data no null", realmcfg); - Assert.assertEquals("realm cfg serverUrl", serverUrl, realmcfg.serverUrl()); - Assert.assertEquals("realm cfg realm", "master", realmcfg.realm()); - Assert.assertEquals("client id", "admin-cli", realmcfg.getClientId()); - Assert.assertNotNull("token not null", realmcfg.getToken()); - Assert.assertNotNull("refresh token not null", realmcfg.getRefreshToken()); - Assert.assertNotNull("token expires not null", realmcfg.getExpiresAt()); - Assert.assertNotNull("token expires in future", realmcfg.getExpiresAt() > System.currentTimeMillis()); - Assert.assertNotNull("refresh token expires not null", realmcfg.getRefreshExpiresAt()); - Assert.assertNotNull("refresh token expires in future", realmcfg.getRefreshExpiresAt() > System.currentTimeMillis()); + Assertions.assertNotNull(realmcfg, "realm config data no null"); + Assertions.assertEquals(serverUrl, realmcfg.serverUrl(), "realm cfg serverUrl"); + Assertions.assertEquals("master", realmcfg.realm(), "realm cfg realm"); + Assertions.assertEquals("admin-cli", realmcfg.getClientId(), "client id"); + Assertions.assertNotNull(realmcfg.getToken(), "token not null"); + Assertions.assertNotNull(realmcfg.getRefreshToken(), "refresh token not null"); + Assertions.assertNotNull(realmcfg.getExpiresAt(), "token expires not null"); + Assertions.assertNotNull(realmcfg.getExpiresAt() > System.currentTimeMillis(), "token expires in future"); + Assertions.assertNotNull(realmcfg.getRefreshExpiresAt(), "refresh token expires not null"); + Assertions.assertNotNull(realmcfg.getRefreshExpiresAt() > System.currentTimeMillis(), "refresh token expires in future"); } finally { configFile.delete(); @@ -456,7 +456,7 @@ public void testCustomConfigLoginCreateDelete() throws IOException { ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("clientId", "test-client", client.getClientId()); + Assertions.assertEquals("test-client", client.getClientId(), "clientId"); @@ -491,8 +491,8 @@ public void testCRUDWithOnTheFlyUserAuthWithClientSecret() throws IOException { " --user user1 --password userpass --client admin-cli-secret --secret password"); assertExitCodeAndStreamSizes(exe, 1, 0, 2); - Assert.assertEquals("login message", "Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0)); - Assert.assertEquals("error message", "Client not allowed for direct access grants [unauthorized_client]", exe.stderrLines().get(exe.stderrLines().size() - 1)); + Assertions.assertEquals("Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0), "login message"); + Assertions.assertEquals("Client not allowed for direct access grants [unauthorized_client]", exe.stderrLines().get(exe.stderrLines().size() - 1), "error message"); // try wrong user password @@ -500,8 +500,8 @@ public void testCRUDWithOnTheFlyUserAuthWithClientSecret() throws IOException { " --user user1 --password wrong --client admin-cli-secret-direct --secret password"); assertExitCodeAndStreamSizes(exe, 1, 0, 2); - Assert.assertEquals("login message", "Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0)); - Assert.assertEquals("error message", "Invalid user credentials [invalid_grant]", exe.stderrLines().get(exe.stderrLines().size() - 1)); + Assertions.assertEquals("Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0), "login message"); + Assertions.assertEquals("Invalid user credentials [invalid_grant]", exe.stderrLines().get(exe.stderrLines().size() - 1), "error message"); // try wrong client secret @@ -509,8 +509,8 @@ public void testCRUDWithOnTheFlyUserAuthWithClientSecret() throws IOException { " --user user1 --password userpass --client admin-cli-secret-direct --secret wrong"); assertExitCodeAndStreamSizes(exe, 1, 0, 2); - Assert.assertEquals("login message", "Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0)); - Assert.assertEquals("error message", "Invalid client or Invalid client credentials [unauthorized_client]", exe.stderrLines().get(exe.stderrLines().size() - 1)); + Assertions.assertEquals("Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0), "login message"); + Assertions.assertEquals("Invalid client or Invalid client credentials [unauthorized_client]", exe.stderrLines().get(exe.stderrLines().size() - 1), "error message"); // try whole CRUD @@ -536,7 +536,7 @@ private void testCRUDWithOnTheFlyUserAuthWithSignedJwtClient(String keystoreFile * Login is performed by each operation again, and again using username, password, and client JWT signature. */ File keystore = new File(System.getProperty("user.dir") + "/src/test/resources/cli/kcadm/admin-cli-keystore." + keystoreFileExtension); - Assert.assertTrue("admin-cli-keystore." + keystoreFileExtension + " must exist, but it does not exists", keystore.isFile()); + Assertions.assertTrue(keystore.isFile(), "admin-cli-keystore." + keystoreFileExtension + " must exist, but it does not exists"); // try client without direct grants enabled KcAdmExec exe = KcAdmExec.execute("get clients --no-config --server " + serverUrl + " --realm test" + @@ -544,8 +544,8 @@ private void testCRUDWithOnTheFlyUserAuthWithSignedJwtClient(String keystoreFile " --storepass storepass --keypass keypass --alias admin-cli"); assertExitCodeAndStreamSizes(exe, 1, 0, 2); - Assert.assertEquals("login message", "Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0)); - Assert.assertEquals("error message", "Client not allowed for direct access grants [unauthorized_client]", exe.stderrLines().get(exe.stderrLines().size() - 1)); + Assertions.assertEquals("Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0), "login message"); + Assertions.assertEquals("Client not allowed for direct access grants [unauthorized_client]", exe.stderrLines().get(exe.stderrLines().size() - 1), "error message"); // try wrong user password @@ -554,8 +554,8 @@ private void testCRUDWithOnTheFlyUserAuthWithSignedJwtClient(String keystoreFile " --storepass storepass --keypass keypass --alias admin-cli"); assertExitCodeAndStreamSizes(exe, 1, 0, 2); - Assert.assertEquals("login message", "Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0)); - Assert.assertEquals("error message", "Invalid user credentials [invalid_grant]", exe.stderrLines().get(exe.stderrLines().size() - 1)); + Assertions.assertEquals("Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0), "login message"); + Assertions.assertEquals("Invalid user credentials [invalid_grant]", exe.stderrLines().get(exe.stderrLines().size() - 1), "error message"); // try wrong storepass @@ -564,8 +564,8 @@ private void testCRUDWithOnTheFlyUserAuthWithSignedJwtClient(String keystoreFile " --storepass wrong --keypass keypass --alias admin-cli"); assertExitCodeAndStreamSizes(exe, 1, 0, 2); - Assert.assertEquals("login message", "Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0)); - Assert.assertTrue("error message", exe.stderrLines().get(exe.stderrLines().size() - 1).startsWith("Failed to load private key:")); + Assertions.assertEquals("Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0), "login message"); + Assertions.assertTrue(exe.stderrLines().get(exe.stderrLines().size() - 1).startsWith("Failed to load private key:"), "error message"); // try whole CRUD @@ -593,7 +593,7 @@ public void testCRUDWithOnTheFlyServiceAccountWithSignedJwtClient() throws IOExc * Login is performed by each operation again, and again using only client JWT signature - service account is used. */ File keystore = new File(System.getProperty("user.dir") + "/src/test/resources/cli/kcadm/admin-cli-keystore.p12"); - Assert.assertTrue("admin-cli-keystore.p12 exists", keystore.isFile()); + Assertions.assertTrue(keystore.isFile(), "admin-cli-keystore.p12 exists"); testCRUDWithOnTheFlyAuth(serverUrl, "--client admin-cli-jwt --keystore '" + keystore.getAbsolutePath() + "' --storepass storepass --keypass keypass --alias admin-cli", "", @@ -624,11 +624,11 @@ public void testGetUserNameExact() { KcAdmExec.execute("create users -r demorealm -s username=anothertestuser"); KcAdmExec.execute("create users -r demorealm -s username=onemoretestuser"); KcAdmExec exec = execute("add-roles --uusername=testuser --rolename offline_access --target-realm=demorealm"); - Assert.assertEquals(0, exec.exitCode()); + Assertions.assertEquals(0, exec.exitCode()); exec = execute("add-roles --uusername=anothertestuser --rolename offline_access --target-realm=demorealm"); - Assert.assertEquals(0, exec.exitCode()); + Assertions.assertEquals(0, exec.exitCode()); exec = execute("add-roles --uusername=onemoretestuser --rolename offline_access --target-realm=demorealm"); - Assert.assertEquals(0, exec.exitCode()); + Assertions.assertEquals(0, exec.exitCode()); } @Test @@ -640,13 +640,13 @@ public void testGetGroupNameExact() { KcAdmExec.execute("create groups -r demorealm -s name=anothertest"); KcAdmExec.execute("create groups -r demorealm -s name=onemoretest"); KcAdmExec exec = execute("get-roles -r demorealm --gname test"); - Assert.assertEquals(exec.stderrString(), 0, exec.exitCode()); + Assertions.assertEquals(0, exec.exitCode(), exec.stderrString()); exec = execute("get-roles -r demorealm --gname anothertest"); - Assert.assertEquals(exec.stderrString(), 0, exec.exitCode()); + Assertions.assertEquals(0, exec.exitCode(), exec.stderrString()); exec = execute("get-roles -r demorealm --gname onemoretest"); - Assert.assertEquals(exec.stderrString(), 0, exec.exitCode()); + Assertions.assertEquals(0, exec.exitCode(), exec.stderrString()); exec = execute("get-roles -r demorealm --gname not_there"); - Assert.assertEquals(1, exec.exitCode()); + Assertions.assertEquals(1, exec.exitCode()); } @Test @@ -654,7 +654,7 @@ public void testCsvFormat() { execute("config credentials --server " + serverUrl + " --realm master --user admin --password admin"); KcAdmExec exec = execute("get realms/master --format csv"); assertExitCodeAndStreamSizes(exec, 0, 1, 0); - Assert.assertTrue(exec.stdoutString().startsWith("\"")); + Assertions.assertTrue(exec.stdoutString().startsWith("\"")); } @Test @@ -663,7 +663,7 @@ public void testCsvFormatWithMissingFields() { KcAdmExec exec = execute("get realms/master --format csv --fields foo"); // nothing valid was selected, should be blank assertExitCodeAndStreamSizes(exec, 0, 1, 0); - Assert.assertTrue(exec.stdoutString().isBlank()); + Assertions.assertTrue(exec.stdoutString().isBlank()); } @Test @@ -690,12 +690,12 @@ public void testStatusOptionForConfigCred() { execute("config credentials --server " + serverUrl + " --realm master --user admin --password admin"); KcAdmExec exec = execute("config credentials --status"); assertExitCodeAndStreamSizes(exec, 0, 1, 0); - Assert.assertTrue(exec.stdoutString().startsWith("Logged in (server: " + serverUrl + ", realm: master, expired: false, timeToExpiry:")); - Assert.assertTrue(exec.stdoutString().endsWith("from now)\n")); + Assertions.assertTrue(exec.stdoutString().startsWith("Logged in (server: " + serverUrl + ", realm: master, expired: false, timeToExpiry:")); + Assertions.assertTrue(exec.stdoutString().endsWith("from now)\n")); exec = execute("config credentials --status --server " + serverUrl + " --realm master --user admin --password admin"); assertExitCodeAndStreamSizes(exec, 0, 1, 0); - Assert.assertTrue(exec.stdoutString().startsWith("Logged in (server: " + serverUrl + ", realm: master, expired: false, timeToExpiry:")); - Assert.assertTrue(exec.stdoutString().endsWith("from now)\n")); + Assertions.assertTrue(exec.stdoutString().startsWith("Logged in (server: " + serverUrl + ", realm: master, expired: false, timeToExpiry:")); + Assertions.assertTrue(exec.stdoutString().endsWith("from now)\n")); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmTruststoreTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmTruststoreTest.java index 80d34973688d..c48a7f04f49c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmTruststoreTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmTruststoreTest.java @@ -10,8 +10,8 @@ import org.keycloak.testsuite.util.TempFileResource; import org.keycloak.testsuite.util.oauth.OAuthClient; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.client.admin.cli.KcAdmMain.DEFAULT_CONFIG_FILE_PATH; import static org.keycloak.client.cli.util.OsUtil.EOL; @@ -31,8 +31,8 @@ public void testTruststore() throws IOException { KcAdmExec exe = execute("config truststore --no-config '" + truststore.getAbsolutePath() + "'"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("stderr first line", "Unsupported option: --no-config", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + KcAdmMain.CMD + " config truststore --help' for more information on the available options.", exe.stderrLines().get(1)); + Assertions.assertEquals("Unsupported option: --no-config", exe.stderrLines().get(0), "stderr first line"); + Assertions.assertEquals("Try '" + KcAdmMain.CMD + " config truststore --help' for more information on the available options.", exe.stderrLines().get(1), "try help"); // only run this test if ssl protected keycloak server is available if (!AUTH_SERVER_SSL_REQUIRED) { @@ -101,19 +101,19 @@ public void testTruststore() throws IOException { exe = execute("config truststore --delete '" + truststore.getAbsolutePath() + "'"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("incompatible", "Option --delete is mutually exclusive with specifying a TRUSTSTORE", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + KcAdmMain.CMD + " config truststore --help' for more information on the available options.", exe.stderrLines().get(1)); + Assertions.assertEquals("Option --delete is mutually exclusive with specifying a TRUSTSTORE", exe.stderrLines().get(0), "incompatible"); + Assertions.assertEquals("Try '" + KcAdmMain.CMD + " config truststore --help' for more information on the available options.", exe.stderrLines().get(1), "try help"); exe = execute("config truststore --delete --trustpass secret"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("no truststore error", "Options --trustpass and --delete are mutually exclusive", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + KcAdmMain.CMD + " config truststore --help' for more information on the available options.", exe.stderrLines().get(1)); + Assertions.assertEquals("Options --trustpass and --delete are mutually exclusive", exe.stderrLines().get(0), "no truststore error"); + Assertions.assertEquals("Try '" + KcAdmMain.CMD + " config truststore --help' for more information on the available options.", exe.stderrLines().get(1), "try help"); FileConfigHandler cfghandler = new FileConfigHandler(); FileConfigHandler.setConfigFile(DEFAULT_CONFIG_FILE_PATH); ConfigData config = cfghandler.loadConfig(); - Assert.assertNull("truststore null", config.getTruststore()); - Assert.assertNull("trustpass null", config.getTrustpass()); + Assertions.assertNull(config.getTruststore(), "truststore null"); + Assertions.assertNull(config.getTrustpass(), "trustpass null"); // perform no-config CRUD test against ssl protected endpoint diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmUpdateTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmUpdateTest.java index deca9bcde2d0..8410f4b110a3 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmUpdateTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmUpdateTest.java @@ -18,8 +18,8 @@ import org.keycloak.testsuite.util.TempFileResource; import org.keycloak.util.JsonSerialization; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.cli.KcAdmExec.CMD; import static org.keycloak.testsuite.cli.KcAdmExec.execute; @@ -89,10 +89,10 @@ public void testUpdateThoroughly() throws IOException { ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertTrue("enabled", client.isEnabled()); - Assert.assertFalse("publicClient", client.isPublicClient()); - Assert.assertFalse("bearerOnly", client.isBearerOnly()); - Assert.assertTrue("redirectUris is empty", client.getRedirectUris().isEmpty()); + Assertions.assertTrue(client.isEnabled(), "enabled"); + Assertions.assertFalse(client.isPublicClient(), "publicClient"); + Assertions.assertFalse(client.isBearerOnly(), "bearerOnly"); + Assertions.assertTrue(client.getRedirectUris().isEmpty(), "redirectUris is empty"); // Merge update @@ -102,8 +102,8 @@ public void testUpdateThoroughly() throws IOException { assertExitCodeAndStdErrSize(exe, 0, 0); client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertFalse("enabled", client.isEnabled()); - Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris()); + Assertions.assertFalse(client.isEnabled(), "enabled"); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris(), "redirectUris"); @@ -114,8 +114,8 @@ public void testUpdateThoroughly() throws IOException { client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertTrue("redirectUris is empty", client.getRedirectUris().isEmpty()); - Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8981/myapp"), client.getWebOrigins()); + Assertions.assertTrue(client.getRedirectUris().isEmpty(), "redirectUris is empty"); + Assertions.assertEquals(Arrays.asList("http://localhost:8981/myapp"), client.getWebOrigins(), "webOrigins"); @@ -141,8 +141,8 @@ public void testUpdateThoroughly() throws IOException { exe = execute("update clients/" + client.getId() + " --nonexisting --config '" + configFile.getName() + "'"); assertExitCodeAndStreamSizes(exe, 2, 0, 3); - Assert.assertEquals("error message", "Unknown option: '--nonexisting'", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " update --help' for more information on the available options.", exe.stderrLines().get(2)); + Assertions.assertEquals("Unknown option: '--nonexisting'", exe.stderrLines().get(0), "error message"); + Assertions.assertEquals("Try '" + CMD + " update --help' for more information on the available options.", exe.stderrLines().get(2), "try help"); // test overwrite from file @@ -156,9 +156,9 @@ public void testUpdateThoroughly() throws IOException { client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); // web origin is not sent to the server, thus it retains the current value - Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8981/myapp"), client.getWebOrigins()); - Assert.assertFalse("enabled is false", client.isEnabled()); - Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris()); + Assertions.assertEquals(Arrays.asList("http://localhost:8981/myapp"), client.getWebOrigins(), "webOrigins"); + Assertions.assertFalse(client.isEnabled(), "enabled is false"); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris(), "redirectUris"); // test using merge with file @@ -171,9 +171,9 @@ public void testUpdateThoroughly() throws IOException { assertExitCodeAndStdErrSize(exe, 0, 0); client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8980/myapp"), client.getWebOrigins()); - Assert.assertFalse("enabled is false", client.isEnabled()); - Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris()); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp"), client.getWebOrigins(), "webOrigins"); + Assertions.assertFalse(client.isEnabled(), "enabled is false"); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris(), "redirectUris"); exe = KcAdmExec.newBuilder() .argsLine("update clients/" + client.getId() + " --config '" + configFile.getName() + @@ -184,8 +184,8 @@ public void testUpdateThoroughly() throws IOException { assertExitCodeAndStdErrSize(exe, 0, 0); client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8980/myapp1"), client.getWebOrigins()); - Assert.assertTrue("enabled is true", client.isEnabled()); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp1"), client.getWebOrigins(), "webOrigins"); + Assertions.assertTrue(client.isEnabled(), "enabled is true"); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/AbstractRegCliTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/AbstractRegCliTest.java index 23178ef083ff..ab02c7d1b2d2 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/AbstractRegCliTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/AbstractRegCliTest.java @@ -36,8 +36,8 @@ import org.keycloak.testsuite.util.UserBuilder; import org.keycloak.util.JsonSerialization; -import org.junit.Assert; import org.junit.Before; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.cli.KcRegExec.WORK_DIR; @@ -146,13 +146,13 @@ void assertFieldsEqualWithExclusions(ConfigData config1, ConfigData config2, Str HashSet exclusions = new HashSet<>(Arrays.asList(excluded)); if (!exclusions.contains("serverUrl")) { - Assert.assertEquals("serverUrl", config1.getServerUrl(), config2.getServerUrl()); + Assertions.assertEquals(config1.getServerUrl(), config2.getServerUrl(), "serverUrl"); } if (!exclusions.contains("realm")) { - Assert.assertEquals("realm", config1.getRealm(), config2.getRealm()); + Assertions.assertEquals(config1.getRealm(), config2.getRealm(), "realm"); } if (!exclusions.contains("truststore")) { - Assert.assertEquals("truststore", config1.getTruststore(), config2.getTruststore()); + Assertions.assertEquals(config1.getTruststore(), config2.getTruststore(), "truststore"); } if (!exclusions.contains("endpoints")) { Map> endp1 = config1.getEndpoints(); @@ -168,7 +168,7 @@ void assertFieldsEqualWithExclusions(ConfigData config1, ConfigData config2, Str String serverUrl = ent1.getKey(); String endpskey = "endpoints." + serverUrl; if (!exclusions.contains(endpskey)) { - Assert.assertEquals(endpskey, ent1.getKey(), ent2.getKey()); + Assertions.assertEquals(ent1.getKey(), ent2.getKey(), endpskey); Map realms1 = ent1.getValue(); Map realms2 = ent2.getValue(); @@ -183,7 +183,7 @@ void assertFieldsEqualWithExclusions(ConfigData config1, ConfigData config2, Str String realm = rent1.getKey(); String rkey = endpskey + "." + realm; if (!exclusions.contains(endpskey)) { - Assert.assertEquals(rkey, rent1.getKey(), rent2.getKey()); + Assertions.assertEquals(rent1.getKey(), rent2.getKey(), rkey); RealmConfigData rdata1 = rent1.getValue(); RealmConfigData rdata2 = rent2.getValue(); @@ -211,57 +211,57 @@ void assertFieldsEqualWithExclusions(String server, String realm, RealmConfigDat String ekey = pfix + "serverUrl"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.serverUrl(), data2.serverUrl()); + Assertions.assertEquals(data1.serverUrl(), data2.serverUrl(), ekey); } ekey = pfix + "realm"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.realm(), data2.realm()); + Assertions.assertEquals(data1.realm(), data2.realm(), ekey); } ekey = pfix + "clientId"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.getClientId(), data2.getClientId()); + Assertions.assertEquals(data1.getClientId(), data2.getClientId(), ekey); } ekey = pfix + "initialToken"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.getInitialToken(), data2.getInitialToken()); + Assertions.assertEquals(data1.getInitialToken(), data2.getInitialToken(), ekey); } ekey = pfix + "token"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.getToken(), data2.getToken()); + Assertions.assertEquals(data1.getToken(), data2.getToken(), ekey); } ekey = pfix + "refreshToken"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.getRefreshToken(), data2.getRefreshToken()); + Assertions.assertEquals(data1.getRefreshToken(), data2.getRefreshToken(), ekey); } ekey = pfix + "expiresAt"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.getExpiresAt(), data2.getExpiresAt()); + Assertions.assertEquals(data1.getExpiresAt(), data2.getExpiresAt(), ekey); } ekey = pfix + "refreshExpiresAt"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.getRefreshExpiresAt(), data2.getRefreshExpiresAt()); + Assertions.assertEquals(data1.getRefreshExpiresAt(), data2.getRefreshExpiresAt(), ekey); } ekey = pfix + "secret"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.getSecret(), data2.getSecret()); + Assertions.assertEquals(data1.getSecret(), data2.getSecret(), ekey); } ekey = pfix + "signingToken"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.getSigningToken(), data2.getSigningToken()); + Assertions.assertEquals(data1.getSigningToken(), data2.getSigningToken(), ekey); } ekey = pfix + "sigExpiresAt"; if (!exclusions.contains(ekey)) { - Assert.assertEquals(ekey, data1.getSigExpiresAt(), data2.getSigExpiresAt()); + Assertions.assertEquals(data1.getSigExpiresAt(), data2.getSigExpiresAt(), ekey); } ekey = pfix + "clients"; @@ -278,10 +278,10 @@ void assertFieldsEqualWithExclusions(String server, String realm, RealmConfigDat String ckey = ekey + "." + (ckey1 != null ? ckey1.getKey() : ckey2.getKey()); if (!exclusions.contains(ckey)) { - Assert.assertNotNull(ckey + " left not null", ckey1); - Assert.assertNotNull(ckey + " right not null", ckey2); - Assert.assertEquals(ckey, ckey1.getKey(), ckey2.getKey()); - Assert.assertEquals(ckey + " value", ckey1.getValue(), ckey2.getValue()); + Assertions.assertNotNull(ckey1, ckey + " left not null"); + Assertions.assertNotNull(ckey2, ckey + " right not null"); + Assertions.assertEquals(ckey1.getKey(), ckey2.getKey(), ckey); + Assertions.assertEquals(ckey1.getValue(), ckey2.getValue(), ckey + " value"); } } } @@ -346,7 +346,7 @@ String issueInitialAccessToken(String realm) { ClientInitialAccessPresentation response = resource.create(rep); String token = response.getToken(); - Assert.assertNotNull("Issued initial access token not null", token); + Assertions.assertNotNull(token, "Issued initial access token not null"); return token; } @@ -381,15 +381,15 @@ void testCRUDWithOnTheFlyAuth(String serverUrl, String credentials, String extra KcRegExec exe = execute("create --no-config --server " + serverUrl + " --realm test " + credentials + " " + extraOptions + " -s clientId=test-client -o"); - Assert.assertEquals("exitCode == 0", 0, exe.exitCode()); - Assert.assertEquals("login message", loginMessage, exe.stderrLines().get(0)); + Assertions.assertEquals(0, exe.exitCode(), "exitCode == 0"); + Assertions.assertEquals(loginMessage, exe.stderrLines().get(0), "login message"); ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("clientId", "test-client", client.getClientId()); - Assert.assertNotNull("registrationAccessToken not null", client.getRegistrationAccessToken()); + Assertions.assertEquals("test-client", client.getClientId(), "clientId"); + Assertions.assertNotNull(client.getRegistrationAccessToken(), "registrationAccessToken not null"); long lastModified2 = configFile.exists() ? configFile.lastModified() : 0; - Assert.assertEquals("config file not modified", lastModified, lastModified2); + Assertions.assertEquals(lastModified, lastModified2, "config file not modified"); @@ -399,13 +399,13 @@ void testCRUDWithOnTheFlyAuth(String serverUrl, String credentials, String extra assertExitCodeAndStdErrSize(exe, 0, 1); ClientRepresentation client2 = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("clientId", "test-client", client2.getClientId()); + Assertions.assertEquals("test-client", client2.getClientId(), "clientId"); // we did not provide a token, thus no registrationAccessToken is present - Assert.assertNull("registrationAccessToken is null", client2.getRegistrationAccessToken()); + Assertions.assertNull(client2.getRegistrationAccessToken(), "registrationAccessToken is null"); lastModified2 = configFile.exists() ? configFile.lastModified() : 0; - Assert.assertEquals("config file not modified", lastModified, lastModified2); + Assertions.assertEquals(lastModified, lastModified2, "config file not modified"); @@ -418,13 +418,12 @@ void testCRUDWithOnTheFlyAuth(String serverUrl, String credentials, String extra assertExitCodeAndStdErrSize(exe, 0, 0); ClientRepresentation client3 = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("clientId", "test-client", client3.getClientId()); + Assertions.assertEquals("test-client", client3.getClientId(), "clientId"); - Assert.assertEquals("registrationAccessToken in returned json is different than one returned by create", - client.getRegistrationAccessToken(), client3.getRegistrationAccessToken()); + Assertions.assertEquals(client.getRegistrationAccessToken(), client3.getRegistrationAccessToken(), "registrationAccessToken in returned json is different than one returned by create"); lastModified2 = configFile.exists() ? configFile.lastModified() : 0; - Assert.assertEquals("config file not modified", lastModified, lastModified2); + Assertions.assertEquals(lastModified, lastModified2, "config file not modified"); @@ -437,13 +436,13 @@ void testCRUDWithOnTheFlyAuth(String serverUrl, String credentials, String extra assertExitCodeAndStdErrSize(exe, 0, 1); ClientRepresentation client4 = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("clientId", "test-client", client4.getClientId()); - Assert.assertFalse("enabled", client4.isEnabled()); + Assertions.assertEquals("test-client", client4.getClientId(), "clientId"); + Assertions.assertFalse(client4.isEnabled(), "enabled"); - Assert.assertNull("registrationAccessToken in null", client4.getRegistrationAccessToken()); + Assertions.assertNull(client4.getRegistrationAccessToken(), "registrationAccessToken in null"); lastModified2 = configFile.exists() ? configFile.lastModified() : 0; - Assert.assertEquals("config file not modified", lastModified, lastModified2); + Assertions.assertEquals(lastModified, lastModified2, "config file not modified"); @@ -457,14 +456,13 @@ void testCRUDWithOnTheFlyAuth(String serverUrl, String credentials, String extra assertExitCodeAndStdErrSize(exe, 0, 0); ClientRepresentation client5 = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("clientId", "test-client", client5.getClientId()); - Assert.assertTrue("enabled", client5.isEnabled()); + Assertions.assertEquals("test-client", client5.getClientId(), "clientId"); + Assertions.assertTrue(client5.isEnabled(), "enabled"); - Assert.assertNotEquals("registrationAccessToken in returned json is different than one returned by get", - client3.getRegistrationAccessToken(), client5.getRegistrationAccessToken()); + Assertions.assertNotEquals(client3.getRegistrationAccessToken(), client5.getRegistrationAccessToken(), "registrationAccessToken in returned json is different than one returned by get"); lastModified2 = configFile.exists() ? configFile.lastModified() : 0; - Assert.assertEquals("config file not modified", lastModified, lastModified2); + Assertions.assertEquals(lastModified, lastModified2, "config file not modified"); @@ -477,7 +475,7 @@ void testCRUDWithOnTheFlyAuth(String serverUrl, String credentials, String extra assertExitCodeAndStreamSizes(exe, 0, 0, 1); lastModified2 = configFile.exists() ? configFile.lastModified() : 0; - Assert.assertEquals("config file not modified", lastModified, lastModified2); + Assertions.assertEquals(lastModified, lastModified2, "config file not modified"); @@ -487,9 +485,9 @@ void testCRUDWithOnTheFlyAuth(String serverUrl, String credentials, String extra exe = execute("delete test-client --no-config --server " + serverUrl + " --realm test " + credentials + " " + extraOptions); assertExitCodeAndStreamSizes(exe, 1, 0, 2); - Assert.assertEquals("error message", "Client not found [invalid_request]", exe.stderrLines().get(exe.stderrLines().size() - 1)); + Assertions.assertEquals("Client not found [invalid_request]", exe.stderrLines().get(exe.stderrLines().size() - 1), "error message"); lastModified2 = configFile.exists() ? configFile.lastModified() : 0; - Assert.assertEquals("config file not modified", lastModified, lastModified2); + Assertions.assertEquals(lastModified, lastModified2, "config file not modified"); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegConfigTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegConfigTest.java index 31b6678648dd..ee091e3be300 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegConfigTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegConfigTest.java @@ -6,8 +6,8 @@ import org.keycloak.testsuite.cli.KcRegExec; import org.keycloak.testsuite.util.TempFileResource; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.client.cli.util.OsUtil.EOL; import static org.keycloak.client.registration.cli.KcRegMain.CMD; @@ -28,20 +28,20 @@ public void testRegistrationToken() throws IOException { // without --server KcRegExec exe = execute("config registration-token --config '" + configFile.getName() + "' "); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("error message", "Required option not specified: --server", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " config registration-token --help' for more information on the available options.", exe.stderrLines().get(1)); + Assertions.assertEquals("Required option not specified: --server", exe.stderrLines().get(0), "error message"); + Assertions.assertEquals("Try '" + CMD + " config registration-token --help' for more information on the available options.", exe.stderrLines().get(1), "try help"); // without --realm exe = execute("config registration-token --config '" + configFile.getName() + "' --server http://localhost:8080/auth"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("error message", "Required option not specified: --realm", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " config registration-token --help' for more information on the available options.", exe.stderrLines().get(1)); + Assertions.assertEquals("Required option not specified: --realm", exe.stderrLines().get(0), "error message"); + Assertions.assertEquals("Try '" + CMD + " config registration-token --help' for more information on the available options.", exe.stderrLines().get(1), "try help"); // without --client exe = execute("config registration-token --config '" + configFile.getName() + "' --server http://localhost:8080/auth --realm test"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("error message", "Required option not specified: --client", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " config registration-token --help' for more information on the available options.", exe.stderrLines().get(1)); + Assertions.assertEquals("Required option not specified: --client", exe.stderrLines().get(0), "error message"); + Assertions.assertEquals("Try '" + CMD + " config registration-token --help' for more information on the available options.", exe.stderrLines().get(1), "try help"); // specify token on cmdline exe = execute("config registration-token --config '" + configFile.getName() + "' --server http://localhost:8080/auth --realm test --client my_client NEWTOKEN"); @@ -77,13 +77,13 @@ public void testNoConfigOption() throws IOException { KcRegExec exe = execute("config registration-token --no-config --server http://localhost:8080/auth --realm test --client my_client --delete"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("stderr first line", "Unsupported option: --no-config", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " config registration-token --help' for more information on the available options.", exe.stderrLines().get(1)); + Assertions.assertEquals("Unsupported option: --no-config", exe.stderrLines().get(0), "stderr first line"); + Assertions.assertEquals("Try '" + CMD + " config registration-token --help' for more information on the available options.", exe.stderrLines().get(1), "try help"); exe = execute("config initial-token --no-config --server http://localhost:8080/auth --realm test --delete"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("stderr first line", "Unsupported option: --no-config", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " config initial-token --help' for more information on the available options.", exe.stderrLines().get(1)); + Assertions.assertEquals("Unsupported option: --no-config", exe.stderrLines().get(0), "stderr first line"); + Assertions.assertEquals("Try '" + CMD + " config initial-token --help' for more information on the available options.", exe.stderrLines().get(1), "try help"); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegCreateTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegCreateTest.java index 49c1f37f0e79..a827c9546003 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegCreateTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegCreateTest.java @@ -27,10 +27,10 @@ import org.keycloak.util.JsonSerialization; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.cli.KcRegExec.execute; import static org.keycloak.testsuite.util.ServerURLs.AUTH_SERVER_SSL_REQUIRED; @@ -87,9 +87,9 @@ public void testCreateThoroughly() throws IOException { // check that current server, realm, and initial token are saved in the file ConfigData config = handler.loadConfig(); - Assert.assertEquals("Config serverUrl", oauth.AUTH_SERVER_ROOT, config.getServerUrl()); - Assert.assertEquals("Config realm", realm, config.getRealm()); - Assert.assertEquals("Config initial access token", token, config.ensureRealmConfigData(oauth.AUTH_SERVER_ROOT, realm).getInitialToken()); + Assertions.assertEquals(oauth.AUTH_SERVER_ROOT, config.getServerUrl(), "Config serverUrl"); + Assertions.assertEquals(realm, config.getRealm(), "Config realm"); + Assertions.assertEquals(token, config.ensureRealmConfigData(oauth.AUTH_SERVER_ROOT, realm).getInitialToken(), "Config initial access token"); // create configuration from file using stdin redirect ... output an object String content = "{\n" + @@ -116,22 +116,22 @@ public void testCreateThoroughly() throws IOException { assertExitCodeAndStdErrSize(exe, 0, 2); ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertNotNull("id", client.getId()); - Assert.assertEquals("clientId", "my_client", client.getClientId()); - Assert.assertEquals("enabled", true, client.isEnabled()); - Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris()); - Assert.assertEquals("serviceAccountsEnabled", true, client.isServiceAccountsEnabled()); - Assert.assertEquals("name", "My Client App", client.getName()); - Assert.assertEquals("implicitFlowEnabled", false, client.isImplicitFlowEnabled()); - Assert.assertEquals("publicClient", true, client.isPublicClient()); + Assertions.assertNotNull(client.getId(), "id"); + Assertions.assertEquals("my_client", client.getClientId(), "clientId"); + Assertions.assertEquals(true, client.isEnabled(), "enabled"); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris(), "redirectUris"); + Assertions.assertEquals(true, client.isServiceAccountsEnabled(), "serviceAccountsEnabled"); + Assertions.assertEquals("My Client App", client.getName(), "name"); + Assertions.assertEquals(false, client.isImplicitFlowEnabled(), "implicitFlowEnabled"); + Assertions.assertEquals(true, client.isPublicClient(), "publicClient"); // note there is no server-side check if protocol is supported - Assert.assertEquals("protocol", "openid-connect", client.getProtocol()); - Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8980/myapp"), client.getWebOrigins()); - Assert.assertEquals("consentRequired", false, client.isConsentRequired()); - Assert.assertEquals("baseUrl", "http://localhost:8980/myapp", client.getBaseUrl()); - Assert.assertEquals("rootUrl", "http://localhost:8980/myapp", client.getRootUrl()); - Assert.assertEquals("bearerOnly", true, client.isStandardFlowEnabled()); - Assert.assertNull("mappers are null", client.getProtocolMappers()); + Assertions.assertEquals("openid-connect", client.getProtocol(), "protocol"); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp"), client.getWebOrigins(), "webOrigins"); + Assertions.assertEquals(false, client.isConsentRequired(), "consentRequired"); + Assertions.assertEquals("http://localhost:8980/myapp", client.getBaseUrl(), "baseUrl"); + Assertions.assertEquals("http://localhost:8980/myapp", client.getRootUrl(), "rootUrl"); + Assertions.assertEquals(true, client.isStandardFlowEnabled(), "bearerOnly"); + Assertions.assertNull(client.getProtocolMappers(), "mappers are null"); // create configuration from file as a template and override clientId and other attributes ... output an object exe = execute("create --insecure --config '" + configFile.getName() + "' -o -f '" + tmpFile.getName() + @@ -142,41 +142,41 @@ public void testCreateThoroughly() throws IOException { assertExitCodeAndStdErrSize(exe, 0, 2); ClientRepresentation client2 = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertNotNull("id", client2.getId()); - Assert.assertEquals("clientId", "my_client2", client2.getClientId()); - Assert.assertEquals("enabled", false, client2.isEnabled()); - Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8980/myapp2/*"), client2.getRedirectUris()); - Assert.assertEquals("serviceAccountsEnabled", true, client2.isServiceAccountsEnabled()); - Assert.assertEquals("name", "My Client App II", client2.getName()); - Assert.assertEquals("implicitFlowEnabled", false, client2.isImplicitFlowEnabled()); - Assert.assertEquals("publicClient", true, client2.isPublicClient()); - Assert.assertEquals("protocol", "openid-connect", client2.getProtocol()); - Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8980/myapp2"), client2.getWebOrigins()); - Assert.assertEquals("consentRequired", false, client2.isConsentRequired()); - Assert.assertEquals("baseUrl", "http://localhost:8980/myapp2", client2.getBaseUrl()); - Assert.assertEquals("rootUrl", "http://localhost:8980/myapp2", client2.getRootUrl()); - Assert.assertEquals("bearerOnly", true, client2.isStandardFlowEnabled()); - Assert.assertNull("mappers are null", client2.getProtocolMappers()); + Assertions.assertNotNull(client2.getId(), "id"); + Assertions.assertEquals("my_client2", client2.getClientId(), "clientId"); + Assertions.assertEquals(false, client2.isEnabled(), "enabled"); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp2/*"), client2.getRedirectUris(), "redirectUris"); + Assertions.assertEquals(true, client2.isServiceAccountsEnabled(), "serviceAccountsEnabled"); + Assertions.assertEquals("My Client App II", client2.getName(), "name"); + Assertions.assertEquals(false, client2.isImplicitFlowEnabled(), "implicitFlowEnabled"); + Assertions.assertEquals(true, client2.isPublicClient(), "publicClient"); + Assertions.assertEquals("openid-connect", client2.getProtocol(), "protocol"); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp2"), client2.getWebOrigins(), "webOrigins"); + Assertions.assertEquals(false, client2.isConsentRequired(), "consentRequired"); + Assertions.assertEquals("http://localhost:8980/myapp2", client2.getBaseUrl(), "baseUrl"); + Assertions.assertEquals("http://localhost:8980/myapp2", client2.getRootUrl(), "rootUrl"); + Assertions.assertEquals(true, client2.isStandardFlowEnabled(), "bearerOnly"); + Assertions.assertNull(client2.getProtocolMappers(), "mappers are null"); // check that using an invalid attribute key is not ignored exe = execute("create --config '" + configFile.getName() + "' -o -f '" + tmpFile.getName() + "' -s client_id=my_client3"); assertExitCodeAndStreamSizes(exe, 1, 0, 1); - Assert.assertEquals("Failed to set attribute 'client_id' on document type 'default'", exe.stderrLines().get(0)); + Assertions.assertEquals("Failed to set attribute 'client_id' on document type 'default'", exe.stderrLines().get(0)); } // simple create, output an id exe = execute("create --insecure --config '" + configFile.getName() + "' -i -s clientId=my_client3"); assertExitCodeAndStreamSizes(exe, 0, 1, 2); - Assert.assertEquals("only clientId returned", "my_client3", exe.stdoutLines().get(0)); + Assertions.assertEquals("my_client3", exe.stdoutLines().get(0), "only clientId returned"); // simple create, default output exe = execute("create --insecure --config '" + configFile.getName() + "' -s clientId=my_client4"); assertExitCodeAndStreamSizes(exe, 0, 0, 3); - Assert.assertEquals("only clientId returned", "Registered new client with client_id 'my_client4'", exe.stderrLines().get(exe.stderrLines().size() - 1)); + Assertions.assertEquals("Registered new client with client_id 'my_client4'", exe.stderrLines().get(exe.stderrLines().size() - 1), "only clientId returned"); @@ -199,12 +199,12 @@ public void testCreateThoroughly() throws IOException { OIDCClientRepresentation client = JsonSerialization.readValue(exe.stdout(), OIDCClientRepresentation.class); - Assert.assertNotNull("clientId", client.getClientId()); - Assert.assertEquals("redirect_uris", Arrays.asList("http://localhost:8980/myapp5/*"), client.getRedirectUris()); - Assert.assertEquals("grant_types", Arrays.asList("authorization_code", "client_credentials", "refresh_token"), client.getGrantTypes()); - Assert.assertEquals("response_types", Arrays.asList("code", "none"), client.getResponseTypes()); - Assert.assertEquals("client_name", "My Client App V", client.getClientName()); - Assert.assertEquals("client_uri", "http://localhost:8980/myapp5", client.getClientUri()); + Assertions.assertNotNull(client.getClientId(), "clientId"); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp5/*"), client.getRedirectUris(), "redirect_uris"); + Assertions.assertEquals(Arrays.asList("authorization_code", "client_credentials", "refresh_token"), client.getGrantTypes(), "grant_types"); + Assertions.assertEquals(Arrays.asList("code", "none"), client.getResponseTypes(), "response_types"); + Assertions.assertEquals("My Client App V", client.getClientName(), "client_name"); + Assertions.assertEquals("http://localhost:8980/myapp5", client.getClientUri(), "client_uri"); @@ -212,7 +212,7 @@ public void testCreateThoroughly() throws IOException { exe = execute("create --config '" + configFile.getName() + "' -e default -f '" + tmpFile.getName() + "'"); assertExitCodeAndStreamSizes(exe, 1, 0, 1); - Assert.assertEquals("Error message", "Attribute 'redirect_uris' not supported on document type 'default'", exe.stderrLines().get(0)); + Assertions.assertEquals("Attribute 'redirect_uris' not supported on document type 'default'", exe.stderrLines().get(0), "Error message"); } // TODO: SAML is not tested with FIPS enabled as it does not work. This needs to be revisited when SAML works with FIPS @@ -220,19 +220,19 @@ public void testCreateThoroughly() throws IOException { // test create saml formated xml - format autodetection File samlSpMetaFile = new File(System.getProperty("user.dir") + "/src/test/resources/cli/kcreg/saml-sp-metadata.xml"); - Assert.assertTrue("saml-sp-metadata.xml exists", samlSpMetaFile.isFile()); + Assertions.assertTrue(samlSpMetaFile.isFile(), "saml-sp-metadata.xml exists"); exe = execute("create --insecure --config '" + configFile.getName() + "' -o -f - < '" + samlSpMetaFile.getAbsolutePath() + "'"); assertExitCodeAndStdErrSize(exe, 0, 2); ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertNotNull("id", client.getId()); - Assert.assertEquals("clientId", "http://localhost:8080/sales-post-enc/", client.getClientId()); - Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8081/sales-post-enc/saml"), client.getRedirectUris()); - Assert.assertEquals("attributes.saml_name_id_format", "username", client.getAttributes().get("saml_name_id_format")); - Assert.assertEquals("attributes.saml_assertion_consumer_url_post", "http://localhost:8081/sales-post-enc/saml", client.getAttributes().get("saml_assertion_consumer_url_post")); - Assert.assertEquals("attributes.saml.signature.algorithm", "RSA_SHA256", client.getAttributes().get("saml.signature.algorithm")); + Assertions.assertNotNull(client.getId(), "id"); + Assertions.assertEquals("http://localhost:8080/sales-post-enc/", client.getClientId(), "clientId"); + Assertions.assertEquals(Arrays.asList("http://localhost:8081/sales-post-enc/saml"), client.getRedirectUris(), "redirectUris"); + Assertions.assertEquals("username", client.getAttributes().get("saml_name_id_format"), "attributes.saml_name_id_format"); + Assertions.assertEquals("http://localhost:8081/sales-post-enc/saml", client.getAttributes().get("saml_assertion_consumer_url_post"), "attributes.saml_assertion_consumer_url_post"); + Assertions.assertEquals("RSA_SHA256", client.getAttributes().get("saml.signature.algorithm"), "attributes.saml.signature.algorithm"); } // delete initial token @@ -240,7 +240,7 @@ public void testCreateThoroughly() throws IOException { assertExitCodeAndStreamSizes(exe, 0, 0, 0); config = handler.loadConfig(); - Assert.assertNull("initial token == null", config.ensureRealmConfigData(serverUrl, realm).getInitialToken()); + Assertions.assertNull(config.ensureRealmConfigData(serverUrl, realm).getInitialToken(), "initial token == null"); } } @@ -267,17 +267,17 @@ public void testCreateWithAuthorizationServices() throws IOException { ClientResource client = clients.get(clientRep.getId()); clientRep = client.toRepresentation(); - Assert.assertTrue(clientRep.getAuthorizationServicesEnabled()); + Assertions.assertTrue(clientRep.getAuthorizationServicesEnabled()); ResourceServerRepresentation settings = client.authorization().getSettings(); - Assert.assertEquals(PolicyEnforcementMode.ENFORCING, settings.getPolicyEnforcementMode()); - Assert.assertTrue(settings.isAllowRemoteResourceManagement()); + Assertions.assertEquals(PolicyEnforcementMode.ENFORCING, settings.getPolicyEnforcementMode()); + Assertions.assertTrue(settings.isAllowRemoteResourceManagement()); List roles = client.roles().list(); - Assert.assertEquals(1, roles.size()); - Assert.assertEquals("uma_protection", roles.get(0).getName()); + Assertions.assertEquals(1, roles.size()); + Assertions.assertEquals("uma_protection", roles.get(0).getName()); // create using oidc endpoint - autodetect format String content = " {\n" + @@ -298,32 +298,32 @@ public void testCreateWithAuthorizationServices() throws IOException { OIDCClientRepresentation oidcClient = JsonSerialization.readValue(exe.stdout(), OIDCClientRepresentation.class); - Assert.assertNotNull("clientId", oidcClient.getClientId()); - Assert.assertEquals("redirect_uris", Arrays.asList("http://localhost:8980/myapp5/*"), oidcClient.getRedirectUris()); + Assertions.assertNotNull(oidcClient.getClientId(), "clientId"); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp5/*"), oidcClient.getRedirectUris(), "redirect_uris"); assertThat("grant_types", oidcClient.getGrantTypes(), Matchers.containsInAnyOrder("authorization_code", "client_credentials", "refresh_token", OAuth2Constants.UMA_GRANT_TYPE)); - Assert.assertEquals("response_types", Arrays.asList("code", "none"), oidcClient.getResponseTypes()); - Assert.assertEquals("client_name", "My Reg Authz", oidcClient.getClientName()); - Assert.assertEquals("client_uri", "http://localhost:8980/myapp5", oidcClient.getClientUri()); + Assertions.assertEquals(Arrays.asList("code", "none"), oidcClient.getResponseTypes(), "response_types"); + Assertions.assertEquals("My Reg Authz", oidcClient.getClientName(), "client_name"); + Assertions.assertEquals("http://localhost:8980/myapp5", oidcClient.getClientUri(), "client_uri"); client = clients.get(oidcClient.getClientId()); clientRep = client.toRepresentation(); - Assert.assertTrue(clientRep.getAuthorizationServicesEnabled()); + Assertions.assertTrue(clientRep.getAuthorizationServicesEnabled()); settings = client.authorization().getSettings(); - Assert.assertEquals(PolicyEnforcementMode.ENFORCING, settings.getPolicyEnforcementMode()); - Assert.assertTrue(settings.isAllowRemoteResourceManagement()); + Assertions.assertEquals(PolicyEnforcementMode.ENFORCING, settings.getPolicyEnforcementMode()); + Assertions.assertTrue(settings.isAllowRemoteResourceManagement()); roles = client.roles().list(); - Assert.assertEquals(1, roles.size()); - Assert.assertEquals("uma_protection", roles.get(0).getName()); + Assertions.assertEquals(1, roles.size()); + Assertions.assertEquals("uma_protection", roles.get(0).getName()); UserRepresentation serviceAccount = realm.users().search(ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + clientRep.getClientId()).get(0); - Assert.assertNotNull(serviceAccount); + Assertions.assertNotNull(serviceAccount); List serviceAccountRoles = realm.users().get(serviceAccount.getId()).roles().clientLevel(clientRep.getId()).listAll(); - Assert.assertTrue(serviceAccountRoles.stream().anyMatch(roleRepresentation -> "uma_protection".equals(roleRepresentation.getName()))); + Assertions.assertTrue(serviceAccountRoles.stream().anyMatch(roleRepresentation -> "uma_protection".equals(roleRepresentation.getName()))); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegTest.java index 24d51dc6a45b..29c5b076fb17 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegTest.java @@ -16,9 +16,9 @@ import org.keycloak.testsuite.util.TempFileResource; import org.keycloak.util.JsonSerialization; -import org.junit.Assert; import org.junit.Assume; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.client.cli.util.OsUtil.EOL; import static org.keycloak.client.registration.cli.KcRegMain.CMD; @@ -40,10 +40,10 @@ public void testNoArgs() { assertExitCodeAndStdErrSize(exe, 2, 0); List lines = exe.stdoutLines(); - Assert.assertTrue("stdout output not empty", lines.size() > 0); - Assert.assertEquals("stdout first line", "Keycloak Client Registration CLI", lines.get(0)); - Assert.assertEquals("stdout one but last line", "Use '" + KcRegExec.CMD + " help ' for more information about a given command.", lines.get(lines.size() - 2)); - Assert.assertEquals("stdout last line", "", lines.get(lines.size() - 1)); + Assertions.assertTrue(lines.size() > 0, "stdout output not empty"); + Assertions.assertEquals("Keycloak Client Registration CLI", lines.get(0), "stdout first line"); + Assertions.assertEquals("Use '" + KcRegExec.CMD + " help ' for more information about a given command.", lines.get(lines.size() - 2), "stdout one but last line"); + Assertions.assertEquals("", lines.get(lines.size() - 1), "stdout last line"); /* @@ -51,72 +51,72 @@ public void testNoArgs() { */ exe = execute("config"); assertExitCodeAndStreamSizes(exe, 2, 8, 0); - Assert.assertEquals("error message", - "Usage: kcreg.sh config SUB_COMMAND [ARGUMENTS]", - exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: kcreg.sh config SUB_COMMAND [ARGUMENTS]", + exe.stdoutLines().get(0), + "error message"); exe = execute("config credentials"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", "Usage: " + CMD + " config credentials --server SERVER_URL --realm REALM [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals("Usage: " + CMD + " config credentials --server SERVER_URL --realm REALM [ARGUMENTS]", exe.stdoutLines().get(0), "help message"); exe = execute("config initial-token"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", "Usage: " + CMD + " config initial-token --server SERVER --realm REALM [--delete | TOKEN] [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals("Usage: " + CMD + " config initial-token --server SERVER --realm REALM [--delete | TOKEN] [ARGUMENTS]", exe.stdoutLines().get(0), "help message"); exe = execute("config registration-token"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", "Usage: " + CMD + " config registration-token --server SERVER --realm REALM --client CLIENT [--delete | TOKEN] [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals("Usage: " + CMD + " config registration-token --server SERVER --realm REALM --client CLIENT [--delete | TOKEN] [ARGUMENTS]", exe.stdoutLines().get(0), "help message"); exe = execute("config truststore"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", "Usage: " + CMD + " config truststore [TRUSTSTORE | --delete] [--trustpass PASSWORD] [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals("Usage: " + CMD + " config truststore [TRUSTSTORE | --delete] [--trustpass PASSWORD] [ARGUMENTS]", exe.stdoutLines().get(0), "help message"); exe = execute("create"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", "Usage: " + CMD + " create [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals("Usage: " + CMD + " create [ARGUMENTS]", exe.stdoutLines().get(0), "help message"); //Assert.assertEquals("error message", "No file nor attribute values specified", exe.stderrLines().get(0)); exe = execute("get"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", "Usage: " + CMD + " get CLIENT [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals("Usage: " + CMD + " get CLIENT [ARGUMENTS]", exe.stdoutLines().get(0), "help message"); //Assert.assertEquals("error message", "CLIENT not specified", exe.stderrLines().get(0)); exe = execute("update"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", "Usage: " + CMD + " update CLIENT [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals("Usage: " + CMD + " update CLIENT [ARGUMENTS]", exe.stdoutLines().get(0), "help message"); //Assert.assertEquals("error message", "No file nor attribute values specified", exe.stderrLines().get(0)); exe = execute("delete"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", "Usage: " + CMD + " delete CLIENT [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals("Usage: " + CMD + " delete CLIENT [ARGUMENTS]", exe.stdoutLines().get(0), "help message"); //Assert.assertEquals("error message", "CLIENT not specified", exe.stderrLines().get(0)); exe = execute("attrs"); - Assert.assertEquals("exit code", 0, exe.exitCode()); - Assert.assertTrue("stdout has response", exe.stdoutLines().size() > 10); - Assert.assertEquals("first line", "Attributes for default format:", exe.stdoutLines().get(0)); + Assertions.assertEquals(0, exe.exitCode(), "exit code"); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "stdout has response"); + Assertions.assertEquals("Attributes for default format:", exe.stdoutLines().get(0), "first line"); exe = execute("update-token"); assertExitCodeAndStdErrSize(exe, 2, 0); - Assert.assertTrue("help message returned", exe.stdoutLines().size() > 10); - Assert.assertEquals("help message", "Usage: " + CMD + " update-token CLIENT [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().size() > 10, "help message returned"); + Assertions.assertEquals("Usage: " + CMD + " update-token CLIENT [ARGUMENTS]", exe.stdoutLines().get(0), "help message"); //Assert.assertEquals("error message", "CLIENT not specified", exe.stderrLines().get(0)); exe = execute("help"); assertExitCodeAndStdErrSize(exe, 0, 0); lines = exe.stdoutLines(); - Assert.assertTrue("stdout output not empty", lines.size() > 0); - Assert.assertEquals("stdout first line", "Keycloak Client Registration CLI", lines.get(0)); - Assert.assertEquals("stdout one but last line", "Use '" + KcRegExec.CMD + " help ' for more information about a given command.", lines.get(lines.size() - 2)); - Assert.assertEquals("stdout last line", "", lines.get(lines.size() - 1)); + Assertions.assertTrue(lines.size() > 0, "stdout output not empty"); + Assertions.assertEquals("Keycloak Client Registration CLI", lines.get(0), "stdout first line"); + Assertions.assertEquals("Use '" + KcRegExec.CMD + " help ' for more information about a given command.", lines.get(lines.size() - 2), "stdout one but last line"); + Assertions.assertEquals("", lines.get(lines.size() - 1), "stdout last line"); } @Test @@ -126,59 +126,59 @@ public void testHelpGlobalOption() { */ KcRegExec exe = execute("--help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Keycloak Client Registration CLI", exe.stdoutLines().get(0)); + Assertions.assertEquals("Keycloak Client Registration CLI", exe.stdoutLines().get(0), "stdout first line"); exe = execute("create --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Usage: " + CMD + " create [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " create [ARGUMENTS]", exe.stdoutLines().get(0), "stdout first line"); exe = execute("get --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Usage: " + CMD + " get CLIENT [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " get CLIENT [ARGUMENTS]", exe.stdoutLines().get(0), "stdout first line"); exe = execute("update --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Usage: " + CMD + " update CLIENT [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " update CLIENT [ARGUMENTS]", exe.stdoutLines().get(0), "stdout first line"); exe = execute("delete --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Usage: " + CMD + " delete CLIENT [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " delete CLIENT [ARGUMENTS]", exe.stdoutLines().get(0), "stdout first line"); exe = execute("attrs --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Usage: " + CMD + " attrs [ATTRIBUTE] [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " attrs [ATTRIBUTE] [ARGUMENTS]", exe.stdoutLines().get(0), "stdout first line"); exe = execute("update-token --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Usage: " + CMD + " update-token CLIENT [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " update-token CLIENT [ARGUMENTS]", exe.stdoutLines().get(0), "stdout first line"); exe = execute("config --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", "Usage: " + CMD + " config SUB_COMMAND [ARGUMENTS]", exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " config SUB_COMMAND [ARGUMENTS]", exe.stdoutLines().get(0), "stdout first line"); exe = execute("config credentials --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", - "Usage: " + CMD + " config credentials --server SERVER_URL --realm REALM [ARGUMENTS]", - exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " config credentials --server SERVER_URL --realm REALM [ARGUMENTS]", + exe.stdoutLines().get(0), + "stdout first line"); exe = execute("config initial-token --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", - "Usage: " + CMD + " config initial-token --server SERVER --realm REALM [--delete | TOKEN] [ARGUMENTS]", - exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " config initial-token --server SERVER --realm REALM [--delete | TOKEN] [ARGUMENTS]", + exe.stdoutLines().get(0), + "stdout first line"); exe = execute("config registration-token --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", - "Usage: " + CMD + " config registration-token --server SERVER --realm REALM --client CLIENT [--delete | TOKEN] [ARGUMENTS]", - exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " config registration-token --server SERVER --realm REALM --client CLIENT [--delete | TOKEN] [ARGUMENTS]", + exe.stdoutLines().get(0), + "stdout first line"); exe = execute("config truststore --help"); assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertEquals("stdout first line", - "Usage: " + CMD + " config truststore [TRUSTSTORE | --delete] [--trustpass PASSWORD] [ARGUMENTS]", - exe.stdoutLines().get(0)); + Assertions.assertEquals("Usage: " + CMD + " config truststore [TRUSTSTORE | --delete] [--trustpass PASSWORD] [ARGUMENTS]", + exe.stdoutLines().get(0), + "stdout first line"); } @@ -190,7 +190,7 @@ public void testBadCommand() { KcRegExec exe = execute("nonexistent"); assertExitCodeAndStreamSizes(exe, 2, 0, 3); - Assert.assertEquals("stderr first line", "Unmatched argument at index 0: 'nonexistent'", exe.stderrLines().get(0)); + Assertions.assertEquals("Unmatched argument at index 0: 'nonexistent'", exe.stderrLines().get(0), "stderr first line"); } @Test @@ -201,7 +201,7 @@ public void testBadOptionInPlaceOfCommand() { KcRegExec exe = execute("--nonexistent"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("stderr first line", "Unknown option: '--nonexistent'", exe.stderrLines().get(0)); + Assertions.assertEquals("Unknown option: '--nonexistent'", exe.stderrLines().get(0), "stderr first line"); } @Test @@ -213,8 +213,8 @@ public void testBadOption() { KcRegExec exe = execute("get my_client --nonexistent"); assertExitCodeAndStreamSizes(exe, 2, 0, 3); - Assert.assertEquals("stderr first line", "Unknown option: '--nonexistent'", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " get --help' for more information on the available options.", exe.stderrLines().get(2)); + Assertions.assertEquals("Unknown option: '--nonexistent'", exe.stderrLines().get(0), "stderr first line"); + Assertions.assertEquals("Try '" + CMD + " get --help' for more information on the available options.", exe.stderrLines().get(2), "try help"); } @Test @@ -235,8 +235,8 @@ public void testCredentialsNoServerWithDefaultConfig() { KcRegExec exe = execute("config credentials --realm master --user admin --password admin"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("stderr first line", "Required option not specified: --server", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " config credentials --help' for more information on the available options.", exe.stderrLines().get(1)); + Assertions.assertEquals("Required option not specified: --server", exe.stderrLines().get(0), "stderr first line"); + Assertions.assertEquals("Try '" + CMD + " config credentials --help' for more information on the available options.", exe.stderrLines().get(1), "try help"); } @Test @@ -247,8 +247,8 @@ public void testCredentialsNoRealmWithDefaultConfig() { KcRegExec exe = execute("config credentials --server " + serverUrl + " --user admin --password admin"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("stderr first line", "Required option not specified: --realm", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " config credentials --help' for more information on the available options.", exe.stderrLines().get(1)); + Assertions.assertEquals("Required option not specified: --realm", exe.stderrLines().get(0), "stderr first line"); + Assertions.assertEquals("Try '" + CMD + " config credentials --help' for more information on the available options.", exe.stderrLines().get(1), "try help"); } @Test @@ -259,8 +259,8 @@ public void testCredentialsWithNoConfig() { KcRegExec exe = KcRegExec.execute("config credentials --no-config --server " + serverUrl + " --realm master --user admin --password admin"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("stderr first line", "Unsupported option: --no-config", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " config credentials --help' for more information on the available options.", exe.stderrLines().get(1)); + Assertions.assertEquals("Unsupported option: --no-config", exe.stderrLines().get(0), "stderr first line"); + Assertions.assertEquals("Try '" + CMD + " config credentials --help' for more information on the available options.", exe.stderrLines().get(1), "try help"); } @Test @@ -271,7 +271,7 @@ public void testUserLoginWithDefaultConfig() { KcRegExec exe = execute("config credentials --server " + serverUrl + " --realm master --user admin --password admin"); assertExitCodeAndStreamSizes(exe, 0, 0, 1); - Assert.assertEquals("stderr first line", "Logging into " + serverUrl + " as user admin of realm master", exe.stderrLines().get(0)); + Assertions.assertEquals("Logging into " + serverUrl + " as user admin of realm master", exe.stderrLines().get(0), "stderr first line"); } @Test @@ -294,7 +294,7 @@ public void testUserLoginWithDefaultConfigInteractive() throws IOException { exe.waitCompletion(); assertExitCodeAndStreamSizes(exe, 0, 1, 1); - Assert.assertEquals("stderr first line", "Logging into " + serverUrl + " as user admin of realm master", exe.stderrLines().get(0)); + Assertions.assertEquals("Logging into " + serverUrl + " as user admin of realm master", exe.stderrLines().get(0), "stderr first line"); /* @@ -310,8 +310,8 @@ public void testUserLoginWithDefaultConfigInteractive() throws IOException { exe = execute("config credentials --server " + serverUrl + " --realm master --user admin < '" + tmpFile.getName() + "'"); assertExitCodeAndStreamSizes(exe, 0, 1, 1); - Assert.assertTrue("Enter password prompt", exe.stdoutLines().get(0).startsWith("Enter password: ")); - Assert.assertEquals("stderr first line", "Logging into " + serverUrl + " as user admin of realm master", exe.stderrLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().get(0).startsWith("Enter password: "), "Enter password prompt"); + Assertions.assertEquals("Logging into " + serverUrl + " as user admin of realm master", exe.stderrLines().get(0), "stderr first line"); } finally { tmpFile.delete(); @@ -339,7 +339,7 @@ public void testClientLoginWithDefaultConfigInteractive() throws IOException { exe.waitCompletion(); assertExitCodeAndStreamSizes(exe, 0, 1, 1); - Assert.assertEquals("stderr first line", "Logging into " + serverUrl + " as service-account-reg-cli-secret of realm test", exe.stderrLines().get(0)); + Assertions.assertEquals("Logging into " + serverUrl + " as service-account-reg-cli-secret of realm test", exe.stderrLines().get(0), "stderr first line"); /* * Run the test one more time with stdin redirect @@ -356,8 +356,8 @@ public void testClientLoginWithDefaultConfigInteractive() throws IOException { .execute(); assertExitCodeAndStreamSizes(exe, 0, 1, 1); - Assert.assertTrue("Enter client secret prompt", exe.stdoutLines().get(0).startsWith("Enter client secret: ")); - Assert.assertEquals("stderr first line", "Logging into " + serverUrl + " as service-account-reg-cli-secret of realm test", exe.stderrLines().get(0)); + Assertions.assertTrue(exe.stdoutLines().get(0).startsWith("Enter client secret: "), "Enter client secret prompt"); + Assertions.assertEquals("Logging into " + serverUrl + " as service-account-reg-cli-secret of realm test", exe.stderrLines().get(0), "stderr first line"); } finally { tmpFile.delete(); } @@ -376,24 +376,24 @@ public void testUserLoginWithCustomConfig() { " --user admin --password admin --config '" + configFile.getName() + "'"); assertExitCodeAndStreamSizes(exe, 0, 0, 1); - Assert.assertEquals("stderr first line", "Logging into " + serverUrl + " as user admin of realm master", exe.stderrLines().get(0)); + Assertions.assertEquals("Logging into " + serverUrl + " as user admin of realm master", exe.stderrLines().get(0), "stderr first line"); // make sure the config file exists, and has the right content ConfigData config = handler.loadConfig(); - Assert.assertEquals("serverUrl", serverUrl, config.getServerUrl()); - Assert.assertEquals("realm", "master", config.getRealm()); + Assertions.assertEquals(serverUrl, config.getServerUrl(), "serverUrl"); + Assertions.assertEquals("master", config.getRealm(), "realm"); RealmConfigData realmcfg = config.sessionRealmConfigData(); - Assert.assertNotNull("realm config data no null", realmcfg); - Assert.assertEquals("realm cfg serverUrl", serverUrl, realmcfg.serverUrl()); - Assert.assertEquals("realm cfg realm", "master", realmcfg.realm()); - Assert.assertEquals("client id", "admin-cli", realmcfg.getClientId()); - Assert.assertNotNull("token not null", realmcfg.getToken()); - Assert.assertNotNull("refresh token not null", realmcfg.getRefreshToken()); - Assert.assertNotNull("token expires not null", realmcfg.getExpiresAt()); - Assert.assertNotNull("token expires in future", realmcfg.getExpiresAt() > System.currentTimeMillis()); - Assert.assertNotNull("refresh token expires not null", realmcfg.getRefreshExpiresAt()); - Assert.assertNotNull("refresh token expires in future", realmcfg.getRefreshExpiresAt() > System.currentTimeMillis()); - Assert.assertTrue("clients is empty", realmcfg.getClients().isEmpty()); + Assertions.assertNotNull(realmcfg, "realm config data no null"); + Assertions.assertEquals(serverUrl, realmcfg.serverUrl(), "realm cfg serverUrl"); + Assertions.assertEquals("master", realmcfg.realm(), "realm cfg realm"); + Assertions.assertEquals("admin-cli", realmcfg.getClientId(), "client id"); + Assertions.assertNotNull(realmcfg.getToken(), "token not null"); + Assertions.assertNotNull(realmcfg.getRefreshToken(), "refresh token not null"); + Assertions.assertNotNull(realmcfg.getExpiresAt(), "token expires not null"); + Assertions.assertNotNull(realmcfg.getExpiresAt() > System.currentTimeMillis(), "token expires in future"); + Assertions.assertNotNull(realmcfg.getRefreshExpiresAt(), "refresh token expires not null"); + Assertions.assertNotNull(realmcfg.getRefreshExpiresAt() > System.currentTimeMillis(), "refresh token expires in future"); + Assertions.assertTrue(realmcfg.getClients().isEmpty(), "clients is empty"); } finally { configFile.delete(); @@ -431,14 +431,13 @@ public void testCustomConfigLoginCreateDelete() throws IOException { assertFieldsEqualWithExclusions(config1, config2, "endpoints." + serverUrl + ".master.clients.test-client"); // check that registration access token is now set - Assert.assertNotNull(config2.sessionRealmConfigData().getClients().get("test-client")); + Assertions.assertNotNull(config2.sessionRealmConfigData().getClients().get("test-client")); ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("clientId", "test-client", client.getClientId()); - Assert.assertNotNull("registrationAccessToken", client.getRegistrationAccessToken()); - Assert.assertEquals("registrationAccessToken in returned json same as in config", - config2.sessionRealmConfigData().getClients().get("test-client"), client.getRegistrationAccessToken()); + Assertions.assertEquals("test-client", client.getClientId(), "clientId"); + Assertions.assertNotNull(client.getRegistrationAccessToken(), "registrationAccessToken"); + Assertions.assertEquals(config2.sessionRealmConfigData().getClients().get("test-client"), client.getRegistrationAccessToken(), "registrationAccessToken in returned json same as in config"); @@ -452,7 +451,7 @@ public void testCustomConfigLoginCreateDelete() throws IOException { assertFieldsEqualWithExclusions(config2, config3, "endpoints." + serverUrl + ".master.clients.test-client"); // check that registration access token is no longer there - Assert.assertTrue("clients empty", config3.sessionRealmConfigData().getClients().isEmpty()); + Assertions.assertTrue(config3.sessionRealmConfigData().getClients().isEmpty(), "clients empty"); } } @@ -477,8 +476,8 @@ public void testCRUDWithOnTheFlyUserAuthWithClientSecret() throws IOException { " --user user1 --password userpass --client reg-cli-secret --secret password"); assertExitCodeAndStreamSizes(exe, 1, 0, 2); - Assert.assertEquals("login message", "Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0)); - Assert.assertEquals("error message", "Client not allowed for direct access grants [unauthorized_client]", exe.stderrLines().get(exe.stderrLines().size() - 1)); + Assertions.assertEquals("Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0), "login message"); + Assertions.assertEquals("Client not allowed for direct access grants [unauthorized_client]", exe.stderrLines().get(exe.stderrLines().size() - 1), "error message"); // try wrong user password @@ -486,8 +485,8 @@ public void testCRUDWithOnTheFlyUserAuthWithClientSecret() throws IOException { " --user user1 --password wrong --client reg-cli-secret-direct --secret password"); assertExitCodeAndStreamSizes(exe, 1, 0, 2); - Assert.assertEquals("login message", "Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0)); - Assert.assertEquals("error message", "Invalid user credentials [invalid_grant]", exe.stderrLines().get(exe.stderrLines().size() - 1)); + Assertions.assertEquals("Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0), "login message"); + Assertions.assertEquals("Invalid user credentials [invalid_grant]", exe.stderrLines().get(exe.stderrLines().size() - 1), "error message"); // try wrong client secret @@ -495,8 +494,8 @@ public void testCRUDWithOnTheFlyUserAuthWithClientSecret() throws IOException { " --user user1 --password userpass --client reg-cli-secret-direct --secret wrong"); assertExitCodeAndStreamSizes(exe, 1, 0, 2); - Assert.assertEquals("login message", "Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0)); - Assert.assertEquals("error message", "Invalid client or Invalid client credentials [unauthorized_client]", exe.stderrLines().get(exe.stderrLines().size() - 1)); + Assertions.assertEquals("Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0), "login message"); + Assertions.assertEquals("Invalid client or Invalid client credentials [unauthorized_client]", exe.stderrLines().get(exe.stderrLines().size() - 1), "error message"); // try whole CRUD @@ -522,7 +521,7 @@ private void testCRUDWithOnTheFlyUserAuthWithSignedJwtClient(String keystoreFile * Login is performed by each operation again, and again using username, password, and client JWT signature. */ File keystore = new File(System.getProperty("user.dir") + "/src/test/resources/cli/kcreg/reg-cli-keystore." + keystoreFileExtension); - Assert.assertTrue("reg-cli-keystore." + keystoreFileExtension + " exists", keystore.isFile()); + Assertions.assertTrue(keystore.isFile(), "reg-cli-keystore." + keystoreFileExtension + " exists"); // try client without direct grants enabled KcRegExec exe = execute("get test-client --no-config --server " + serverUrl + " --realm test" + @@ -530,8 +529,8 @@ private void testCRUDWithOnTheFlyUserAuthWithSignedJwtClient(String keystoreFile " --storepass storepass --keypass keypass --alias reg-cli"); assertExitCodeAndStreamSizes(exe, 1, 0, 2); - Assert.assertEquals("login message", "Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0)); - Assert.assertEquals("error message", "Client not allowed for direct access grants [unauthorized_client]", exe.stderrLines().get(exe.stderrLines().size() - 1)); + Assertions.assertEquals("Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0), "login message"); + Assertions.assertEquals("Client not allowed for direct access grants [unauthorized_client]", exe.stderrLines().get(exe.stderrLines().size() - 1), "error message"); // try wrong user password @@ -540,8 +539,8 @@ private void testCRUDWithOnTheFlyUserAuthWithSignedJwtClient(String keystoreFile " --storepass storepass --keypass keypass --alias reg-cli"); assertExitCodeAndStreamSizes(exe, 1, 0, 2); - Assert.assertEquals("login message", "Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0)); - Assert.assertEquals("error message", "Invalid user credentials [invalid_grant]", exe.stderrLines().get(exe.stderrLines().size() - 1)); + Assertions.assertEquals("Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0), "login message"); + Assertions.assertEquals("Invalid user credentials [invalid_grant]", exe.stderrLines().get(exe.stderrLines().size() - 1), "error message"); // try wrong storepass @@ -550,8 +549,8 @@ private void testCRUDWithOnTheFlyUserAuthWithSignedJwtClient(String keystoreFile " --storepass wrong --keypass keypass --alias reg-cli"); assertExitCodeAndStreamSizes(exe, 1, 0, 2); - Assert.assertEquals("login message", "Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0)); - Assert.assertTrue("error message", exe.stderrLines().get(exe.stderrLines().size() - 1).startsWith("Failed to load private key: ")); + Assertions.assertEquals("Logging into " + serverUrl + " as user user1 of realm test", exe.stderrLines().get(0), "login message"); + Assertions.assertTrue(exe.stderrLines().get(exe.stderrLines().size() - 1).startsWith("Failed to load private key: "), "error message"); // try whole CRUD @@ -579,7 +578,7 @@ public void testCRUDWithOnTheFlyServiceAccountWithSignedJwtClient() throws IOExc * Login is performed by each operation again, and again using only client JWT signature - service account is used. */ File keystore = new File(System.getProperty("user.dir") + "/src/test/resources/cli/kcreg/reg-cli-keystore.p12"); - Assert.assertTrue("reg-cli-keystore.p12 exists", keystore.isFile()); + Assertions.assertTrue(keystore.isFile(), "reg-cli-keystore.p12 exists"); testCRUDWithOnTheFlyAuth(serverUrl, "--client reg-cli-jwt --keystore '" + keystore.getAbsolutePath() + "' --storepass storepass --keypass keypass --alias reg-cli", "", @@ -620,21 +619,22 @@ private void testCreateDeleteWithInitialAndRegistrationTokensWithUnsecureOption( KcRegExec exe = execute("create " + (useConfig ? ("--config '" + configFile.getAbsolutePath()) + "'" : "--no-config") + " --insecure --server " + oauth.AUTH_SERVER_ROOT + " --realm " + realm + " -s clientId=test-client2 -o -t " + token); - Assert.assertEquals("exitCode == 0", 0, exe.exitCode()); + Assertions.assertEquals(0, exe.exitCode(), "exitCode == 0"); ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("clientId", "test-client2", client.getClientId()); - Assert.assertNotNull("registrationAccessToken", client.getRegistrationAccessToken()); + Assertions.assertEquals("test-client2", client.getClientId(), "clientId"); + Assertions.assertNotNull(client.getRegistrationAccessToken(), "registrationAccessToken"); if (useConfig) { ConfigData config = handler.loadConfig(); - Assert.assertEquals("Registration Access Token in config file", client.getRegistrationAccessToken(), - config.ensureRealmConfigData(oauth.AUTH_SERVER_ROOT, realm).getClients().get("test-client2")); + Assertions.assertEquals(client.getRegistrationAccessToken(), + config.ensureRealmConfigData(oauth.AUTH_SERVER_ROOT, realm).getClients().get("test-client2"), + "Registration Access Token in config file"); } else { - Assert.assertFalse("There should be no config file", configFile.isFile()); + Assertions.assertFalse(configFile.isFile(), "There should be no config file"); } exe = execute("delete test-client2 " + (useConfig ? ("--config '" + configFile.getAbsolutePath()) + "'" : "--no-config") @@ -670,8 +670,8 @@ private void testCreateWithAllowedHostsWithoutAuthentication(String realm, boole ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("clientId", "test-client", client.getClientId()); - Assert.assertNotNull("registrationAccessToken", client.getRegistrationAccessToken()); + Assertions.assertEquals("test-client", client.getClientId(), "clientId"); + Assertions.assertNotNull(client.getRegistrationAccessToken(), "registrationAccessToken"); exe = execute("delete test-client " + (useConfig ? ("--config '" + configFile.getAbsolutePath()) + "'" : "--no-config") + " --server " + serverUrl + " --realm " + realm + " -t " + client.getRegistrationAccessToken()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegTruststoreTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegTruststoreTest.java index 697345cd37ba..80b426b93ffa 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegTruststoreTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegTruststoreTest.java @@ -9,8 +9,8 @@ import org.keycloak.testsuite.util.TempFileResource; import org.keycloak.testsuite.util.oauth.OAuthClient; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.client.cli.util.OsUtil.EOL; import static org.keycloak.client.registration.cli.KcRegMain.CMD; @@ -31,8 +31,8 @@ public void testTruststore() throws IOException { KcRegExec exe = execute("config truststore --no-config '" + truststore.getAbsolutePath() + "'"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("stderr first line", "Unsupported option: --no-config", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " config truststore --help' for more information on the available options.", exe.stderrLines().get(1)); + Assertions.assertEquals("Unsupported option: --no-config", exe.stderrLines().get(0), "stderr first line"); + Assertions.assertEquals("Try '" + CMD + " config truststore --help' for more information on the available options.", exe.stderrLines().get(1), "try help"); // only run the rest of this test if ssl protected keycloak server is available if (!AUTH_SERVER_SSL_REQUIRED) { @@ -101,19 +101,19 @@ public void testTruststore() throws IOException { exe = execute("config truststore --delete '" + truststore.getAbsolutePath() + "'"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("incompatible", "Option --delete is mutually exclusive with specifying a TRUSTSTORE", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " config truststore --help' for more information on the available options.", exe.stderrLines().get(1)); + Assertions.assertEquals("Option --delete is mutually exclusive with specifying a TRUSTSTORE", exe.stderrLines().get(0), "incompatible"); + Assertions.assertEquals("Try '" + CMD + " config truststore --help' for more information on the available options.", exe.stderrLines().get(1), "try help"); exe = execute("config truststore --delete --trustpass secret"); assertExitCodeAndStreamSizes(exe, 2, 0, 2); - Assert.assertEquals("no truststore error", "Options --trustpass and --delete are mutually exclusive", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " config truststore --help' for more information on the available options.", exe.stderrLines().get(1)); + Assertions.assertEquals("Options --trustpass and --delete are mutually exclusive", exe.stderrLines().get(0), "no truststore error"); + Assertions.assertEquals("Try '" + CMD + " config truststore --help' for more information on the available options.", exe.stderrLines().get(1), "try help"); FileConfigHandler cfghandler = new FileConfigHandler(); FileConfigHandler.setConfigFile(DEFAULT_CONFIG_FILE_PATH); ConfigData config = cfghandler.loadConfig(); - Assert.assertNull("truststore null", config.getTruststore()); - Assert.assertNull("trustpass null", config.getTrustpass()); + Assertions.assertNull(config.getTruststore(), "truststore null"); + Assertions.assertNull(config.getTrustpass(), "trustpass null"); // perform no-config CRUD test against ssl protected endpoint diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegUpdateTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegUpdateTest.java index 4262d11864fb..d3ecfc792994 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegUpdateTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegUpdateTest.java @@ -10,8 +10,8 @@ import org.keycloak.testsuite.util.TempFileResource; import org.keycloak.util.JsonSerialization; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.client.registration.cli.KcRegMain.CMD; import static org.keycloak.testsuite.cli.KcRegExec.execute; @@ -41,10 +41,10 @@ public void testUpdateThoroughly() throws IOException { ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("enabled", true, client.isEnabled()); - Assert.assertEquals("publicClient", false, client.isPublicClient()); - Assert.assertEquals("bearerOnly", false, client.isBearerOnly()); - Assert.assertTrue("redirectUris is empty", client.getRedirectUris().isEmpty()); + Assertions.assertEquals(true, client.isEnabled(), "enabled"); + Assertions.assertEquals(false, client.isPublicClient(), "publicClient"); + Assertions.assertEquals(false, client.isBearerOnly(), "bearerOnly"); + Assertions.assertTrue(client.getRedirectUris().isEmpty(), "redirectUris is empty"); // Merge update @@ -54,8 +54,8 @@ public void testUpdateThoroughly() throws IOException { assertExitCodeAndStdErrSize(exe, 0, 0); client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("enabled", false, client.isEnabled()); - Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris()); + Assertions.assertEquals(false, client.isEnabled(), "enabled"); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris(), "redirectUris"); @@ -66,8 +66,8 @@ public void testUpdateThoroughly() throws IOException { client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertTrue("redirectUris is empty", client.getRedirectUris().isEmpty()); - Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8981/myapp"), client.getWebOrigins()); + Assertions.assertTrue(client.getRedirectUris().isEmpty(), "redirectUris is empty"); + Assertions.assertEquals(Arrays.asList("http://localhost:8981/myapp"), client.getWebOrigins(), "webOrigins"); @@ -93,15 +93,15 @@ public void testUpdateThoroughly() throws IOException { exe = execute("update my_client --nonexisting --config '" + configFile.getName() + "'"); assertExitCodeAndStreamSizes(exe, 2, 0, 3); - Assert.assertEquals("error message", "Unknown option: '--nonexisting'", exe.stderrLines().get(0)); - Assert.assertEquals("try help", "Try '" + CMD + " update --help' for more information on the available options.", exe.stderrLines().get(2)); + Assertions.assertEquals("Unknown option: '--nonexisting'", exe.stderrLines().get(0), "error message"); + Assertions.assertEquals("Try '" + CMD + " update --help' for more information on the available options.", exe.stderrLines().get(2), "try help"); // try use incompatible endpoint exe = execute("update my_client --config '" + configFile.getName() + "' -o -s enabled=true -e oidc"); assertExitCodeAndStreamSizes(exe, 1, 0, 1); - Assert.assertEquals("error message", "Failed to set attribute 'enabled' on document type 'oidc'", exe.stderrLines().get(exe.stderrLines().size() - 1)); + Assertions.assertEquals("Failed to set attribute 'enabled' on document type 'oidc'", exe.stderrLines().get(exe.stderrLines().size() - 1), "error message"); @@ -116,9 +116,9 @@ public void testUpdateThoroughly() throws IOException { client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); // web origin is not sent to the server, thus it retains the current value - Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8981/myapp"), client.getWebOrigins()); - Assert.assertFalse("enabled is false", client.isEnabled()); - Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris()); + Assertions.assertEquals(Arrays.asList("http://localhost:8981/myapp"), client.getWebOrigins(), "webOrigins"); + Assertions.assertFalse(client.isEnabled(), "enabled is false"); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris(), "redirectUris"); @@ -132,9 +132,9 @@ public void testUpdateThoroughly() throws IOException { assertExitCodeAndStdErrSize(exe, 0, 0); client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8980/myapp"), client.getWebOrigins()); - Assert.assertTrue("enabled is true", client.isEnabled()); - Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris()); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp"), client.getWebOrigins(), "webOrigins"); + Assertions.assertTrue(client.isEnabled(), "enabled is true"); + Assertions.assertEquals(Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris(), "redirectUris"); @@ -144,7 +144,7 @@ public void testUpdateThoroughly() throws IOException { assertExitCodeAndStdErrSize(exe, 0, 0); - Assert.assertNull("my_client registration token", handler.loadConfig().ensureRealmConfigData(serverUrl, realm).getClients().get("my_client")); + Assertions.assertNull(handler.loadConfig().ensureRealmConfigData(serverUrl, realm).getClients().get("my_client"), "my_client registration token"); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegUpdateTokenTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegUpdateTokenTest.java index 26159253efae..84dd542597e5 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegUpdateTokenTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/registration/KcRegUpdateTokenTest.java @@ -11,8 +11,8 @@ import org.keycloak.testsuite.util.TempFileResource; import org.keycloak.util.JsonSerialization; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.cli.KcRegExec.execute; @@ -35,7 +35,7 @@ public void testUpdateToken() throws IOException { // read current registration access token ConfigData data = ConfigUtil.loadConfig(); RealmConfigData rdata = data.getRealmConfigData(serverUrl, "test"); - Assert.assertNull("realm info set", rdata); + Assertions.assertNull(rdata, "realm info set"); // update registration access token exe = execute("update-token --config '" + configFile.getName() + "' reg-cli-secret-direct --server " + serverUrl + " --realm test --user user1 --password userpass"); @@ -45,10 +45,10 @@ public void testUpdateToken() throws IOException { // read current registration token data = ConfigUtil.loadConfig(); rdata = data.getRealmConfigData(serverUrl, "test"); - Assert.assertEquals("current session realm unchanged", "master", data.getRealm()); - Assert.assertNotNull("realm info set", rdata); - Assert.assertNull("on the fly login was transient", rdata.getToken()); - Assert.assertNotNull("client info has registration access token", rdata.getClients().get("reg-cli-secret-direct")); + Assertions.assertEquals("master", data.getRealm(), "current session realm unchanged"); + Assertions.assertNotNull(rdata, "realm info set"); + Assertions.assertNull(rdata.getToken(), "on the fly login was transient"); + Assertions.assertNotNull(rdata.getClients().get("reg-cli-secret-direct"), "client info has registration access token"); // use --no-config and on-the-fly auth exe = execute("update-token reg-cli-secret-direct --no-config --server " + serverUrl + " --realm test --user user1 --password userpass"); @@ -63,7 +63,7 @@ public void testUpdateToken() throws IOException { assertExitCodeAndStdErrSize(exe, 0, 0); ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class); - Assert.assertEquals("client representation returned", "reg-cli-secret-direct", client.getClientId()); + Assertions.assertEquals("reg-cli-secret-direct", client.getClientId(), "client representation returned"); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/AbstractFAPI2Test.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/AbstractFAPI2Test.java index 8a3342ceb7c5..95b4db299fa9 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/AbstractFAPI2Test.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/AbstractFAPI2Test.java @@ -38,10 +38,10 @@ import static org.keycloak.testsuite.util.ClientPoliciesUtil.createAnyClientConditionConfig; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Test for the FAPI 2 specifications (still implementer's draft): diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/AbstractFAPITest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/AbstractFAPITest.java index d7a899b0eebf..f7714faeed45 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/AbstractFAPITest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/AbstractFAPITest.java @@ -42,7 +42,6 @@ import org.keycloak.representations.idm.CredentialRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.client.policies.AbstractClientPoliciesTest; import org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource; @@ -68,10 +67,11 @@ import org.junit.After; import org.junit.Assume; import org.junit.BeforeClass; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public abstract class AbstractFAPITest extends AbstractClientPoliciesTest { @@ -133,8 +133,8 @@ public void addTestRealms(List testRealms) { public static void assertScopes(String expectedScope, String receivedScope) { Collection expectedScopes = Arrays.asList(expectedScope.split(" ")); Collection receivedScopes = Arrays.asList(receivedScope.split(" ")); - Assert.assertTrue("Not matched. expectedScope: " + expectedScope + ", receivedScope: " + receivedScope, - expectedScopes.containsAll(receivedScopes) && receivedScopes.containsAll(expectedScopes)); + Assertions.assertTrue(expectedScopes.containsAll(receivedScopes) && receivedScopes.containsAll(expectedScopes), + "Not matched. expectedScope: " + expectedScope + ", receivedScope: " + receivedScope); } protected String loginUserAndGetCode(String clientId, String nonce, boolean fragmentResponseModeExpected) { @@ -146,7 +146,7 @@ protected String loginUserAndGetCode(String clientId, String nonce, boolean frag grantPage.accept(); String code = oauth.parseLoginResponse().getCode(); - Assert.assertNotNull(code); + Assertions.assertNotNull(code); return code; } @@ -160,7 +160,7 @@ protected String loginUserAndGetCodeInJwtQueryResponseMode(String clientId, Stri AuthorizationResponseToken responseToken = oauth.verifyAuthorizationResponseToken(oauth.parseLoginResponse().getResponse()); String code = (String)responseToken.getOtherClaims().get("code"); - Assert.assertNotNull(code); + Assertions.assertNotNull(code); return code; } @@ -170,24 +170,24 @@ protected void assertSuccessfulTokenResponse(AccessTokenResponse tokenResponse) MatcherAssert.assertThat(tokenResponse.getAccessToken(), Matchers.notNullValue()); // Scope parameter must be present per FAPI - Assert.assertNotNull(tokenResponse.getScope()); + Assertions.assertNotNull(tokenResponse.getScope()); assertScopes("openid profile email", tokenResponse.getScope()); // ID Token contains all the claims IDToken idToken = oauth.verifyIDToken(tokenResponse.getIdToken()); - Assert.assertNotNull(idToken.getId()); - Assert.assertEquals("foo", idToken.getIssuedFor()); - Assert.assertEquals("john", idToken.getPreferredUsername()); - Assert.assertEquals("john@keycloak.org", idToken.getEmail()); - Assert.assertEquals("Johny", idToken.getGivenName()); - Assert.assertEquals("123456", idToken.getNonce()); + Assertions.assertNotNull(idToken.getId()); + Assertions.assertEquals("foo", idToken.getIssuedFor()); + Assertions.assertEquals("john", idToken.getPreferredUsername()); + Assertions.assertEquals("john@keycloak.org", idToken.getEmail()); + Assertions.assertEquals("Johny", idToken.getGivenName()); + Assertions.assertEquals("123456", idToken.getNonce()); } protected void logoutUserAndRevokeConsent(String clientId, String username) { UserResource user = AdminApiUtil.findUserByUsernameId(adminClient.realm(REALM_NAME), username); user.logout(); List> consents = user.getConsents(); - org.junit.Assert.assertEquals(1, consents.size()); + Assertions.assertEquals(1, consents.size()); user.revokeConsent(clientId); } @@ -200,7 +200,7 @@ protected void assertRedirectedToClientWithError(String expectedError, String ex protected void assertBrowserWithError(String expectedError) { errorPage.assertCurrent(); - Assert.assertEquals(expectedError, errorPage.getError()); + Assertions.assertEquals(expectedError, errorPage.getError()); } protected AccessTokenResponse doAccessTokenRequestWithClientSignedJWT(String code, String signedJwt, Supplier httpClientSupplier) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/AdapterInstallationConfigTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/AdapterInstallationConfigTest.java index 29c22f4a996b..b0360b5f6afb 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/AdapterInstallationConfigTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/AdapterInstallationConfigTest.java @@ -28,9 +28,9 @@ import static org.keycloak.testsuite.util.ServerURLs.AUTH_SERVER_SSL_REQUIRED; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Stian Thorgersen diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/CIBATest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/CIBATest.java index dc5ebe4992be..14b1de6a934a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/CIBATest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/CIBATest.java @@ -97,11 +97,11 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.hamcrest.CoreMatchers; -import org.junit.Assert; import org.junit.Assume; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelResponse.Status.CANCELLED; import static org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelResponse.Status.SUCCEED; @@ -122,9 +122,9 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests for the CIBA "poll" mode and generic CIBA functionality tests @@ -782,7 +782,7 @@ public void testBackchannelClientValidations() throws Exception { attributes.put(CibaConfig.OIDC_CIBA_GRANT_ENABLED, Boolean.TRUE.toString()); clientRep.setAttributes(attributes); clientResource.update(clientRep); - Assert.fail("Not expected to successfully update client"); + Assertions.fail("Not expected to successfully update client"); } catch (BadRequestException bre) { // Expected } @@ -793,14 +793,14 @@ public void testBackchannelClientValidations() throws Exception { clientRep = clientResource.toRepresentation(); attributes = Optional.ofNullable(clientRep.getAttributes()).orElse(new HashMap<>()); - Assert.assertEquals("ping", attributes.get(CibaConfig.CIBA_BACKCHANNEL_TOKEN_DELIVERY_MODE_PER_CLIENT)); - Assert.assertEquals(TestApplicationResourceUrls.cibaClientNotificationEndpointUri(), attributes.get(CibaConfig.CIBA_BACKCHANNEL_CLIENT_NOTIFICATION_ENDPOINT)); + Assertions.assertEquals("ping", attributes.get(CibaConfig.CIBA_BACKCHANNEL_TOKEN_DELIVERY_MODE_PER_CLIENT)); + Assertions.assertEquals(TestApplicationResourceUrls.cibaClientNotificationEndpointUri(), attributes.get(CibaConfig.CIBA_BACKCHANNEL_CLIENT_NOTIFICATION_ENDPOINT)); // Update to "Push" mode should fail try { attributes.put(CibaConfig.CIBA_BACKCHANNEL_TOKEN_DELIVERY_MODE_PER_CLIENT, "push"); clientResource.update(clientRep); - Assert.fail("Not expected to successfully update client"); + Assertions.fail("Not expected to successfully update client"); } catch (BadRequestException bre) { // Expected } @@ -810,7 +810,7 @@ public void testBackchannelClientValidations() throws Exception { attributes.put(CibaConfig.CIBA_BACKCHANNEL_TOKEN_DELIVERY_MODE_PER_CLIENT, "ping"); attributes.put(CibaConfig.CIBA_BACKCHANNEL_AUTH_REQUEST_SIGNING_ALG, Algorithm.HS256); clientResource.update(clientRep); - Assert.fail("Not expected to successfully update client"); + Assertions.fail("Not expected to successfully update client"); } catch (BadRequestException bre) { // Expected } @@ -821,7 +821,7 @@ public void testBackchannelClientValidations() throws Exception { clientRep = clientResource.toRepresentation(); attributes = Optional.ofNullable(clientRep.getAttributes()).orElse(new HashMap<>()); - Assert.assertEquals(Algorithm.PS256, attributes.get(CibaConfig.CIBA_BACKCHANNEL_AUTH_REQUEST_SIGNING_ALG)); + Assertions.assertEquals(Algorithm.PS256, attributes.get(CibaConfig.CIBA_BACKCHANNEL_AUTH_REQUEST_SIGNING_ALG)); // Revert algorithm attributes.remove(CibaConfig.CIBA_BACKCHANNEL_AUTH_REQUEST_SIGNING_ALG); @@ -883,7 +883,7 @@ public void testPingModeSuccess() throws Exception { // user Backchannel Authentication Request AuthenticationRequestAcknowledgement response = doBackchannelAuthenticationRequest(TEST_CLIENT_NAME, TEST_CLIENT_PASSWORD, username, bindingMessage, clientNotificationToken, additionalParameters); - Assert.assertTrue(response.getInterval() > 0); // Even in the ping mode should be interval set according to the CIBA specification + Assertions.assertTrue(response.getInterval() > 0); // Even in the ping mode should be interval set according to the CIBA specification // user Authentication Channel Request TestAuthenticationChannelRequest testRequest = doAuthenticationChannelRequest(bindingMessage); @@ -894,7 +894,7 @@ public void testPingModeSuccess() throws Exception { // Check clientNotification not yet available ClientNotificationEndpointRequest pushedClientNotification = testingClient.testApp().oidcClientEndpoints().getPushedCibaClientNotification(clientNotificationToken); - Assert.assertNull(pushedClientNotification.getAuthReqId()); + Assertions.assertNull(pushedClientNotification.getAuthReqId()); // user Authentication Channel completed EventRepresentation loginEvent = doAuthenticationChannelCallback(testRequest); @@ -904,7 +904,7 @@ public void testPingModeSuccess() throws Exception { // Check clientNotification exists now for our authReqId pushedClientNotification = testingClient.testApp().oidcClientEndpoints().getPushedCibaClientNotification(clientNotificationToken); - Assert.assertEquals(pushedClientNotification.getAuthReqId(), response.getAuthReqId()); + Assertions.assertEquals(pushedClientNotification.getAuthReqId(), response.getAuthReqId()); // user Token Request AccessTokenResponse tokenRes = doBackchannelAuthenticationTokenRequest(username, response.getAuthReqId()); @@ -956,7 +956,7 @@ public void testPingMode_clientNotificationSentEvenForUserCancel() throws Except // Check client notification is present even if user cancelled authentication ClientNotificationEndpointRequest pushedClientNotification = testingClient.testApp().oidcClientEndpoints().getPushedCibaClientNotification("client-notification-some"); - Assert.assertEquals(pushedClientNotification.getAuthReqId(), response.getAuthReqId()); + Assertions.assertEquals(pushedClientNotification.getAuthReqId(), response.getAuthReqId()); // user Token Request AccessTokenResponse tokenRes = oauth.ciba().doBackchannelAuthenticationTokenRequest(response.getAuthReqId()); @@ -1035,7 +1035,7 @@ public void testExplicitConsentRequiredBackchannelAuthenticationFlows() throws E // client Authentication Channel Request TestAuthenticationChannelRequest clientAuthenticationChannelReq = doAuthenticationChannelRequest("asdfghjkl"); - Assert.assertTrue(clientAuthenticationChannelReq.getRequest().getConsentRequired()); + Assertions.assertTrue(clientAuthenticationChannelReq.getRequest().getConsentRequired()); assertThat(clientAuthenticationChannelReq.getRequest().getScope(), is(containsString(OAuth2Constants.SCOPE_OPENID))); assertThat(clientAuthenticationChannelReq.getRequest().getScope(), is(containsString("email"))); assertThat(clientAuthenticationChannelReq.getRequest().getScope(), is(containsString("profile"))); @@ -1414,7 +1414,7 @@ public void testCibaGrantDeactivated() throws Exception { clientResource.update(clientRep); //clientResource = ApiUtil.findClientByClientId(adminClient.realm(TEST_REALM_NAME), TEST_CLIENT_NAME); clientRep = clientResource.toRepresentation(); - Assert.assertNull(clientRep.getAttributes().get(CibaConfig.OIDC_CIBA_GRANT_ENABLED)); + Assertions.assertNull(clientRep.getAttributes().get(CibaConfig.OIDC_CIBA_GRANT_ENABLED)); assertThat(clientRep.getAttributes().get(CibaConfig.CIBA_BACKCHANNEL_AUTH_REQUEST_SIGNING_ALG), is(Algorithm.RS256)); // user Backchannel Authentication Request @@ -1475,8 +1475,8 @@ public void testCibaGrantDeactivated() throws Exception { public void testCibaGrantSettingByDynamicClientRegistration() throws Exception { String clientId = createClientDynamically(generateSuffixedName("valid-CIBA-CD"), (OIDCClientRepresentation clientRep) -> {}); OIDCClientRepresentation rep = getClientDynamically(clientId); - Assert.assertFalse(rep.getGrantTypes().contains(OAuth2Constants.CIBA_GRANT_TYPE)); - Assert.assertNull(rep.getBackchannelAuthenticationRequestSigningAlg()); + Assertions.assertFalse(rep.getGrantTypes().contains(OAuth2Constants.CIBA_GRANT_TYPE)); + Assertions.assertNull(rep.getBackchannelAuthenticationRequestSigningAlg()); updateClientDynamically(clientId, (OIDCClientRepresentation clientRep) -> { List grantTypes = Optional.ofNullable(clientRep.getGrantTypes()).orElse(new ArrayList<>()); grantTypes.add(OAuth2Constants.CIBA_GRANT_TYPE); @@ -1485,7 +1485,7 @@ public void testCibaGrantSettingByDynamicClientRegistration() throws Exception { }); rep = getClientDynamically(clientId); - Assert.assertTrue(rep.getGrantTypes().contains(OAuth2Constants.CIBA_GRANT_TYPE)); + Assertions.assertTrue(rep.getGrantTypes().contains(OAuth2Constants.CIBA_GRANT_TYPE)); assertThat(rep.getBackchannelAuthenticationRequestSigningAlg(), is(Algorithm.PS256)); } @@ -1959,7 +1959,7 @@ public void testExtendedClientPolicyInterfacesForBackchannelTokenRequest() throw // user Backchannel Authentication Request AuthenticationRequestAcknowledgement response = oauth.ciba().backchannelAuthenticationRequest(TEST_USER_NAME).bindingMessage(bindingMessage).additionalParams(additionalParameters).send(); assertThat(response.getStatusCode(), is(equalTo(200))); - Assert.assertNotNull(response.getAuthReqId()); + Assertions.assertNotNull(response.getAuthReqId()); TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints(); TestAuthenticationChannelRequest authenticationChannelReq = oidcClientEndpointsResource.getAuthenticationChannel(bindingMessage); @@ -2023,7 +2023,7 @@ public void testExtendedClientPolicyInterfacesForBackchannelTokenResponse() thro // user Backchannel Authentication Request AuthenticationRequestAcknowledgement response = oauth.ciba().backchannelAuthenticationRequest(TEST_USER_NAME).bindingMessage(bindingMessage).additionalParams(additionalParameters).send(); assertThat(response.getStatusCode(), is(equalTo(200))); - Assert.assertNotNull(response.getAuthReqId()); + Assertions.assertNotNull(response.getAuthReqId()); TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints(); TestAuthenticationChannelRequest authenticationChannelReq = oidcClientEndpointsResource.getAuthenticationChannel(bindingMessage); @@ -2436,7 +2436,7 @@ public void testClientScopesCondition() throws Exception { response = oauth.ciba().backchannelAuthenticationRequest(username).bindingMessage(bindingMessage).additionalParams(additionalParameters).send(); assertThat(response.getStatusCode(), is(equalTo(200))); - Assert.assertNotNull(response.getAuthReqId()); + Assertions.assertNotNull(response.getAuthReqId()); json = (new ClientProfilesBuilder()).addProfile( (new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Het Eerste Profiel") @@ -2808,7 +2808,7 @@ private AuthenticationRequestAcknowledgement doBackchannelAuthenticationRequest( oauth.client(clientId, clientSecret); AuthenticationRequestAcknowledgement response = oauth.ciba().backchannelAuthenticationRequest(username).request(request).requestUri(requestUri).bindingMessage(bindingMessage).clientNotificationToken(clientNotificationToken).additionalParams(additionalParameters).send(); assertThat(response.getStatusCode(), is(equalTo(200))); - Assert.assertNotNull(response.getAuthReqId()); + Assertions.assertNotNull(response.getAuthReqId()); return response; } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientRedirectTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientRedirectTest.java index 96ed00d0fbbf..45a1686e9331 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientRedirectTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientRedirectTest.java @@ -45,7 +45,7 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Thomas Darimont diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientRegistrationPoliciesTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientRegistrationPoliciesTest.java index ee2009e768c2..3b40ead0aabe 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientRegistrationPoliciesTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientRegistrationPoliciesTest.java @@ -62,15 +62,15 @@ import org.keycloak.services.clientregistration.policy.impl.MaxClientsClientRegistrationPolicyFactory; import org.keycloak.services.clientregistration.policy.impl.ProtocolMappersClientRegistrationPolicyFactory; import org.keycloak.services.clientregistration.policy.impl.TrustedHostClientRegistrationPolicyFactory; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.util.JsonSerialization; import org.junit.After; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Marek Posolda @@ -144,12 +144,12 @@ private void assertOidcFail(ClientRegOp operation, OIDCClientRepresentation clie break; } - Assert.fail("Not expected to successfuly run operation " + operation.toString() + " on client"); + Assertions.fail("Not expected to successfuly run operation " + operation.toString() + " on client"); } catch (ClientRegistrationException expected) { HttpErrorException httpEx = (HttpErrorException) expected.getCause(); - Assert.assertEquals(expectedStatusCode, httpEx.getStatusLine().getStatusCode()); + Assertions.assertEquals(expectedStatusCode, httpEx.getStatusLine().getStatusCode()); if (expectedErrorContains != null) { - assertTrue("Error response doesn't contain expected text. The error response text is: " + httpEx.getErrorResponse(), httpEx.getErrorResponse().contains(expectedErrorContains)); + assertTrue(httpEx.getErrorResponse().contains(expectedErrorContains), "Error response doesn't contain expected text. The error response text is: " + httpEx.getErrorResponse()); } } } @@ -165,12 +165,12 @@ private void assertFail(ClientRegOp operation, ClientRepresentation client, int break; } - Assert.fail("Not expected to successfuly run operation " + operation.toString() + " on client"); + Assertions.fail("Not expected to successfuly run operation " + operation.toString() + " on client"); } catch (ClientRegistrationException expected) { HttpErrorException httpEx = (HttpErrorException) expected.getCause(); - Assert.assertEquals(expectedStatusCode, httpEx.getStatusLine().getStatusCode()); + Assertions.assertEquals(expectedStatusCode, httpEx.getStatusLine().getStatusCode()); if (expectedErrorContains != null) { - assertTrue("Error response doesn't contain expected text. The error response text is: " + httpEx.getErrorResponse(), httpEx.getErrorResponse().contains(expectedErrorContains)); + assertTrue(httpEx.getErrorResponse().contains(expectedErrorContains), "Error response doesn't contain expected text. The error response text is: " + httpEx.getErrorResponse()); } } } @@ -265,7 +265,7 @@ public void testAnonConsentRequired() throws Exception { // Assert new client has consent required String clientId = client.getClientId(); ClientRepresentation clientRep = AdminApiUtil.findClientByClientId(realmResource(), clientId).toRepresentation(); - Assert.assertTrue(clientRep.isConsentRequired()); + Assertions.assertTrue(clientRep.isConsentRequired()); // Try update with disabled consent required. Should fail clientRep.setConsentRequired(false); @@ -285,7 +285,7 @@ public void testAnonFullScopeAllowed() throws Exception { // Assert new client has fullScopeAllowed disabled String clientId = client.getClientId(); ClientRepresentation clientRep = AdminApiUtil.findClientByClientId(realmResource(), clientId).toRepresentation(); - Assert.assertFalse(clientRep.isFullScopeAllowed()); + Assertions.assertFalse(clientRep.isFullScopeAllowed()); // Try update with disabled consent required. Should fail clientRep.setFullScopeAllowed(true); @@ -305,7 +305,7 @@ public void testClientDisabledPolicy() throws Exception { OIDCClientRepresentation client = create(); String clientId = client.getClientId(); ClientRepresentation clientRep = AdminApiUtil.findClientByClientId(realmResource(), clientId).toRepresentation(); - Assert.assertTrue(clientRep.isEnabled()); + Assertions.assertTrue(clientRep.isEnabled()); // Add client-disabled policy ComponentRepresentation rep = new ComponentRepresentation(); @@ -322,7 +322,7 @@ public void testClientDisabledPolicy() throws Exception { client = create(); clientId = client.getClientId(); clientRep = AdminApiUtil.findClientByClientId(realmResource(), clientId).toRepresentation(); - Assert.assertFalse(clientRep.isEnabled()); + Assertions.assertFalse(clientRep.isEnabled()); // Try enable client. Should fail clientRep.setEnabled(true); @@ -383,11 +383,11 @@ public void testProviders() throws Exception { // test that clientScope provider contains just the default client scopes ComponentTypeRepresentation clientScopeRep = providersMap.get(ClientScopesClientRegistrationPolicyFactory.PROVIDER_ID); List clientScopes = getProviderConfigProperty(clientScopeRep, ClientScopesClientRegistrationPolicyFactory.ALLOWED_CLIENT_SCOPES); - Assert.assertFalse(clientScopes.isEmpty()); - Assert.assertTrue(clientScopes.contains(OAuth2Constants.SCOPE_PROFILE)); - Assert.assertTrue(clientScopes.contains(OAuth2Constants.SCOPE_OPENID)); - Assert.assertFalse(clientScopes.contains("foo")); - Assert.assertFalse(clientScopes.contains("bar")); + Assertions.assertFalse(clientScopes.isEmpty()); + Assertions.assertTrue(clientScopes.contains(OAuth2Constants.SCOPE_PROFILE)); + Assertions.assertTrue(clientScopes.contains(OAuth2Constants.SCOPE_OPENID)); + Assertions.assertFalse(clientScopes.contains("foo")); + Assertions.assertFalse(clientScopes.contains("bar")); // Add some clientScopes ClientScopeRepresentation clientScope = new ClientScopeRepresentation(); @@ -413,8 +413,8 @@ public void testProviders() throws Exception { }).findFirst().get(); clientScopes = getProviderConfigProperty(clientScopeRep, ClientScopesClientRegistrationPolicyFactory.ALLOWED_CLIENT_SCOPES); - Assert.assertTrue(clientScopes.contains("foo")); - Assert.assertTrue(clientScopes.contains("bar")); + Assertions.assertTrue(clientScopes.contains("foo")); + Assertions.assertTrue(clientScopes.contains("bar")); // Revert client scopes realmResource().clientScopes().get(fooScopeId).remove(); @@ -422,7 +422,7 @@ public void testProviders() throws Exception { } private List getProviderConfigProperty(ComponentTypeRepresentation provider, String expectedConfigPropName) { - Assert.assertNotNull(provider); + Assertions.assertNotNull(provider); List list = provider.getProperties(); @@ -432,10 +432,10 @@ private List getProviderConfigProperty(ComponentTypeRepresentation provi }).collect(Collectors.toList()); - Assert.assertEquals(list.size(), 1); + Assertions.assertEquals(list.size(), 1); ConfigPropertyRepresentation allowedProtocolMappers = list.get(0); - Assert.assertEquals(allowedProtocolMappers.getName(), expectedConfigPropName); + Assertions.assertEquals(allowedProtocolMappers.getName(), expectedConfigPropName); return allowedProtocolMappers.getOptions(); } @@ -503,7 +503,7 @@ public void testClientScopesPolicyWithPermittedScope() throws Exception { // Check that I can register client now ClientRepresentation registeredClient = reg.create(clientRep); - Assert.assertNotNull(registeredClient.getRegistrationAccessToken()); + Assertions.assertNotNull(registeredClient.getRegistrationAccessToken()); // Revert client scope AdminApiUtil.findClientResourceByClientId(realmResource(), "test-app").remove(); @@ -534,7 +534,7 @@ public void testProtocolMappersCreate() throws Exception { // Check authenticated registration is permitted ClientRepresentation registeredClient = reg.create(clientRep); - Assert.assertNotNull(registeredClient.getRegistrationAccessToken()); + Assertions.assertNotNull(registeredClient.getRegistrationAccessToken()); // Check "anonymous" registration still fails clientRep = createRep("test-app-2"); @@ -690,7 +690,7 @@ public void testProtocolMappersConsentRequired() throws Exception { ClientRepresentation clientRep = createRep("test-app"); ClientRepresentation registeredClient = reg.create(clientRep); - Assert.assertNull(registeredClient.getProtocolMappers()); + Assertions.assertNull(registeredClient.getProtocolMappers()); // Revert AdminApiUtil.findClientResourceByClientId(realmResource(), "test-app").remove(); @@ -712,7 +712,7 @@ public void testProtocolMappersRemoveBuiltins() throws Exception { clientRep.setProtocolMappers(Collections.singletonList(createHardcodedMapperRep())); ClientRepresentation registeredClient = reg.create(clientRep); - Assert.assertEquals(1, registeredClient.getProtocolMappers().size()); + Assertions.assertEquals(1, registeredClient.getProtocolMappers().size()); ProtocolMapperRepresentation hardcodedMapper = registeredClient.getProtocolMappers().get(0); // Revert @@ -734,15 +734,15 @@ public void testRegisterFakeClientScope() { rep.getConfig().putSingle(ClientScopesClientRegistrationPolicyFactory.ALLOWED_CLIENT_SCOPES, "foo1"); Response response = realmResource().components().add(rep); ErrorRepresentation error = response.readEntity(ErrorRepresentation.class); - Assert.assertEquals("Client scopes not allowed: [foo1]", error.getErrorMessage()); + Assertions.assertEquals("Client scopes not allowed: [foo1]", error.getErrorMessage()); //update ComponentRepresentation clientScopesPolicyRep = findPolicyByProviderAndAuth(ClientScopesClientRegistrationPolicyFactory.PROVIDER_ID, getPolicyAnon()); clientScopesPolicyRep.getConfig().putSingle(ClientScopesClientRegistrationPolicyFactory.ALLOWED_CLIENT_SCOPES, "foo2"); - BadRequestException e = Assert.assertThrows(BadRequestException.class, + BadRequestException e = Assertions.assertThrows(BadRequestException.class, () -> realmResource().components().component(clientScopesPolicyRep.getId()).update(clientScopesPolicyRep)); error = e.getResponse().readEntity(ErrorRepresentation.class); - Assert.assertEquals("Client scopes not allowed: [foo2]", error.getErrorMessage()); + Assertions.assertEquals("Client scopes not allowed: [foo2]", error.getErrorMessage()); } // HELPER METHODS @@ -777,7 +777,7 @@ private void setTrustedHost(String hostname) { private void assertRegAccessToken(String registrationAccessToken, RegistrationAuth expectedRegAuth) throws Exception { byte[] content = new JWSInput(registrationAccessToken).getContent(); RegistrationAccessToken regAccessToken = JsonSerialization.readValue(content, RegistrationAccessToken.class); - Assert.assertEquals(regAccessToken.getRegistrationAuth(), expectedRegAuth.toString().toLowerCase()); + Assertions.assertEquals(regAccessToken.getRegistrationAuth(), expectedRegAuth.toString().toLowerCase()); } private enum ClientRegOp { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientRegistrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientRegistrationTest.java index 352c6e36d1d2..2518805fe482 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientRegistrationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientRegistrationTest.java @@ -87,12 +87,12 @@ import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Stian Thorgersen @@ -218,8 +218,7 @@ public void registerOid4vcClientShouldBeRejected() { client.setProtocol("oid4vc"); Response response = adminClient.realm(REALM_NAME).clients().create(client); - assertEquals("Creating a client with OID4VC protocol should be rejected as it is not a valid protocol for clients.", - 400, response.getStatus()); + assertEquals(400, response.getStatus(), "Creating a client with OID4VC protocol should be rejected as it is not a valid protocol for clients."); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientSecretRotationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientSecretRotationTest.java index 57285c18f863..001bfef02117 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientSecretRotationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientSecretRotationTest.java @@ -70,8 +70,8 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Marcelo Sales diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientTypesTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientTypesTest.java index 53bcc15e8bae..c952334bb003 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientTypesTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientTypesTest.java @@ -38,7 +38,6 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.services.clienttype.impl.DefaultClientTypeProviderFactory; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.arquillian.annotation.DisableFeature; import org.keycloak.testsuite.arquillian.annotation.EnableFeature; @@ -46,6 +45,7 @@ import org.keycloak.testsuite.util.ClientBuilder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.common.Profile.Feature.CLIENT_TYPES; @@ -53,10 +53,10 @@ import static org.hamcrest.Matchers.everyItem; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.in; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Marek Posolda @@ -87,15 +87,15 @@ public void testCreateClientWithClientType() { assertEquals("foo", clientRep.getClientId()); assertEquals(ClientTypeManager.SERVICE_ACCOUNT, clientRep.getType()); assertEquals(OIDCLoginProtocol.LOGIN_PROTOCOL, clientRep.getProtocol()); - Assert.assertFalse(clientRep.isStandardFlowEnabled()); - Assert.assertFalse(clientRep.isImplicitFlowEnabled()); - Assert.assertFalse(clientRep.isDirectAccessGrantsEnabled()); - Assert.assertTrue(clientRep.isServiceAccountsEnabled()); - Assert.assertFalse(clientRep.isPublicClient()); - Assert.assertFalse(clientRep.isBearerOnly()); + Assertions.assertFalse(clientRep.isStandardFlowEnabled()); + Assertions.assertFalse(clientRep.isImplicitFlowEnabled()); + Assertions.assertFalse(clientRep.isDirectAccessGrantsEnabled()); + Assertions.assertTrue(clientRep.isServiceAccountsEnabled()); + Assertions.assertFalse(clientRep.isPublicClient()); + Assertions.assertFalse(clientRep.isBearerOnly()); // Check type not included as client attribute - Assert.assertFalse(clientRep.getAttributes().containsKey(ClientModel.TYPE)); + Assertions.assertFalse(clientRep.getAttributes().containsKey(ClientModel.TYPE)); } @Test @@ -117,7 +117,7 @@ public void testUpdateClientWithClientType() { clientRep.setType(ClientTypeManager.STANDARD); try { testRealm().clients().get(clientRep.getId()).update(clientRep); - Assert.fail("Not expected to update client"); + Assertions.fail("Not expected to update client"); } catch (BadRequestException bre) { assertErrorContainsMessage(bre, ClientTypeException.Message.CANNOT_CHANGE_CLIENT_TYPE); } @@ -127,7 +127,7 @@ public void testUpdateClientWithClientType() { clientRep.setServiceAccountsEnabled(false); try { testRealm().clients().get(clientRep.getId()).update(clientRep); - Assert.fail("Not expected to update client"); + Assertions.fail("Not expected to update client"); } catch (BadRequestException bre) { assertErrorResponseContainsParams(bre.getResponse(), "serviceAccountsEnabled"); } @@ -195,7 +195,7 @@ public void testClientTypesAdminRestAPI_realmTypes() { clientType.setConfig(new HashMap<>()); clientTypes.setRealmClientTypes(List.of(clientType)); testRealm().clientTypes().updateClientTypes(clientTypes); - Assert.fail("Not expected to update client types"); + Assertions.fail("Not expected to update client types"); } catch (BadRequestException bre) { assertErrorContainsMessage(bre, ClientTypeException.Message.INVALID_CLIENT_TYPE_PROVIDER); } @@ -206,7 +206,7 @@ public void testClientTypesAdminRestAPI_realmTypes() { ClientTypeRepresentation.PropertyConfig cfg = new ClientTypeRepresentation.PropertyConfig(); clientType.getConfig().put("standardFlowEnabled", cfg); testRealm().clientTypes().updateClientTypes(clientTypes); - Assert.fail("Not expected to update client types"); + Assertions.fail("Not expected to update client types"); } catch (BadRequestException bre) { assertErrorContainsMessage(bre, ClientTypeException.Message.CLIENT_TYPE_FIELD_NOT_APPLICABLE); } @@ -217,7 +217,7 @@ public void testClientTypesAdminRestAPI_realmTypes() { cfg.setApplicable(false); cfg.setValue(true); testRealm().clientTypes().updateClientTypes(clientTypes); - Assert.fail("Not expected to update client types"); + Assertions.fail("Not expected to update client types"); } catch (BadRequestException bre) { assertErrorContainsMessage(bre, ClientTypeException.Message.INVALID_CLIENT_TYPE_CONFIGURATION); } @@ -237,7 +237,7 @@ public void testClientTypesAdminRestAPI_realmTypes() { clientType2.setConfig(new HashMap<>()); clientTypes.getRealmClientTypes().add(clientType2); testRealm().clientTypes().updateClientTypes(clientTypes); - Assert.fail("Not expected to update client types"); + Assertions.fail("Not expected to update client types"); } catch (BadRequestException bre) { assertErrorContainsMessage(bre, ClientTypeException.Message.DUPLICATE_CLIENT_TYPE); } @@ -246,7 +246,7 @@ public void testClientTypesAdminRestAPI_realmTypes() { try { clientType2.setName("service-account"); testRealm().clientTypes().updateClientTypes(clientTypes); - Assert.fail("Not expected to update client types"); + Assertions.fail("Not expected to update client types"); } catch (BadRequestException bre) { assertErrorContainsMessage(bre, ClientTypeException.Message.DUPLICATE_CLIENT_TYPE); } @@ -331,8 +331,8 @@ private void assertNames(List clientTypes, String... e private void assertPropertyConfig(String propertyName, ClientTypeRepresentation.PropertyConfig cfg, Boolean expectedApplicable, Object expectedValue) { - assertEquals("'applicable' for property " + propertyName + " not equal", expectedApplicable, cfg.getApplicable()); - assertEquals("'value' for property " + propertyName + " not equal", expectedValue, cfg.getValue()); + assertEquals(expectedApplicable, cfg.getApplicable(), "'applicable' for property " + propertyName + " not equal"); + assertEquals(expectedValue, cfg.getValue(), "'value' for property " + propertyName + " not equal"); } private ClientRepresentation createClientWithType(String clientId, String clientType) { @@ -351,7 +351,7 @@ private ClientRepresentation createClientWithType(String clientId, String client private void checkIfFeatureWorks(boolean shouldWork) { try { ClientTypesRepresentation clientTypes = testRealm().clientTypes().getClientTypes(); - Assert.assertTrue(clientTypes.getRealmClientTypes().isEmpty()); + Assertions.assertTrue(clientTypes.getRealmClientTypes().isEmpty()); if (!shouldWork) fail("Feature is available, but at this moment should be disabled"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/DefaultClientValidationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/DefaultClientValidationTest.java index 54816c6ee0a9..adb951540361 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/DefaultClientValidationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/DefaultClientValidationTest.java @@ -4,8 +4,8 @@ import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class DefaultClientValidationTest { @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/FAPI1Test.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/FAPI1Test.java index cb7ef8f74562..6e2e8d389456 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/FAPI1Test.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/FAPI1Test.java @@ -59,14 +59,15 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPoliciesBuilder; import static org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPolicyBuilder; import static org.keycloak.testsuite.util.ClientPoliciesUtil.createAnyClientConditionConfig; import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientUpdateContextConditionConfig; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * Test for the FAPI 1 specifications: @@ -94,27 +95,27 @@ public void testFAPIBaselineClientAuthenticator() throws Exception { // Try to register client with "client-jwt" - should pass String clientUUID = createClientByAdmin("client-jwt", (ClientRepresentation clientRep) -> clientRep.setClientAuthenticatorType(JWTClientAuthenticator.PROVIDER_ID)); ClientRepresentation client = getClientByAdmin(clientUUID); - Assert.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); // Try to register client with "client-secret-jwt" - should pass clientUUID = createClientByAdmin("client-secret-jwt", (ClientRepresentation clientRep) -> clientRep.setClientAuthenticatorType(JWTClientSecretAuthenticator.PROVIDER_ID)); client = getClientByAdmin(clientUUID); - Assert.assertEquals(JWTClientSecretAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertEquals(JWTClientSecretAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); // Try to register client with "client-x509" - should pass clientUUID = createClientByAdmin("client-x509", (ClientRepresentation clientRep) -> clientRep.setClientAuthenticatorType(X509ClientAuthenticator.PROVIDER_ID)); client = getClientByAdmin(clientUUID); - Assert.assertEquals(X509ClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertEquals(X509ClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); // Try to register client with default authenticator - should pass. Client authenticator should be "client-jwt" clientUUID = createClientByAdmin("client-jwt-2", (ClientRepresentation clientRep) -> { }); client = getClientByAdmin(clientUUID); - Assert.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); // Check the Consent is enabled, PKCS set to S256 - Assert.assertTrue(client.isConsentRequired()); - Assert.assertEquals(OAuth2Constants.PKCE_METHOD_S256, OIDCAdvancedConfigWrapper.fromClientRepresentation(client).getPkceCodeChallengeMethod()); + Assertions.assertTrue(client.isConsentRequired()); + Assertions.assertEquals(OAuth2Constants.PKCE_METHOD_S256, OIDCAdvancedConfigWrapper.fromClientRepresentation(client).getPkceCodeChallengeMethod()); } @@ -128,11 +129,11 @@ public void testFAPIBaselineSecureSettingsWhenUseAdminPolicy() throws Exception String clientUUID = createClientByAdmin("client-jwt-3", (ClientRepresentation clientRep) -> { }); ClientRepresentation client = getClientByAdmin(clientUUID); - Assert.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); // Check the Consent is enabled, PKCS set to S256 - Assert.assertTrue(client.isConsentRequired()); - Assert.assertEquals(OAuth2Constants.PKCE_METHOD_S256, OIDCAdvancedConfigWrapper.fromClientRepresentation(client).getPkceCodeChallengeMethod()); + Assertions.assertTrue(client.isConsentRequired()); + Assertions.assertEquals(OAuth2Constants.PKCE_METHOD_S256, OIDCAdvancedConfigWrapper.fromClientRepresentation(client).getPkceCodeChallengeMethod()); } @@ -154,8 +155,8 @@ public void testFAPIBaselineOIDCClientRegistration() throws Exception { clientRep.setJwksUri("https://foo"); }); ClientRepresentation client = getClientByAdmin(clientUUID); - Assert.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); - Assert.assertFalse(client.isFullScopeAllowed()); + Assertions.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertFalse(client.isFullScopeAllowed()); // Set new initialToken for register new clients setInitialAccessTokenForDynamicClientRegistration(); @@ -163,7 +164,7 @@ public void testFAPIBaselineOIDCClientRegistration() throws Exception { // Try to register client with "client-secret-jwt" - should pass clientUUID = createClientDynamically("client-secret-jwt", (OIDCClientRepresentation clientRep) -> clientRep.setTokenEndpointAuthMethod(OIDCLoginProtocol.CLIENT_SECRET_JWT)); client = getClientByAdmin(clientUUID); - Assert.assertEquals(JWTClientSecretAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertEquals(JWTClientSecretAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); // Set new initialToken for register new clients setInitialAccessTokenForDynamicClientRegistration(); @@ -171,11 +172,11 @@ public void testFAPIBaselineOIDCClientRegistration() throws Exception { // Try to register client with "client-x509" - should pass clientUUID = createClientDynamically("client-x509", (OIDCClientRepresentation clientRep) -> clientRep.setTokenEndpointAuthMethod(OIDCLoginProtocol.TLS_CLIENT_AUTH)); client = getClientByAdmin(clientUUID); - Assert.assertEquals(X509ClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertEquals(X509ClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); // Check the Consent is enabled, PKCS set to S256 - Assert.assertTrue(client.isConsentRequired()); - Assert.assertEquals(OAuth2Constants.PKCE_METHOD_S256, OIDCAdvancedConfigWrapper.fromClientRepresentation(client).getPkceCodeChallengeMethod()); + Assertions.assertTrue(client.isConsentRequired()); + Assertions.assertEquals(OAuth2Constants.PKCE_METHOD_S256, OIDCAdvancedConfigWrapper.fromClientRepresentation(client).getPkceCodeChallengeMethod()); } @@ -227,9 +228,9 @@ public void testFAPIBaselineConfidentialClientLogin() throws Exception { clientRep.setSecret("atleast-14chars-password"); }); ClientRepresentation client = getClientByAdmin(clientUUID); - Assert.assertFalse(client.isPublicClient()); - Assert.assertEquals(JWTClientSecretAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); - Assert.assertFalse(client.isFullScopeAllowed()); + Assertions.assertFalse(client.isPublicClient()); + Assertions.assertEquals(JWTClientSecretAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertFalse(client.isFullScopeAllowed()); checkPKCEWithS256RequiredDuringLogin("foo"); @@ -254,7 +255,7 @@ public void testFAPIBaselinePublicClientLogin() throws Exception { // Register client as public client String clientUUID = createClientByAdmin("foo", (ClientRepresentation clientRep) -> clientRep.setPublicClient(true)); ClientRepresentation client = getClientByAdmin(clientUUID); - Assert.assertTrue(client.isPublicClient()); + Assertions.assertTrue(client.isPublicClient()); checkPKCEWithS256RequiredDuringLogin("foo"); @@ -303,26 +304,26 @@ public void testFAPIAdvancedClientRegistration() throws Exception { // Try to register client with "client-jwt" - should pass String clientUUID = createClientByAdmin("client-jwt", (ClientRepresentation clientRep) -> clientRep.setClientAuthenticatorType(JWTClientAuthenticator.PROVIDER_ID)); ClientRepresentation client = getClientByAdmin(clientUUID); - Assert.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); // Try to register client with "client-x509" - should pass clientUUID = createClientByAdmin("client-x509", (ClientRepresentation clientRep) -> clientRep.setClientAuthenticatorType(X509ClientAuthenticator.PROVIDER_ID)); client = getClientByAdmin(clientUUID); - Assert.assertEquals(X509ClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertEquals(X509ClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); // Try to register client with default authenticator - should pass. Client authenticator should be "client-jwt" clientUUID = createClientByAdmin("client-jwt-2", (ClientRepresentation clientRep) -> { }); client = getClientByAdmin(clientUUID); - Assert.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); // Check the Consent is enabled, Holder-of-key is enabled, fullScopeAllowed disabled and default signature algorithm. - Assert.assertTrue(client.isConsentRequired()); + Assertions.assertTrue(client.isConsentRequired()); OIDCAdvancedConfigWrapper clientConfig = OIDCAdvancedConfigWrapper.fromClientRepresentation(client); - Assert.assertTrue(clientConfig.isUseMtlsHokToken()); - Assert.assertEquals(Algorithm.PS256, clientConfig.getIdTokenSignedResponseAlg()); - Assert.assertEquals(Algorithm.PS256, clientConfig.getRequestObjectSignatureAlg()); - Assert.assertFalse(client.isFullScopeAllowed()); + Assertions.assertTrue(clientConfig.isUseMtlsHokToken()); + Assertions.assertEquals(Algorithm.PS256, clientConfig.getIdTokenSignedResponseAlg()); + Assertions.assertEquals(Algorithm.PS256, clientConfig.getRequestObjectSignatureAlg()); + Assertions.assertFalse(client.isFullScopeAllowed()); } @@ -333,7 +334,7 @@ public void testFAPIAdvancedPublicClientLoginNotPossible() throws Exception { // Register client as public client String clientUUID = createClientByAdmin("foo", (ClientRepresentation clientRep) -> clientRep.setPublicClient(true)); ClientRepresentation client = getClientByAdmin(clientUUID); - Assert.assertTrue(client.isPublicClient()); + Assertions.assertTrue(client.isPublicClient()); // Setup PKCE and nonce pkceGenerator = PkceGenerator.s256(); @@ -374,18 +375,18 @@ public void testFAPIAdvancedSignatureAlgorithms() throws Exception { }); ClientRepresentation client = getClientByAdmin(clientUUID); OIDCAdvancedConfigWrapper clientConfig = OIDCAdvancedConfigWrapper.fromClientRepresentation(client); - Assert.assertEquals(Algorithm.ES256, clientConfig.getIdTokenSignedResponseAlg()); - Assert.assertEquals(Algorithm.PS256, clientConfig.getRequestObjectSignatureAlg()); + Assertions.assertEquals(Algorithm.ES256, clientConfig.getIdTokenSignedResponseAlg()); + Assertions.assertEquals(Algorithm.PS256, clientConfig.getRequestObjectSignatureAlg()); // Test default algorithms set everywhere clientUUID = createClientByAdmin("client-jwt-default-alg", (ClientRepresentation clientRep) -> clientRep.setClientAuthenticatorType(JWTClientAuthenticator.PROVIDER_ID)); client = getClientByAdmin(clientUUID); clientConfig = OIDCAdvancedConfigWrapper.fromClientRepresentation(client); - Assert.assertEquals(Algorithm.PS256, clientConfig.getIdTokenSignedResponseAlg()); - Assert.assertEquals(Algorithm.PS256, clientConfig.getRequestObjectSignatureAlg()); - Assert.assertEquals(Algorithm.PS256, clientConfig.getUserInfoSignedResponseAlg()); - Assert.assertEquals(Algorithm.PS256, clientConfig.getTokenEndpointAuthSigningAlg()); - Assert.assertEquals(Algorithm.PS256, client.getAttributes().get(OIDCConfigAttributes.ACCESS_TOKEN_SIGNED_RESPONSE_ALG)); + Assertions.assertEquals(Algorithm.PS256, clientConfig.getIdTokenSignedResponseAlg()); + Assertions.assertEquals(Algorithm.PS256, clientConfig.getRequestObjectSignatureAlg()); + Assertions.assertEquals(Algorithm.PS256, clientConfig.getUserInfoSignedResponseAlg()); + Assertions.assertEquals(Algorithm.PS256, clientConfig.getTokenEndpointAuthSigningAlg()); + Assertions.assertEquals(Algorithm.PS256, client.getAttributes().get(OIDCConfigAttributes.ACCESS_TOKEN_SIGNED_RESPONSE_ALG)); } @@ -457,20 +458,20 @@ public void testFAPIAdvancedLoginWithPrivateKeyJWT() throws Exception { AuthorizationEndpointResponse authorizationEndpointResponse = oauth.parseLoginResponse(); // Check token not present in the AuthorizationResponse. Check ID Token present, but used as detached signature - Assert.assertNull(authorizationEndpointResponse.getAccessToken()); + Assertions.assertNull(authorizationEndpointResponse.getAccessToken()); String idTokenParam = authorizationEndpointResponse.getIdToken(); assertIDTokenAsDetachedSignature(idTokenParam, code); // Check HoK required String signedJwt = createSignedRequestToken("foo", privateKey, publicKey, org.keycloak.crypto.Algorithm.PS256); AccessTokenResponse tokenResponse = doAccessTokenRequestWithClientSignedJWT(code, signedJwt, DefaultHttpClient::new); - Assert.assertEquals(OAuthErrorException.INVALID_GRANT,tokenResponse.getError()); - Assert.assertEquals("Client Certification missing for MTLS HoK Token Binding", tokenResponse.getErrorDescription()); + Assertions.assertEquals(OAuthErrorException.INVALID_GRANT,tokenResponse.getError()); + Assertions.assertEquals("Client Certification missing for MTLS HoK Token Binding", tokenResponse.getErrorDescription()); // Login with private-key-jwt client authentication and MTLS added to HttpClient. TokenRequest should be successful now oauth.loginForm().requestUri(requestUri).open(); code = oauth.parseLoginResponse().getCode(); - Assert.assertNotNull(code); + Assertions.assertNotNull(code); String signedJwt2 = createSignedRequestToken("foo", privateKey, publicKey, org.keycloak.crypto.Algorithm.PS256); @@ -478,7 +479,7 @@ public void testFAPIAdvancedLoginWithPrivateKeyJWT() throws Exception { assertSuccessfulTokenResponse(tokenResponse); AccessToken accessToken = oauth.verifyToken(tokenResponse.getAccessToken()); - Assert.assertNotNull(accessToken.getConfirmation().getCertThumbprint()); + Assertions.assertNotNull(accessToken.getConfirmation().getCertThumbprint()); // Logout and remove consent of the user for next logins logoutUserAndRevokeConsent("foo", TEST_USERNAME); @@ -525,7 +526,7 @@ public void testFAPIAdvancedLoginWithMTLS() throws Exception { AuthorizationEndpointResponse authorizationEndpointResponse = oauth.parseLoginResponse(); // Check token not present in the AuthorizationResponse. Check ID Token present, but used as detached signature - Assert.assertNull(authorizationEndpointResponse.getAccessToken()); + Assertions.assertNull(authorizationEndpointResponse.getAccessToken()); String idTokenParam = authorizationEndpointResponse.getIdToken(); assertIDTokenAsDetachedSignature(idTokenParam, code); @@ -534,7 +535,7 @@ public void testFAPIAdvancedLoginWithMTLS() throws Exception { assertSuccessfulTokenResponse(tokenResponse); AccessToken accessToken = oauth.verifyToken(tokenResponse.getAccessToken()); - Assert.assertNotNull(accessToken.getConfirmation().getCertThumbprint()); + Assertions.assertNotNull(accessToken.getConfirmation().getCertThumbprint()); // Logout and remove consent of the user for next logins logoutUserAndRevokeConsent("foo", TEST_USERNAME); @@ -626,18 +627,18 @@ private void successfulLoginAndLogout(String clientId, String nonce, String user } private void assertIDTokenAsDetachedSignature(String idTokenParam, String code) { - Assert.assertNotNull(idTokenParam); + Assertions.assertNotNull(idTokenParam); IDToken idToken = oauth.verifyIDToken(idTokenParam); - Assert.assertNotNull(idToken.getId()); - Assert.assertEquals("foo", idToken.getIssuedFor()); - Assert.assertNull(idToken.getPreferredUsername()); - Assert.assertNull(idToken.getEmail()); - Assert.assertNull(idToken.getGivenName()); - Assert.assertNull(idToken.getAccessTokenHash()); - Assert.assertEquals(idToken.getNonce(), "123456"); + Assertions.assertNotNull(idToken.getId()); + Assertions.assertEquals("foo", idToken.getIssuedFor()); + Assertions.assertNull(idToken.getPreferredUsername()); + Assertions.assertNull(idToken.getEmail()); + Assertions.assertNull(idToken.getGivenName()); + Assertions.assertNull(idToken.getAccessTokenHash()); + Assertions.assertEquals(idToken.getNonce(), "123456"); String state = oauth.parseLoginResponse().getState(); - Assert.assertEquals(idToken.getStateHash(), HashUtils.accessTokenHash(Algorithm.PS256, state)); - Assert.assertEquals(idToken.getCodeHash(), HashUtils.accessTokenHash(Algorithm.PS256, code)); + Assertions.assertEquals(idToken.getStateHash(), HashUtils.accessTokenHash(Algorithm.PS256, state)); + Assertions.assertEquals(idToken.getCodeHash(), HashUtils.accessTokenHash(Algorithm.PS256, code)); } private String getClientSecretSignedJWT(String secret, String algorithm) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/FAPI2DPoPTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/FAPI2DPoPTest.java index b1f3831911ec..c23b81cea8a4 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/FAPI2DPoPTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/FAPI2DPoPTest.java @@ -60,11 +60,11 @@ import static org.keycloak.testsuite.util.ClientPoliciesUtil.generateEcdsaKey; import static org.keycloak.testsuite.util.ClientPoliciesUtil.generateSignedDPoPProof; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public class FAPI2DPoPTest extends AbstractFAPI2Test { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/FAPI2Test.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/FAPI2Test.java index 10a3b4b232b4..e9c4966792c3 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/FAPI2Test.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/FAPI2Test.java @@ -36,7 +36,6 @@ import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.oidc.OIDCClientRepresentation; import org.keycloak.services.clientpolicy.ClientPolicyException; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.client.resources.TestApplicationResourceUrls; import org.keycloak.testsuite.rest.resource.TestingOIDCEndpointsApplicationResource; import org.keycloak.testsuite.util.MutualTLSUtils; @@ -45,11 +44,12 @@ import org.keycloak.testsuite.util.oauth.PkceGenerator; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Test for the FAPI 2 specifications (still implementer's draft): @@ -447,26 +447,26 @@ protected void testFAPI2ClientRegistration(String profile) throws Exception { // Try to register client with "client-jwt" - should pass String clientUUID = createClientByAdmin("client-jwt", (ClientRepresentation clientRep) -> clientRep.setClientAuthenticatorType(JWTClientAuthenticator.PROVIDER_ID)); ClientRepresentation client = getClientByAdmin(clientUUID); - Assert.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); // Try to register client with "client-x509" - should pass clientUUID = createClientByAdmin("client-x509", (ClientRepresentation clientRep) -> clientRep.setClientAuthenticatorType(X509ClientAuthenticator.PROVIDER_ID)); client = getClientByAdmin(clientUUID); - Assert.assertEquals(X509ClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertEquals(X509ClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); // Try to register client with default authenticator - should pass. Client authenticator should be "client-jwt" clientUUID = createClientByAdmin("client-jwt-2", (ClientRepresentation clientRep) -> { }); client = getClientByAdmin(clientUUID); - Assert.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); // Check the Consent is enabled, Holder-of-key is enabled, fullScopeAllowed disabled and default signature algorithm. - Assert.assertTrue(client.isConsentRequired()); + Assertions.assertTrue(client.isConsentRequired()); OIDCAdvancedConfigWrapper clientConfig = OIDCAdvancedConfigWrapper.fromClientRepresentation(client); - Assert.assertTrue(clientConfig.isUseMtlsHokToken()); - Assert.assertEquals(Algorithm.PS256, clientConfig.getIdTokenSignedResponseAlg()); - Assert.assertEquals(Algorithm.PS256, clientConfig.getRequestObjectSignatureAlg()); - Assert.assertFalse(client.isFullScopeAllowed()); + Assertions.assertTrue(clientConfig.isUseMtlsHokToken()); + Assertions.assertEquals(Algorithm.PS256, clientConfig.getIdTokenSignedResponseAlg()); + Assertions.assertEquals(Algorithm.PS256, clientConfig.getRequestObjectSignatureAlg()); + Assertions.assertFalse(client.isFullScopeAllowed()); } protected void testFAPI2OIDCClientRegistration(String profile) throws Exception { @@ -486,8 +486,8 @@ protected void testFAPI2OIDCClientRegistration(String profile) throws Exception clientRep.setJwksUri("https://foo"); }); ClientRepresentation client = getClientByAdmin(clientUUID); - Assert.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); - Assert.assertFalse(client.isFullScopeAllowed()); + Assertions.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertFalse(client.isFullScopeAllowed()); // Set new initialToken for register new clients setInitialAccessTokenForDynamicClientRegistration(); @@ -495,11 +495,11 @@ protected void testFAPI2OIDCClientRegistration(String profile) throws Exception // Try to register client with "client-x509" - should pass clientUUID = createClientDynamically("client-x509", (OIDCClientRepresentation clientRep) -> clientRep.setTokenEndpointAuthMethod(OIDCLoginProtocol.TLS_CLIENT_AUTH)); client = getClientByAdmin(clientUUID); - Assert.assertEquals(X509ClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertEquals(X509ClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); // Check the Consent is enabled, PKCS set to S256 - Assert.assertTrue(client.isConsentRequired()); - Assert.assertEquals(OAuth2Constants.PKCE_METHOD_S256, OIDCAdvancedConfigWrapper.fromClientRepresentation(client).getPkceCodeChallengeMethod()); + Assertions.assertTrue(client.isConsentRequired()); + Assertions.assertEquals(OAuth2Constants.PKCE_METHOD_S256, OIDCAdvancedConfigWrapper.fromClientRepresentation(client).getPkceCodeChallengeMethod()); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/FAPICIBATest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/FAPICIBATest.java index c128d084a6a0..9dd85bebe76d 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/FAPICIBATest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/FAPICIBATest.java @@ -54,7 +54,6 @@ import org.keycloak.services.Urls; import org.keycloak.services.clientpolicy.ClientPolicyException; import org.keycloak.services.clientpolicy.condition.AnyClientConditionFactory; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.client.resources.TestApplicationResourceUrls; import org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource; import org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest; @@ -71,6 +70,7 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.message.BasicNameValuePair; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.protocol.oidc.OIDCLoginProtocol.LOGIN_HINT_PARAM; import static org.keycloak.protocol.oidc.grants.ciba.CibaGrantType.AUTH_REQ_ID; @@ -83,8 +83,8 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * Test for the FAPI CIBA specifications (still implementer's draft): @@ -134,26 +134,26 @@ public void testFAPIAdvancedClientRegistration() throws Exception { // Try to register client with "client-jwt" - should pass String clientUUID = createClientByAdmin("client-jwt", (ClientRepresentation clientRep) -> clientRep.setClientAuthenticatorType(JWTClientAuthenticator.PROVIDER_ID)); ClientRepresentation client = getClientByAdmin(clientUUID); - Assert.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); // Try to register client with "client-x509" - should pass clientUUID = createClientByAdmin("client-x509", (ClientRepresentation clientRep) -> clientRep.setClientAuthenticatorType(X509ClientAuthenticator.PROVIDER_ID)); client = getClientByAdmin(clientUUID); - Assert.assertEquals(X509ClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertEquals(X509ClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); // Try to register client with default authenticator - should pass. Client authenticator should be "client-jwt" clientUUID = createClientByAdmin("client-jwt-2", (ClientRepresentation clientRep) -> { }); client = getClientByAdmin(clientUUID); - Assert.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); + Assertions.assertEquals(JWTClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType()); // Check the Consent is enabled, Holder-of-key is enabled, fullScopeAllowed disabled and default signature algorithm. - Assert.assertTrue(client.isConsentRequired()); + Assertions.assertTrue(client.isConsentRequired()); OIDCAdvancedConfigWrapper clientConfig = OIDCAdvancedConfigWrapper.fromClientRepresentation(client); - Assert.assertTrue(clientConfig.isUseMtlsHokToken()); - Assert.assertEquals(Algorithm.PS256, clientConfig.getIdTokenSignedResponseAlg()); - Assert.assertEquals(Algorithm.PS256, clientConfig.getRequestObjectSignatureAlg()); - Assert.assertFalse(client.isFullScopeAllowed()); + Assertions.assertTrue(clientConfig.isUseMtlsHokToken()); + Assertions.assertEquals(Algorithm.PS256, clientConfig.getIdTokenSignedResponseAlg()); + Assertions.assertEquals(Algorithm.PS256, clientConfig.getRequestObjectSignatureAlg()); + Assertions.assertFalse(client.isFullScopeAllowed()); } @Test @@ -183,20 +183,20 @@ public void testFAPICIBASignatureAlgorithms() throws Exception { }); ClientRepresentation client = getClientByAdmin(clientUUID); OIDCAdvancedConfigWrapper clientConfig = OIDCAdvancedConfigWrapper.fromClientRepresentation(client); - Assert.assertEquals(Algorithm.ES256, clientConfig.getIdTokenSignedResponseAlg()); - Assert.assertEquals(Algorithm.PS256, clientConfig.getRequestObjectSignatureAlg()); - Assert.assertEquals(Algorithm.ES256, client.getAttributes().get(CibaConfig.CIBA_BACKCHANNEL_AUTH_REQUEST_SIGNING_ALG)); + Assertions.assertEquals(Algorithm.ES256, clientConfig.getIdTokenSignedResponseAlg()); + Assertions.assertEquals(Algorithm.PS256, clientConfig.getRequestObjectSignatureAlg()); + Assertions.assertEquals(Algorithm.ES256, client.getAttributes().get(CibaConfig.CIBA_BACKCHANNEL_AUTH_REQUEST_SIGNING_ALG)); // Test default algorithms set everywhere clientUUID = createClientByAdmin("client-jwt-default-alg", (ClientRepresentation clientRep) -> clientRep.setClientAuthenticatorType(JWTClientAuthenticator.PROVIDER_ID)); client = getClientByAdmin(clientUUID); clientConfig = OIDCAdvancedConfigWrapper.fromClientRepresentation(client); - Assert.assertEquals(Algorithm.PS256, clientConfig.getIdTokenSignedResponseAlg()); - Assert.assertEquals(Algorithm.PS256, clientConfig.getRequestObjectSignatureAlg()); - Assert.assertEquals(Algorithm.PS256, clientConfig.getUserInfoSignedResponseAlg()); - Assert.assertEquals(Algorithm.PS256, clientConfig.getTokenEndpointAuthSigningAlg()); - Assert.assertEquals(Algorithm.PS256, client.getAttributes().get(OIDCConfigAttributes.ACCESS_TOKEN_SIGNED_RESPONSE_ALG)); - Assert.assertEquals(Algorithm.PS256, client.getAttributes().get(CibaConfig.CIBA_BACKCHANNEL_AUTH_REQUEST_SIGNING_ALG)); + Assertions.assertEquals(Algorithm.PS256, clientConfig.getIdTokenSignedResponseAlg()); + Assertions.assertEquals(Algorithm.PS256, clientConfig.getRequestObjectSignatureAlg()); + Assertions.assertEquals(Algorithm.PS256, clientConfig.getUserInfoSignedResponseAlg()); + Assertions.assertEquals(Algorithm.PS256, clientConfig.getTokenEndpointAuthSigningAlg()); + Assertions.assertEquals(Algorithm.PS256, client.getAttributes().get(OIDCConfigAttributes.ACCESS_TOKEN_SIGNED_RESPONSE_ALG)); + Assertions.assertEquals(Algorithm.PS256, client.getAttributes().get(CibaConfig.CIBA_BACKCHANNEL_AUTH_REQUEST_SIGNING_ALG)); } @@ -566,7 +566,7 @@ private void verifyBackchannelAuthenticationTokenRequest(AccessTokenResponse tok AccessToken accessToken = oauth.verifyToken(tokenRes.getAccessToken()); assertThat(accessToken.getIssuedFor(), is(equalTo(clientId))); - Assert.assertNotNull(accessToken.getConfirmation().getCertThumbprint()); + Assertions.assertNotNull(accessToken.getConfirmation().getCertThumbprint()); events.expectAuthReqIdToToken(null, null).clearDetails().user(accessToken.getSubject()).client(clientId).assertEvent(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/InitialAccessTokenTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/InitialAccessTokenTest.java index a26131ad76e6..c93faa181894 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/InitialAccessTokenTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/InitialAccessTokenTest.java @@ -31,11 +31,11 @@ import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.testsuite.util.TokenSignatureUtil; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Stian Thorgersen @@ -62,11 +62,11 @@ public void create() throws ClientRegistrationException, InterruptedException { setTimeOffset(10); ClientRepresentation created = reg.create(rep); - Assert.assertNotNull(created); + Assertions.assertNotNull(created); try { reg.create(rep); - Assert.fail("Expected exception"); + Assertions.fail("Expected exception"); } catch (ClientRegistrationException e) { assertEquals(401, ((HttpErrorException) e.getCause()).getStatusLine().getStatusCode()); } @@ -87,7 +87,7 @@ public void createWithES256() throws JWSInputException, ClientRegistrationExcept ClientRepresentation rep = new ClientRepresentation(); ClientRepresentation created = reg.create(rep); - Assert.assertNotNull(created); + Assertions.assertNotNull(created); } finally { TokenSignatureUtil.changeRealmTokenSignatureProvider(adminClient, Algorithm.RS256); } @@ -102,14 +102,14 @@ public void createMultiple() throws ClientRegistrationException { ClientRepresentation rep = new ClientRepresentation(); ClientRepresentation created = reg.create(rep); - Assert.assertNotNull(created); + Assertions.assertNotNull(created); created = reg.create(rep); - Assert.assertNotNull(created); + Assertions.assertNotNull(created); try { reg.create(rep); - Assert.fail("Expected exception"); + Assertions.fail("Expected exception"); } catch (ClientRegistrationException e) { assertEquals(401, ((HttpErrorException) e.getCause()).getStatusLine().getStatusCode()); } @@ -127,7 +127,7 @@ public void createExpired() throws ClientRegistrationException, InterruptedExcep try { reg.create(rep); - Assert.fail("Expected exception"); + Assertions.fail("Expected exception"); } catch (ClientRegistrationException e) { assertEquals(401, ((HttpErrorException) e.getCause()).getStatusLine().getStatusCode()); } @@ -145,7 +145,7 @@ public void createDeleted() throws ClientRegistrationException, InterruptedExcep try { reg.create(rep); - Assert.fail("Expected exception"); + Assertions.fail("Expected exception"); } catch (ClientRegistrationException e) { assertEquals(401, ((HttpErrorException) e.getCause()).getStatusLine().getStatusCode()); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/MutualTLSClientTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/MutualTLSClientTest.java index a9cd0218ce55..f7ab4ea9bf62 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/MutualTLSClientTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/MutualTLSClientTest.java @@ -27,10 +27,10 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.message.BasicNameValuePair; -import org.junit.Assert; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * Mutual TLS Client tests. @@ -261,13 +261,13 @@ private void login(String clientId) { } private void assertTokenObtained(AccessTokenResponse token) { - Assert.assertEquals(200, token.getStatusCode()); - Assert.assertNotNull(token.getAccessToken()); + Assertions.assertEquals(200, token.getStatusCode()); + Assertions.assertNotNull(token.getAccessToken()); } private void assertTokenNotObtained(AccessTokenResponse token) { - Assert.assertEquals(401, token.getStatusCode()); - Assert.assertNull(token.getAccessToken()); + Assertions.assertEquals(401, token.getStatusCode()); + Assertions.assertNull(token.getAccessToken()); } /* diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OAuth2_1ConfidentialClientTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OAuth2_1ConfidentialClientTest.java index ff7b9ad27794..fffc8c534345 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OAuth2_1ConfidentialClientTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OAuth2_1ConfidentialClientTest.java @@ -37,7 +37,6 @@ import org.keycloak.representations.oidc.OIDCClientRepresentation; import org.keycloak.services.clientpolicy.ClientPolicyException; import org.keycloak.services.clientpolicy.condition.AnyClientConditionFactory; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.client.resources.TestApplicationResourceUrls; import org.keycloak.testsuite.util.ClientPoliciesUtil; @@ -49,13 +48,14 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.util.ClientPoliciesUtil.createAnyClientConditionConfig; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class OAuth2_1ConfidentialClientTest extends AbstractFAPITest { @@ -215,7 +215,7 @@ public void testOAuth2_1OAuthMtlsSenderConstrainedToken() throws Exception { AccessTokenResponse tokenResponse = oauth.accessTokenRequest(res.getCode()).codeVerifier(pkceGenerator.getCodeVerifier()).send(); AccessToken accessToken = oauth.verifyToken(tokenResponse.getAccessToken()); - Assert.assertNotNull(accessToken.getConfirmation().getCertThumbprint()); + Assertions.assertNotNull(accessToken.getConfirmation().getCertThumbprint()); oauth.logoutForm().idTokenHint(tokenResponse.getIdToken()).open(); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OAuth2_1PublicClientTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OAuth2_1PublicClientTest.java index 19e35639a22c..40963eaf2bbf 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OAuth2_1PublicClientTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OAuth2_1PublicClientTest.java @@ -57,8 +57,8 @@ import static org.keycloak.testsuite.util.ClientPoliciesUtil.generateEcdsaKey; import static org.keycloak.testsuite.util.ClientPoliciesUtil.generateSignedDPoPProof; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class OAuth2_1PublicClientTest extends AbstractFAPITest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationDefaultSignatureTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationDefaultSignatureTest.java index 7d4ff78bd9e7..30bfbf9924d3 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationDefaultSignatureTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationDefaultSignatureTest.java @@ -27,11 +27,11 @@ import org.keycloak.representations.idm.ClientInitialAccessPresentation; import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.oidc.OIDCClientRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.TokenSignatureUtil; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; public class OIDCClientRegistrationDefaultSignatureTest extends AbstractClientRegistrationTest { @Before @@ -63,44 +63,44 @@ public void testIdTokenSignedResponse() throws Exception { OIDCClientRepresentation clientRep = createRep(); response = reg.oidc().create(clientRep); - Assert.assertEquals(Algorithm.ES512, response.getIdTokenSignedResponseAlg()); + Assertions.assertEquals(Algorithm.ES512, response.getIdTokenSignedResponseAlg()); // Test Keycloak representation ClientRepresentation kcClient = getClient(response.getClientId()); OIDCAdvancedConfigWrapper config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); // Client representation of id.token.signed.response.alg is null as from realm - Assert.assertNull(config.getIdTokenSignedResponseAlg()); + Assertions.assertNull(config.getIdTokenSignedResponseAlg()); // update reg.auth(Auth.token(response)); response.setIdTokenSignedResponseAlg(Algorithm.ES256); updated = reg.oidc().update(response); - Assert.assertEquals(Algorithm.ES256, updated.getIdTokenSignedResponseAlg()); + Assertions.assertEquals(Algorithm.ES256, updated.getIdTokenSignedResponseAlg()); // Test Keycloak representation kcClient = getClient(updated.getClientId()); config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertEquals(Algorithm.ES256, config.getIdTokenSignedResponseAlg()); + Assertions.assertEquals(Algorithm.ES256, config.getIdTokenSignedResponseAlg()); // update after changing default realm token signature TokenSignatureUtil.changeRealmTokenSignatureProvider(adminClient, Algorithm.ES384); reg.auth(Auth.token(updated)); updated.setIdTokenSignedResponseAlg(null); response = reg.oidc().update(updated); - Assert.assertEquals(Algorithm.ES384, response.getIdTokenSignedResponseAlg()); + Assertions.assertEquals(Algorithm.ES384, response.getIdTokenSignedResponseAlg()); } finally { // revert TokenSignatureUtil.changeRealmTokenSignatureProvider(adminClient, Algorithm.RS256); reg.auth(Auth.token(response)); response.setIdTokenSignedResponseAlg(null); updated = reg.oidc().update(response); - Assert.assertNull(updated.getIdTokenSignedResponseAlg()); + Assertions.assertNull(updated.getIdTokenSignedResponseAlg()); // Test Keycloak representation ClientRepresentation kcClient = getClient(updated.getClientId()); OIDCAdvancedConfigWrapper config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); // Client representation of id.token.signed.response.alg is null as from realm - Assert.assertNull(config.getIdTokenSignedResponseAlg()); + Assertions.assertNull(config.getIdTokenSignedResponseAlg()); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationResponseTypesAndGrantsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationResponseTypesAndGrantsTest.java index 3edd2fdf8734..fdd75809ce28 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationResponseTypesAndGrantsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationResponseTypesAndGrantsTest.java @@ -34,13 +34,13 @@ import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.idm.OAuth2ErrorRepresentation; import org.keycloak.representations.oidc.OIDCClientRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.util.JsonSerialization; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.OAuth2Constants.AUTHORIZATION_CODE; import static org.keycloak.OAuth2Constants.CLIENT_CREDENTIALS; @@ -193,12 +193,12 @@ public void testGrantTypeTokenExchange() throws Exception { OIDCClientRepresentation clientRep = createRep(null, List.of(AUTHORIZATION_CODE, REFRESH_TOKEN, TOKEN_EXCHANGE_GRANT_TYPE)); clientRep.setTokenEndpointAuthMethod("none"); - ClientRegistrationException clientRegistrationException = Assert.assertThrows(ClientRegistrationException.class, () -> reg.oidc().create(clientRep)); + ClientRegistrationException clientRegistrationException = Assertions.assertThrows(ClientRegistrationException.class, () -> reg.oidc().create(clientRep)); MatcherAssert.assertThat(clientRegistrationException.getCause(), Matchers.instanceOf(HttpErrorException.class)); HttpErrorException httpErrorException = (HttpErrorException) clientRegistrationException.getCause(); - Assert.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), httpErrorException.getStatusLine().getStatusCode()); + Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), httpErrorException.getStatusLine().getStatusCode()); OAuth2ErrorRepresentation error = JsonSerialization.readValue(httpErrorException.getErrorResponse(), OAuth2ErrorRepresentation.class); - Assert.assertEquals(OAuthErrorException.INVALID_CLIENT_METADATA, error.getError()); + Assertions.assertEquals(OAuthErrorException.INVALID_CLIENT_METADATA, error.getError()); clientRep.setTokenEndpointAuthMethod(null); OIDCClientRepresentation response = reg.oidc().create(clientRep); @@ -262,14 +262,14 @@ private void assertKeycloakClient(OIDCClientRepresentation response, boolean expectedTokenExchange) { ClientRepresentation kcClient = getClient(response.getClientId()); OIDCAdvancedConfigWrapper config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertEquals("Expected standard flow: " + expectedStandardFlow + " did not match.", expectedStandardFlow, kcClient.isStandardFlowEnabled()); - Assert.assertEquals("Expected implicit flow: " + expectedImplicitFlow + " did not match.", expectedImplicitFlow, kcClient.isImplicitFlowEnabled()); - Assert.assertEquals("Expected direct grant flow: " + expectedDirectGrantFlow + " did not match.", expectedDirectGrantFlow, kcClient.isDirectAccessGrantsEnabled()); - Assert.assertEquals("Expected service accounts flow: " + expectedServiceAccountsFlow + " did not match.", expectedServiceAccountsFlow, kcClient.isServiceAccountsEnabled()); - Assert.assertEquals("Expected refresh: " + expectedRefreshToken + " did not match.", expectedRefreshToken, config.isUseRefreshToken()); - Assert.assertFalse("Don't expect refresh token for client credentials grant enabled", config.isUseRefreshTokenForClientCredentialsGrant()); + Assertions.assertEquals(expectedStandardFlow, kcClient.isStandardFlowEnabled(), "Expected standard flow: " + expectedStandardFlow + " did not match."); + Assertions.assertEquals(expectedImplicitFlow, kcClient.isImplicitFlowEnabled(), "Expected implicit flow: " + expectedImplicitFlow + " did not match."); + Assertions.assertEquals(expectedDirectGrantFlow, kcClient.isDirectAccessGrantsEnabled(), "Expected direct grant flow: " + expectedDirectGrantFlow + " did not match."); + Assertions.assertEquals(expectedServiceAccountsFlow, kcClient.isServiceAccountsEnabled(), "Expected service accounts flow: " + expectedServiceAccountsFlow + " did not match."); + Assertions.assertEquals(expectedRefreshToken, config.isUseRefreshToken(), "Expected refresh: " + expectedRefreshToken + " did not match."); + Assertions.assertFalse(config.isUseRefreshTokenForClientCredentialsGrant(), "Don't expect refresh token for client credentials grant enabled"); boolean deviceEnabled = kcClient.getAttributes() != null && Boolean.parseBoolean(kcClient.getAttributes().get(OAUTH2_DEVICE_AUTHORIZATION_GRANT_ENABLED)); - Assert.assertEquals("Expected device: " + expectedDeviceGrant + " did not match.", expectedDeviceGrant, deviceEnabled); - Assert.assertEquals("Expected Token Exchange: " + expectedTokenExchange + " did not match.", expectedTokenExchange, config.isStandardTokenExchangeEnabled()); + Assertions.assertEquals(expectedDeviceGrant, deviceEnabled, "Expected device: " + expectedDeviceGrant + " did not match."); + Assertions.assertEquals(expectedTokenExchange, config.isStandardTokenExchangeEnabled(), "Expected Token Exchange: " + expectedTokenExchange + " did not match."); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationTest.java index 9c66ed2cd020..b904b3e2074e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationTest.java @@ -59,14 +59,15 @@ import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.auth.page.AuthRealm.TEST; import static org.keycloak.testsuite.util.oauth.OAuthClient.AUTH_SERVER_ROOT; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Stian Thorgersen @@ -119,12 +120,12 @@ private void assertCreateFail(OIDCClientRepresentation client, int expectedStatu private void assertCreateFail(OIDCClientRepresentation client, int expectedStatusCode, String expectedErrorContains) { try { reg.oidc().create(client); - Assert.fail("Not expected to successfuly register client"); + Assertions.fail("Not expected to successfuly register client"); } catch (ClientRegistrationException expected) { HttpErrorException httpEx = (HttpErrorException) expected.getCause(); - Assert.assertEquals(expectedStatusCode, httpEx.getStatusLine().getStatusCode()); + Assertions.assertEquals(expectedStatusCode, httpEx.getStatusLine().getStatusCode()); if (expectedErrorContains != null) { - assertTrue("Error response doesn't contain expected text", httpEx.getErrorResponse().contains(expectedErrorContains)); + assertTrue(httpEx.getErrorResponse().contains(expectedErrorContains), "Error response doesn't contain expected text"); } } } @@ -132,12 +133,12 @@ private void assertCreateFail(OIDCClientRepresentation client, int expectedStatu private void assertGetFail(String clientId, int expectedStatusCode, String expectedErrorContains) { try { reg.oidc().get(clientId); - Assert.fail("Not expected to successfully get client"); + Assertions.fail("Not expected to successfully get client"); } catch (ClientRegistrationException expected) { HttpErrorException httpEx = (HttpErrorException) expected.getCause(); - Assert.assertEquals(expectedStatusCode, httpEx.getStatusLine().getStatusCode()); + Assertions.assertEquals(expectedStatusCode, httpEx.getStatusLine().getStatusCode()); if (expectedErrorContains != null) { - assertTrue("Error response doesn't contain expected text", httpEx.getErrorResponse().contains(expectedErrorContains)); + assertTrue(httpEx.getErrorResponse().contains(expectedErrorContains), "Error response doesn't contain expected text"); } } } @@ -168,7 +169,7 @@ public void createClient() throws ClientRegistrationException { assertEquals(Arrays.asList("code", "none"), response.getResponseTypes()); assertEquals(Arrays.asList(OAuth2Constants.AUTHORIZATION_CODE, OAuth2Constants.REFRESH_TOKEN), response.getGrantTypes()); assertEquals(OIDCLoginProtocol.CLIENT_SECRET_BASIC, response.getTokenEndpointAuthMethod()); - Assert.assertNull(response.getUserinfoSignedResponseAlg()); + Assertions.assertNull(response.getUserinfoSignedResponseAlg()); assertEquals("http://frontchannel", response.getFrontChannelLogoutUri()); assertTrue(response.getFrontchannelLogoutSessionRequired()); } @@ -233,7 +234,7 @@ public void createClientResponseTypeNone() throws ClientRegistrationException { assertEquals(List.of("code", "none"), response.getResponseTypes()); assertEquals(Arrays.asList(OAuth2Constants.AUTHORIZATION_CODE, OAuth2Constants.REFRESH_TOKEN), response.getGrantTypes()); assertEquals(OIDCLoginProtocol.CLIENT_SECRET_BASIC, response.getTokenEndpointAuthMethod()); - Assert.assertNull(response.getUserinfoSignedResponseAlg()); + Assertions.assertNull(response.getUserinfoSignedResponseAlg()); assertEquals("http://frontchannel", response.getFrontChannelLogoutUri()); assertTrue(response.getFrontchannelLogoutSessionRequired()); } @@ -268,28 +269,28 @@ public void testSignaturesRequired() throws Exception { clientRep.setRequestObjectSigningAlg(Algorithm.ES256); response = reg.oidc().create(clientRep); - Assert.assertEquals(Algorithm.ES256, response.getUserinfoSignedResponseAlg()); - Assert.assertEquals(Algorithm.ES256, response.getRequestObjectSigningAlg()); - Assert.assertNotNull(response.getClientSecret()); + Assertions.assertEquals(Algorithm.ES256, response.getUserinfoSignedResponseAlg()); + Assertions.assertEquals(Algorithm.ES256, response.getRequestObjectSigningAlg()); + Assertions.assertNotNull(response.getClientSecret()); // Test Keycloak representation ClientRepresentation kcClient = getClient(response.getClientId()); OIDCAdvancedConfigWrapper config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertEquals(config.getUserInfoSignedResponseAlg(), Algorithm.ES256); - Assert.assertEquals(config.getRequestObjectSignatureAlg(), Algorithm.ES256); + Assertions.assertEquals(config.getUserInfoSignedResponseAlg(), Algorithm.ES256); + Assertions.assertEquals(config.getRequestObjectSignatureAlg(), Algorithm.ES256); // update (ES256 to PS256) clientRep.setUserinfoSignedResponseAlg(Algorithm.PS256); clientRep.setRequestObjectSigningAlg(Algorithm.PS256); response = reg.oidc().create(clientRep); - Assert.assertEquals(Algorithm.PS256, response.getUserinfoSignedResponseAlg()); - Assert.assertEquals(Algorithm.PS256, response.getRequestObjectSigningAlg()); + Assertions.assertEquals(Algorithm.PS256, response.getUserinfoSignedResponseAlg()); + Assertions.assertEquals(Algorithm.PS256, response.getRequestObjectSigningAlg()); // keycloak representation kcClient = getClient(response.getClientId()); config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertEquals(config.getUserInfoSignedResponseAlg(), Algorithm.PS256); - Assert.assertEquals(config.getRequestObjectSignatureAlg(), Algorithm.PS256); + Assertions.assertEquals(config.getUserInfoSignedResponseAlg(), Algorithm.PS256); + Assertions.assertEquals(config.getRequestObjectSignatureAlg(), Algorithm.PS256); } finally { // back to RS256 for other tests clientRep.setUserinfoSignedResponseAlg(Algorithm.RS256); @@ -307,9 +308,9 @@ public void createClientImplicitFlow() throws ClientRegistrationException { String clientId = response.getClientId(); ClientRepresentation kcClientRep = getKeycloakClient(clientId); - Assert.assertFalse(kcClientRep.isPublicClient()); - Assert.assertFalse(kcClientRep.isBearerOnly()); - Assert.assertNotNull(kcClientRep.getSecret()); + Assertions.assertFalse(kcClientRep.isPublicClient()); + Assertions.assertFalse(kcClientRep.isBearerOnly()); + Assertions.assertNotNull(kcClientRep.getSecret()); } @Test @@ -318,12 +319,12 @@ public void createPublicClient() throws ClientRegistrationException { clientRep.setTokenEndpointAuthMethod("none"); OIDCClientRepresentation response = reg.oidc().create(clientRep); - Assert.assertEquals("none", response.getTokenEndpointAuthMethod()); + Assertions.assertEquals("none", response.getTokenEndpointAuthMethod()); String clientId = response.getClientId(); ClientRepresentation kcClientRep = getKeycloakClient(clientId); - Assert.assertTrue(kcClientRep.isPublicClient()); - Assert.assertNull(kcClientRep.getSecret()); + Assertions.assertTrue(kcClientRep.isPublicClient()); + Assertions.assertNull(kcClientRep.getSecret()); } @Test @@ -333,21 +334,21 @@ public void testClientSecretsWithAuthMethod() throws ClientRegistrationException clientRep.setTokenEndpointAuthMethod(OIDCLoginProtocol.CLIENT_SECRET_JWT); OIDCClientRepresentation response = reg.oidc().create(clientRep); - Assert.assertEquals("client_secret_jwt", response.getTokenEndpointAuthMethod()); - Assert.assertNotNull(response.getClientSecret()); - Assert.assertNotNull(response.getClientSecretExpiresAt()); + Assertions.assertEquals("client_secret_jwt", response.getTokenEndpointAuthMethod()); + Assertions.assertNotNull(response.getClientSecret()); + Assertions.assertNotNull(response.getClientSecretExpiresAt()); ClientRepresentation kcClientRep = getKeycloakClient(response.getClientId()); - Assert.assertFalse(kcClientRep.isPublicClient()); - Assert.assertNotNull(kcClientRep.getSecret()); + Assertions.assertFalse(kcClientRep.isPublicClient()); + Assertions.assertNotNull(kcClientRep.getSecret()); // Updating reg.auth(Auth.token(response)); response.setTokenEndpointAuthMethod(OIDCLoginProtocol.TLS_CLIENT_AUTH); OIDCClientRepresentation updated = reg.oidc().update(response); - Assert.assertEquals("tls_client_auth", updated.getTokenEndpointAuthMethod()); - Assert.assertNull(updated.getClientSecret()); - Assert.assertNull(updated.getClientSecretExpiresAt()); + Assertions.assertEquals("tls_client_auth", updated.getTokenEndpointAuthMethod()); + Assertions.assertNull(updated.getClientSecret()); + Assertions.assertNull(updated.getClientSecretExpiresAt()); } @Test @@ -357,37 +358,37 @@ public void testClientSecretClientAuthMethod() throws ClientRegistrationExceptio clientRep.setTokenEndpointAuthMethod(OIDCLoginProtocol.CLIENT_SECRET_POST); OIDCClientRepresentation response = reg.oidc().create(clientRep); - Assert.assertEquals(OIDCLoginProtocol.CLIENT_SECRET_POST, response.getTokenEndpointAuthMethod()); - Assert.assertNotNull(response.getClientSecret()); + Assertions.assertEquals(OIDCLoginProtocol.CLIENT_SECRET_POST, response.getTokenEndpointAuthMethod()); + Assertions.assertNotNull(response.getClientSecret()); ClientRepresentation kcClientRep = getKeycloakClient(response.getClientId()); - Assert.assertFalse(kcClientRep.isPublicClient()); - Assert.assertNotNull(kcClientRep.getSecret()); - Assert.assertEquals(OIDCLoginProtocol.CLIENT_SECRET_POST, OIDCClientSecretConfigWrapper.fromClientRepresentation(kcClientRep).getClientSecretAuthenticationAllowedMethod()); + Assertions.assertFalse(kcClientRep.isPublicClient()); + Assertions.assertNotNull(kcClientRep.getSecret()); + Assertions.assertEquals(OIDCLoginProtocol.CLIENT_SECRET_POST, OIDCClientSecretConfigWrapper.fromClientRepresentation(kcClientRep).getClientSecretAuthenticationAllowedMethod()); // Verify that retrieving the client returns client_secret_post reg.auth(Auth.token(response)); OIDCClientRepresentation retrieved = reg.oidc().get(response.getClientId()); - Assert.assertEquals(OIDCLoginProtocol.CLIENT_SECRET_POST, retrieved.getTokenEndpointAuthMethod()); + Assertions.assertEquals(OIDCLoginProtocol.CLIENT_SECRET_POST, retrieved.getTokenEndpointAuthMethod()); // Update to use client_secret_basic and test it reg.auth(Auth.token(response)); response.setTokenEndpointAuthMethod(OIDCLoginProtocol.CLIENT_SECRET_BASIC); OIDCClientRepresentation updated = reg.oidc().update(response); - Assert.assertEquals(OIDCLoginProtocol.CLIENT_SECRET_BASIC, updated.getTokenEndpointAuthMethod()); + Assertions.assertEquals(OIDCLoginProtocol.CLIENT_SECRET_BASIC, updated.getTokenEndpointAuthMethod()); kcClientRep = getKeycloakClient(response.getClientId()); - Assert.assertFalse(kcClientRep.isPublicClient()); - Assert.assertNotNull(kcClientRep.getSecret()); - Assert.assertEquals(OIDCLoginProtocol.CLIENT_SECRET_BASIC, OIDCClientSecretConfigWrapper.fromClientRepresentation(kcClientRep).getClientSecretAuthenticationAllowedMethod()); + Assertions.assertFalse(kcClientRep.isPublicClient()); + Assertions.assertNotNull(kcClientRep.getSecret()); + Assertions.assertEquals(OIDCLoginProtocol.CLIENT_SECRET_BASIC, OIDCClientSecretConfigWrapper.fromClientRepresentation(kcClientRep).getClientSecretAuthenticationAllowedMethod()); // Update to use different method (tls_client_auth) reg.auth(Auth.token(updated)); updated.setTokenEndpointAuthMethod(OIDCLoginProtocol.TLS_CLIENT_AUTH); updated = reg.oidc().update(updated); - Assert.assertEquals(OIDCLoginProtocol.TLS_CLIENT_AUTH, updated.getTokenEndpointAuthMethod()); - Assert.assertNull(updated.getClientSecret()); - Assert.assertNull(updated.getClientSecretExpiresAt()); + Assertions.assertEquals(OIDCLoginProtocol.TLS_CLIENT_AUTH, updated.getTokenEndpointAuthMethod()); + Assertions.assertNull(updated.getClientSecret()); + Assertions.assertNull(updated.getClientSecretExpiresAt()); } @Test @@ -396,11 +397,11 @@ public void createClientFrontchannelLogoutSettings() throws ClientRegistrationEx OIDCClientRepresentation clientRep = createRep(); clientRep.setFrontchannelLogoutSessionRequired(null); OIDCClientRepresentation response = reg.oidc().create(clientRep); - Assert.assertEquals(false, response.getFrontchannelLogoutSessionRequired()); + Assertions.assertEquals(false, response.getFrontchannelLogoutSessionRequired()); String clientId = response.getClientId(); ClientRepresentation kcClientRep = getKeycloakClient(clientId); - Assert.assertFalse(OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClientRep).isFrontChannelLogoutSessionRequired()); + Assertions.assertFalse(OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClientRep).isFrontChannelLogoutSessionRequired()); } // KEYCLOAK-6771 Certificate Bound Token @@ -411,8 +412,8 @@ public void testMtlsHoKTokenEnabled() throws Exception { OIDCClientRepresentation clientRep = createRep(); OIDCClientRepresentation response = reg.oidc().create(clientRep); - Assert.assertEquals(Boolean.FALSE, response.getTlsClientCertificateBoundAccessTokens()); - Assert.assertNotNull(response.getClientSecret()); + Assertions.assertEquals(Boolean.FALSE, response.getTlsClientCertificateBoundAccessTokens()); + Assertions.assertNotNull(response.getClientSecret()); // Test Keycloak representation ClientRepresentation kcClient = getClient(response.getClientId()); @@ -449,8 +450,8 @@ public void testDPoPHoKTokenEnabled() throws Exception { OIDCClientRepresentation clientRep = createRep(); OIDCClientRepresentation response = reg.oidc().create(clientRep); - Assert.assertEquals(Boolean.FALSE, response.getDpopBoundAccessTokens()); - Assert.assertNotNull(response.getClientSecret()); + Assertions.assertEquals(Boolean.FALSE, response.getDpopBoundAccessTokens()); + Assertions.assertNotNull(response.getClientSecret()); // Test Keycloak representation ClientRepresentation kcClient = getClient(response.getClientId()); @@ -494,22 +495,22 @@ public void testUserInfoEncryptedResponse() throws Exception { // Test Keycloak representation ClientRepresentation kcClient = getClient(response.getClientId()); OIDCAdvancedConfigWrapper config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertNull(config.getUserInfoEncryptedResponseAlg()); - Assert.assertNull(config.getUserInfoEncryptedResponseEnc()); + Assertions.assertNull(config.getUserInfoEncryptedResponseAlg()); + Assertions.assertNull(config.getUserInfoEncryptedResponseEnc()); // update (alg RSA1_5, enc A128CBC-HS256) reg.auth(Auth.token(response)); response.setUserinfoEncryptedResponseAlg(JWEConstants.RSA1_5); response.setUserinfoEncryptedResponseEnc(JWEConstants.A128CBC_HS256); updated = reg.oidc().update(response); - Assert.assertEquals(JWEConstants.RSA1_5, updated.getUserinfoEncryptedResponseAlg()); - Assert.assertEquals(JWEConstants.A128CBC_HS256, updated.getUserinfoEncryptedResponseEnc()); + Assertions.assertEquals(JWEConstants.RSA1_5, updated.getUserinfoEncryptedResponseAlg()); + Assertions.assertEquals(JWEConstants.A128CBC_HS256, updated.getUserinfoEncryptedResponseEnc()); // Test Keycloak representation kcClient = getClient(updated.getClientId()); config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertEquals(JWEConstants.RSA1_5, config.getUserInfoEncryptedResponseAlg()); - Assert.assertEquals(JWEConstants.A128CBC_HS256, config.getUserInfoEncryptedResponseEnc()); + Assertions.assertEquals(JWEConstants.RSA1_5, config.getUserInfoEncryptedResponseAlg()); + Assertions.assertEquals(JWEConstants.A128CBC_HS256, config.getUserInfoEncryptedResponseEnc()); } finally { // revert @@ -529,28 +530,28 @@ public void testIdTokenEncryptedResponse() throws Exception { OIDCClientRepresentation clientRep = createRep(); response = reg.oidc().create(clientRep); - Assert.assertEquals(Boolean.FALSE, response.getTlsClientCertificateBoundAccessTokens()); - Assert.assertNotNull(response.getClientSecret()); + Assertions.assertEquals(Boolean.FALSE, response.getTlsClientCertificateBoundAccessTokens()); + Assertions.assertNotNull(response.getClientSecret()); // Test Keycloak representation ClientRepresentation kcClient = getClient(response.getClientId()); OIDCAdvancedConfigWrapper config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertNull(config.getIdTokenEncryptedResponseAlg()); - Assert.assertNull(config.getIdTokenEncryptedResponseEnc()); + Assertions.assertNull(config.getIdTokenEncryptedResponseAlg()); + Assertions.assertNull(config.getIdTokenEncryptedResponseEnc()); // update (alg RSA1_5, enc A128CBC-HS256) reg.auth(Auth.token(response)); response.setIdTokenEncryptedResponseAlg(JWEConstants.RSA1_5); response.setIdTokenEncryptedResponseEnc(JWEConstants.A128CBC_HS256); updated = reg.oidc().update(response); - Assert.assertEquals(JWEConstants.RSA1_5, updated.getIdTokenEncryptedResponseAlg()); - Assert.assertEquals(JWEConstants.A128CBC_HS256, updated.getIdTokenEncryptedResponseEnc()); + Assertions.assertEquals(JWEConstants.RSA1_5, updated.getIdTokenEncryptedResponseAlg()); + Assertions.assertEquals(JWEConstants.A128CBC_HS256, updated.getIdTokenEncryptedResponseEnc()); // Test Keycloak representation kcClient = getClient(updated.getClientId()); config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertEquals(JWEConstants.RSA1_5, config.getIdTokenEncryptedResponseAlg()); - Assert.assertEquals(JWEConstants.A128CBC_HS256, config.getIdTokenEncryptedResponseEnc()); + Assertions.assertEquals(JWEConstants.RSA1_5, config.getIdTokenEncryptedResponseAlg()); + Assertions.assertEquals(JWEConstants.A128CBC_HS256, config.getIdTokenEncryptedResponseEnc()); } finally { // revert @@ -570,23 +571,23 @@ public void testIdTokenSignedResponse() throws Exception { OIDCClientRepresentation clientRep = createRep(); response = reg.oidc().create(clientRep); - Assert.assertNull(response.getIdTokenSignedResponseAlg()); + Assertions.assertNull(response.getIdTokenSignedResponseAlg()); // Test Keycloak representation ClientRepresentation kcClient = getClient(response.getClientId()); OIDCAdvancedConfigWrapper config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertNull(config.getIdTokenSignedResponseAlg()); + Assertions.assertNull(config.getIdTokenSignedResponseAlg()); // update reg.auth(Auth.token(response)); response.setIdTokenSignedResponseAlg(Algorithm.ES256); updated = reg.oidc().update(response); - Assert.assertEquals(Algorithm.ES256, updated.getIdTokenSignedResponseAlg()); + Assertions.assertEquals(Algorithm.ES256, updated.getIdTokenSignedResponseAlg()); // Test Keycloak representation kcClient = getClient(updated.getClientId()); config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertEquals(Algorithm.ES256, config.getIdTokenSignedResponseAlg()); + Assertions.assertEquals(Algorithm.ES256, config.getIdTokenSignedResponseAlg()); } finally { // revert reg.auth(Auth.token(updated)); @@ -604,20 +605,20 @@ public void testTokenEndpointSigningAlg() throws Exception { clientRep.setTokenEndpointAuthSigningAlg(Algorithm.ES256); response = reg.oidc().create(clientRep); - Assert.assertEquals(Algorithm.ES256, response.getTokenEndpointAuthSigningAlg()); + Assertions.assertEquals(Algorithm.ES256, response.getTokenEndpointAuthSigningAlg()); ClientRepresentation kcClient = getClient(response.getClientId()); OIDCAdvancedConfigWrapper config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertEquals(Algorithm.ES256, config.getTokenEndpointAuthSigningAlg()); + Assertions.assertEquals(Algorithm.ES256, config.getTokenEndpointAuthSigningAlg()); reg.auth(Auth.token(response)); response.setTokenEndpointAuthSigningAlg(null); updated = reg.oidc().update(response); - Assert.assertEquals(null, response.getTokenEndpointAuthSigningAlg()); + Assertions.assertEquals(null, response.getTokenEndpointAuthSigningAlg()); kcClient = getClient(updated.getClientId()); config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertEquals(null, config.getTokenEndpointAuthSigningAlg()); + Assertions.assertEquals(null, config.getTokenEndpointAuthSigningAlg()); } finally { // revert reg.auth(Auth.token(updated)); @@ -635,20 +636,20 @@ public void testAuthorizationResponseSigningAlg() throws Exception { clientRep.setAuthorizationSignedResponseAlg(Algorithm.PS256); response = reg.oidc().create(clientRep); - Assert.assertEquals(Algorithm.PS256, response.getAuthorizationSignedResponseAlg()); + Assertions.assertEquals(Algorithm.PS256, response.getAuthorizationSignedResponseAlg()); ClientRepresentation kcClient = getClient(response.getClientId()); OIDCAdvancedConfigWrapper config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertEquals(Algorithm.PS256, config.getAuthorizationSignedResponseAlg()); + Assertions.assertEquals(Algorithm.PS256, config.getAuthorizationSignedResponseAlg()); reg.auth(Auth.token(response)); response.setAuthorizationSignedResponseAlg(null); updated = reg.oidc().update(response); - Assert.assertEquals(null, response.getAuthorizationSignedResponseAlg()); + Assertions.assertEquals(null, response.getAuthorizationSignedResponseAlg()); kcClient = getClient(updated.getClientId()); config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertEquals(null, config.getAuthorizationSignedResponseAlg()); + Assertions.assertEquals(null, config.getAuthorizationSignedResponseAlg()); } finally { // revert reg.auth(Auth.token(updated)); @@ -668,28 +669,28 @@ public void testAuthorizationEncryptedResponse() throws Exception { // create response = reg.oidc().create(clientRep); - Assert.assertEquals(JWEConstants.RSA1_5, response.getAuthorizationEncryptedResponseAlg()); - Assert.assertEquals(JWEConstants.A128CBC_HS256, response.getAuthorizationEncryptedResponseEnc()); + Assertions.assertEquals(JWEConstants.RSA1_5, response.getAuthorizationEncryptedResponseAlg()); + Assertions.assertEquals(JWEConstants.A128CBC_HS256, response.getAuthorizationEncryptedResponseEnc()); // Test Keycloak representation ClientRepresentation kcClient = getClient(response.getClientId()); OIDCAdvancedConfigWrapper config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertEquals(JWEConstants.RSA1_5, config.getAuthorizationEncryptedResponseAlg()); - Assert.assertEquals(JWEConstants.A128CBC_HS256, config.getAuthorizationEncryptedResponseEnc()); + Assertions.assertEquals(JWEConstants.RSA1_5, config.getAuthorizationEncryptedResponseAlg()); + Assertions.assertEquals(JWEConstants.A128CBC_HS256, config.getAuthorizationEncryptedResponseEnc()); // update reg.auth(Auth.token(response)); response.setAuthorizationEncryptedResponseAlg(null); response.setAuthorizationEncryptedResponseEnc(null); updated = reg.oidc().update(response); - Assert.assertNull(updated.getAuthorizationEncryptedResponseAlg()); - Assert.assertNull(updated.getAuthorizationEncryptedResponseEnc()); + Assertions.assertNull(updated.getAuthorizationEncryptedResponseAlg()); + Assertions.assertNull(updated.getAuthorizationEncryptedResponseEnc()); // Test Keycloak representation kcClient = getClient(updated.getClientId()); config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertNull(config.getAuthorizationEncryptedResponseAlg()); - Assert.assertNull(config.getAuthorizationEncryptedResponseEnc()); + Assertions.assertNull(config.getAuthorizationEncryptedResponseAlg()); + Assertions.assertNull(config.getAuthorizationEncryptedResponseEnc()); } finally { // revert @@ -708,11 +709,11 @@ public void testCIBASettings() throws Exception { clientRep.setBackchannelTokenDeliveryMode("poll"); response = reg.oidc().create(clientRep); - Assert.assertEquals("poll", response.getBackchannelTokenDeliveryMode()); + Assertions.assertEquals("poll", response.getBackchannelTokenDeliveryMode()); // Test Keycloak representation ClientRepresentation kcClient = getClient(response.getClientId()); - Assert.assertEquals("poll", kcClient.getAttributes().get(CibaConfig.CIBA_BACKCHANNEL_TOKEN_DELIVERY_MODE_PER_CLIENT)); + Assertions.assertEquals("poll", kcClient.getAttributes().get(CibaConfig.CIBA_BACKCHANNEL_TOKEN_DELIVERY_MODE_PER_CLIENT)); // Create with ping mode (failes due missing clientNotificationEndpoint) clientRep.setBackchannelTokenDeliveryMode("ping"); @@ -726,8 +727,8 @@ public void testCIBASettings() throws Exception { // Create with ping mode (success) clientRep.setBackchannelClientNotificationEndpoint("https://foo/bar"); response = reg.oidc().create(clientRep); - Assert.assertEquals("ping", response.getBackchannelTokenDeliveryMode()); - Assert.assertEquals("https://foo/bar", response.getBackchannelClientNotificationEndpoint()); + Assertions.assertEquals("ping", response.getBackchannelTokenDeliveryMode()); + Assertions.assertEquals("https://foo/bar", response.getBackchannelClientNotificationEndpoint()); // Create with push mode (fails) clientRep.setBackchannelTokenDeliveryMode("push"); @@ -777,28 +778,28 @@ public void testTlsClientAuthSubjectDn() throws Exception { clientRep.setTlsClientAuthSubjectDn("Ein"); response = reg.oidc().create(clientRep); - Assert.assertEquals(OIDCLoginProtocol.TLS_CLIENT_AUTH, response.getTokenEndpointAuthMethod()); - Assert.assertEquals("Ein", response.getTlsClientAuthSubjectDn()); + Assertions.assertEquals(OIDCLoginProtocol.TLS_CLIENT_AUTH, response.getTokenEndpointAuthMethod()); + Assertions.assertEquals("Ein", response.getTlsClientAuthSubjectDn()); // Test Keycloak representation ClientRepresentation kcClient = getClient(response.getClientId()); OIDCAdvancedConfigWrapper config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertEquals(X509ClientAuthenticator.PROVIDER_ID, kcClient.getClientAuthenticatorType()); - Assert.assertEquals("Ein", config.getTlsClientAuthSubjectDn()); - Assert.assertFalse(config.getAllowRegexPatternComparison()); + Assertions.assertEquals(X509ClientAuthenticator.PROVIDER_ID, kcClient.getClientAuthenticatorType()); + Assertions.assertEquals("Ein", config.getTlsClientAuthSubjectDn()); + Assertions.assertFalse(config.getAllowRegexPatternComparison()); // update reg.auth(Auth.token(response)); response.setTlsClientAuthSubjectDn("(.*?)(?:$)"); updated = reg.oidc().update(response); - Assert.assertEquals(OIDCLoginProtocol.TLS_CLIENT_AUTH, updated.getTokenEndpointAuthMethod()); - Assert.assertEquals("(.*?)(?:$)", updated.getTlsClientAuthSubjectDn()); + Assertions.assertEquals(OIDCLoginProtocol.TLS_CLIENT_AUTH, updated.getTokenEndpointAuthMethod()); + Assertions.assertEquals("(.*?)(?:$)", updated.getTlsClientAuthSubjectDn()); // Test Keycloak representation kcClient = getClient(updated.getClientId()); config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient); - Assert.assertEquals(X509ClientAuthenticator.PROVIDER_ID, kcClient.getClientAuthenticatorType()); - Assert.assertEquals("(.*?)(?:$)", config.getTlsClientAuthSubjectDn()); + Assertions.assertEquals(X509ClientAuthenticator.PROVIDER_ID, kcClient.getClientAuthenticatorType()); + Assertions.assertEquals("(.*?)(?:$)", config.getTlsClientAuthSubjectDn()); } finally { // revert reg.auth(Auth.token(updated)); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCJwksClientRegistrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCJwksClientRegistrationTest.java index 8c99e7f3efa8..5d6287a467af 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCJwksClientRegistrationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCJwksClientRegistrationTest.java @@ -46,7 +46,6 @@ import org.keycloak.representations.idm.ClientInitialAccessPresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.oidc.OIDCClientRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.client.resources.TestApplicationResourceUrls; import org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource; import org.keycloak.testsuite.rest.resource.TestingOIDCEndpointsApplicationResource; @@ -62,6 +61,7 @@ import org.apache.http.message.BasicNameValuePair; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @author Marek Posolda @@ -105,9 +105,9 @@ public void createClientWithJWKS_generatedKid() throws Exception { clientRep.setJwks(keySet); OIDCClientRepresentation response = reg.oidc().create(clientRep); - Assert.assertEquals(OIDCLoginProtocol.PRIVATE_KEY_JWT, response.getTokenEndpointAuthMethod()); - Assert.assertNull(response.getClientSecret()); - Assert.assertNull(response.getClientSecretExpiresAt()); + Assertions.assertEquals(OIDCLoginProtocol.PRIVATE_KEY_JWT, response.getTokenEndpointAuthMethod()); + Assertions.assertNull(response.getClientSecret()); + Assertions.assertNull(response.getClientSecretExpiresAt()); // Tries to authenticate client with privateKey JWT assertAuthenticateClientSuccess(generatedKeys, response, KEEP_GENERATED_KID); @@ -200,7 +200,7 @@ public void testTwoClientsWithSameKid() throws Exception { // Assert item in publicKey cache for client1 String expectedCacheKey = PublicKeyStorageUtils.getClientModelCacheKey( adminClient.realm(REALM_NAME).toRepresentation().getId(), response.getClientId()); - Assert.assertTrue(testingClient.testing().cache(InfinispanConnectionProvider.KEYS_CACHE_NAME).contains(expectedCacheKey)); + Assertions.assertTrue(testingClient.testing().cache(InfinispanConnectionProvider.KEYS_CACHE_NAME).contains(expectedCacheKey)); // Assert it's not possible to authenticate as client2 with the same "kid" like client1 assertAuthenticateClientError(generatedKeys, clientRep2, "a1"); @@ -219,7 +219,7 @@ public void testPublicKeyCacheInvalidatedWhenUpdatingClient() throws Exception { // Assert item in publicKey cache for client1 String expectedCacheKey = PublicKeyStorageUtils.getClientModelCacheKey( adminClient.realm(REALM_NAME).toRepresentation().getId(), response.getClientId()); - Assert.assertTrue(testingClient.testing().cache(InfinispanConnectionProvider.KEYS_CACHE_NAME).contains(expectedCacheKey)); + Assertions.assertTrue(testingClient.testing().cache(InfinispanConnectionProvider.KEYS_CACHE_NAME).contains(expectedCacheKey)); @@ -230,7 +230,7 @@ public void testPublicKeyCacheInvalidatedWhenUpdatingClient() throws Exception { .oidc().update(response); // Assert item not any longer for client1 - Assert.assertFalse(testingClient.testing().cache(InfinispanConnectionProvider.KEYS_CACHE_NAME).contains(expectedCacheKey)); + Assertions.assertFalse(testingClient.testing().cache(InfinispanConnectionProvider.KEYS_CACHE_NAME).contains(expectedCacheKey)); // Assert it's not possible to authenticate as client1 assertAuthenticateClientError(generatedKeys, response, "a1"); @@ -251,10 +251,10 @@ public void createClientWithJWKSURI() throws Exception { clientRep.setJwksUri(TestApplicationResourceUrls.clientJwksUri()); OIDCClientRepresentation response = reg.oidc().create(clientRep); - Assert.assertEquals(OIDCLoginProtocol.PRIVATE_KEY_JWT, response.getTokenEndpointAuthMethod()); - Assert.assertNull(response.getClientSecret()); - Assert.assertNull(response.getClientSecretExpiresAt()); - Assert.assertEquals(response.getJwksUri(), TestApplicationResourceUrls.clientJwksUri()); + Assertions.assertEquals(OIDCLoginProtocol.PRIVATE_KEY_JWT, response.getTokenEndpointAuthMethod()); + Assertions.assertNull(response.getClientSecret()); + Assertions.assertNull(response.getClientSecretExpiresAt()); + Assertions.assertEquals(response.getJwksUri(), TestApplicationResourceUrls.clientJwksUri()); // Tries to authenticate client with privateKey JWT assertAuthenticateClientSuccess(generatedKeys, response, KEEP_GENERATED_KID); @@ -274,10 +274,10 @@ public void createClientWithJWKSURI_rotateClientKeys() throws Exception { clientRep.setJwksUri(TestApplicationResourceUrls.clientJwksUri()); OIDCClientRepresentation response = reg.oidc().create(clientRep); - Assert.assertEquals(OIDCLoginProtocol.PRIVATE_KEY_JWT, response.getTokenEndpointAuthMethod()); - Assert.assertNull(response.getClientSecret()); - Assert.assertNull(response.getClientSecretExpiresAt()); - Assert.assertEquals(response.getJwksUri(), TestApplicationResourceUrls.clientJwksUri()); + Assertions.assertEquals(OIDCLoginProtocol.PRIVATE_KEY_JWT, response.getTokenEndpointAuthMethod()); + Assertions.assertNull(response.getClientSecret()); + Assertions.assertNull(response.getClientSecretExpiresAt()); + Assertions.assertEquals(response.getJwksUri(), TestApplicationResourceUrls.clientJwksUri()); // Tries to authenticate client with privateKey JWT assertAuthenticateClientSuccess(generatedKeys, response, KEEP_GENERATED_KID); @@ -301,18 +301,18 @@ private void assertAuthenticateClientSuccess(Map generatedKeys, KeyPair keyPair = getKeyPairFromGeneratedPems(generatedKeys); String signedJwt = getClientSignedJWT(response.getClientId(), keyPair, kid); AccessTokenResponse accessTokenResponse = doClientCredentialsGrantRequest(signedJwt); - Assert.assertEquals(200, accessTokenResponse.getStatusCode()); + Assertions.assertEquals(200, accessTokenResponse.getStatusCode()); AccessToken accessToken = oauth.verifyToken(accessTokenResponse.getAccessToken()); - Assert.assertEquals(response.getClientId(), accessToken.getIssuedFor()); + Assertions.assertEquals(response.getClientId(), accessToken.getIssuedFor()); } private void assertAuthenticateClientError(Map generatedKeys, OIDCClientRepresentation response, String kid) throws Exception { KeyPair keyPair = getKeyPairFromGeneratedPems(generatedKeys); String signedJwt = getClientSignedJWT(response.getClientId(), keyPair, kid); AccessTokenResponse accessTokenResponse = doClientCredentialsGrantRequest(signedJwt); - Assert.assertEquals(400, accessTokenResponse.getStatusCode()); - Assert.assertNull(accessTokenResponse.getAccessToken()); - Assert.assertNotNull(accessTokenResponse.getError()); + Assertions.assertEquals(400, accessTokenResponse.getStatusCode()); + Assertions.assertNull(accessTokenResponse.getAccessToken()); + Assertions.assertNotNull(accessTokenResponse.getError()); } private KeyPair getKeyPairFromGeneratedPems(Map generatedKeys) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCPairwiseClientRegistrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCPairwiseClientRegistrationTest.java index 803d1f3c0479..3a36937fff17 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCPairwiseClientRegistrationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCPairwiseClientRegistrationTest.java @@ -58,10 +58,11 @@ import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public class OIDCPairwiseClientRegistrationTest extends AbstractClientRegistrationTest { @@ -105,12 +106,12 @@ public OIDCClientRepresentation createPairwise() throws ClientRegistrationExcept private void assertCreateFail(OIDCClientRepresentation client, int expectedStatusCode, String expectedErrorContains) { try { reg.oidc().create(client); - Assert.fail("Not expected to successfuly register client"); + Assertions.fail("Not expected to successfuly register client"); } catch (ClientRegistrationException expected) { HttpErrorException httpEx = (HttpErrorException) expected.getCause(); - Assert.assertEquals(expectedStatusCode, httpEx.getStatusLine().getStatusCode()); + Assertions.assertEquals(expectedStatusCode, httpEx.getStatusLine().getStatusCode()); if (expectedErrorContains != null) { - assertTrue("Error response doesn't contain expected text", httpEx.getErrorResponse().contains(expectedErrorContains)); + assertTrue(httpEx.getErrorResponse().contains(expectedErrorContains), "Error response doesn't contain expected text"); } } } @@ -121,19 +122,19 @@ public void createPairwiseClient() throws Exception { clientRep.setSubjectType("pairwise"); OIDCClientRepresentation response = reg.oidc().create(clientRep); - Assert.assertEquals("pairwise", response.getSubjectType()); + Assertions.assertEquals("pairwise", response.getSubjectType()); } @Test public void updateClientToPairwise() throws Exception { OIDCClientRepresentation response = create(); - Assert.assertEquals("public", response.getSubjectType()); + Assertions.assertEquals("public", response.getSubjectType()); reg.auth(Auth.token(response)); response.setSubjectType("pairwise"); OIDCClientRepresentation updated = reg.oidc().update(response); - Assert.assertEquals("pairwise", updated.getSubjectType()); + Assertions.assertEquals("pairwise", updated.getSubjectType()); } @Test @@ -141,8 +142,8 @@ public void updateSectorIdentifierUri() throws Exception { OIDCClientRepresentation clientRep = createRep(); clientRep.setSubjectType("pairwise"); OIDCClientRepresentation response = reg.oidc().create(clientRep); - Assert.assertEquals("pairwise", response.getSubjectType()); - Assert.assertNull(response.getSectorIdentifierUri()); + Assertions.assertEquals("pairwise", response.getSubjectType()); + Assertions.assertNull(response.getSectorIdentifierUri()); reg.auth(Auth.token(response)); @@ -156,16 +157,16 @@ public void updateSectorIdentifierUri() throws Exception { OIDCClientRepresentation updated = reg.oidc().update(response); - Assert.assertEquals("pairwise", updated.getSubjectType()); - Assert.assertEquals(TestApplicationResourceUrls.pairwiseSectorIdentifierUri(), updated.getSectorIdentifierUri()); + Assertions.assertEquals("pairwise", updated.getSubjectType()); + Assertions.assertEquals(TestApplicationResourceUrls.pairwiseSectorIdentifierUri(), updated.getSectorIdentifierUri()); } @Test public void updateToPairwiseThroughAdminRESTSuccess() throws Exception { OIDCClientRepresentation response = create(); - Assert.assertEquals("public", response.getSubjectType()); - Assert.assertNull(response.getSectorIdentifierUri()); + Assertions.assertEquals("public", response.getSubjectType()); + Assertions.assertNull(response.getSectorIdentifierUri()); // Push redirect uris to the sector identifier URI List sectorRedirects = new ArrayList<>(); @@ -183,16 +184,16 @@ public void updateToPairwiseThroughAdminRESTSuccess() throws Exception { reg.auth(Auth.token(response)); OIDCClientRepresentation rep = reg.oidc().get(response.getClientId()); - Assert.assertEquals("pairwise", rep.getSubjectType()); - Assert.assertEquals(sectorIdentifierUri, rep.getSectorIdentifierUri()); + Assertions.assertEquals("pairwise", rep.getSubjectType()); + Assertions.assertEquals(sectorIdentifierUri, rep.getSectorIdentifierUri()); } @Test public void updateToPairwiseThroughAdminRESTFailure() throws Exception { OIDCClientRepresentation response = create(); - Assert.assertEquals("public", response.getSubjectType()); - Assert.assertNull(response.getSectorIdentifierUri()); + Assertions.assertEquals("public", response.getSubjectType()); + Assertions.assertNull(response.getSectorIdentifierUri()); // Push empty list to the sector identifier URI TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints(); @@ -206,13 +207,13 @@ public void updateToPairwiseThroughAdminRESTFailure() throws Exception { RealmResource realmResource = realmsResouce().realm("test"); ClientResource clientResource = AdminApiUtil.findClientByClientId(realmsResouce().realm("test"), clientId); Response resp = clientResource.getProtocolMappers().createMapper(pairwiseProtMapper); - Assert.assertEquals(400, resp.getStatus()); + Assertions.assertEquals(400, resp.getStatus()); // Assert still public reg.auth(Auth.token(response)); OIDCClientRepresentation rep = reg.oidc().get(response.getClientId()); - Assert.assertEquals("public", rep.getSubjectType()); - Assert.assertNull(rep.getSectorIdentifierUri()); + Assertions.assertEquals("public", rep.getSubjectType()); + Assertions.assertNull(rep.getSectorIdentifierUri()); } @Test @@ -229,8 +230,8 @@ public void createPairwiseClientWithSectorIdentifierURI() throws Exception { clientRep.setSectorIdentifierUri(TestApplicationResourceUrls.pairwiseSectorIdentifierUri()); OIDCClientRepresentation response = reg.oidc().create(clientRep); - Assert.assertEquals("pairwise", response.getSubjectType()); - Assert.assertEquals(TestApplicationResourceUrls.pairwiseSectorIdentifierUri(), response.getSectorIdentifierUri()); + Assertions.assertEquals("pairwise", response.getSubjectType()); + Assertions.assertEquals(TestApplicationResourceUrls.pairwiseSectorIdentifierUri(), response.getSectorIdentifierUri()); } @Test @@ -263,8 +264,8 @@ public void createPairwiseClientWithRedirectsToMultipleHosts() throws Exception clientRep.setRedirectUris(redirects); OIDCClientRepresentation response = reg.oidc().create(clientRep); - Assert.assertEquals("pairwise", response.getSubjectType()); - Assert.assertEquals(TestApplicationResourceUrls.pairwiseSectorIdentifierUri(), response.getSectorIdentifierUri()); + Assertions.assertEquals("pairwise", response.getSubjectType()); + Assertions.assertEquals(TestApplicationResourceUrls.pairwiseSectorIdentifierUri(), response.getSectorIdentifierUri()); Assert.assertNames(response.getRedirectUris(), "http://redirect1", "http://redirect2"); } @@ -326,17 +327,17 @@ public void loginUserToPairwiseClient() throws Exception { AuthorizationEndpointResponse loginResponse = oauth.doLogin("test-user@localhost", "password"); AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(loginResponse.getCode()); AccessToken accessToken = oauth.verifyToken(accessTokenResponse.getAccessToken()); - Assert.assertEquals("test-user", accessToken.getPreferredUsername()); - Assert.assertEquals("test-user@localhost", accessToken.getEmail()); + Assertions.assertEquals("test-user", accessToken.getPreferredUsername()); + Assertions.assertEquals("test-user@localhost", accessToken.getEmail()); String tokenUserId = accessToken.getSubject(); // Assert public client has same subject like userId UserRepresentation user = realmsResouce().realm("test").users().search("test-user", 0, 1).get(0); - Assert.assertEquals(user.getId(), tokenUserId); + Assertions.assertEquals(user.getId(), tokenUserId); // Create pairwise client OIDCClientRepresentation pairwiseClient = createPairwise(); - Assert.assertEquals("pairwise", pairwiseClient.getSubjectType()); + Assertions.assertEquals("pairwise", pairwiseClient.getSubjectType()); // Login to pairwise client oauth.client(pairwiseClient.getClientId(), pairwiseClient.getClientSecret()); oauth.openLoginForm(); @@ -345,19 +346,19 @@ public void loginUserToPairwiseClient() throws Exception { // Assert token payloads don't contain more than one "sub" String accessTokenPayload = getPayload(accessTokenResponse.getAccessToken()); - Assert.assertEquals(1, StringUtils.countMatches(accessTokenPayload, "\"sub\"")); + Assertions.assertEquals(1, StringUtils.countMatches(accessTokenPayload, "\"sub\"")); String idTokenPayload = getPayload(accessTokenResponse.getIdToken()); - Assert.assertEquals(1, StringUtils.countMatches(idTokenPayload, "\"sub\"")); + Assertions.assertEquals(1, StringUtils.countMatches(idTokenPayload, "\"sub\"")); String refreshTokenPayload = getPayload(accessTokenResponse.getRefreshToken()); - Assert.assertEquals(1, StringUtils.countMatches(refreshTokenPayload, "\"sub\"")); + Assertions.assertEquals(1, StringUtils.countMatches(refreshTokenPayload, "\"sub\"")); accessToken = oauth.verifyToken(accessTokenResponse.getAccessToken()); - Assert.assertEquals("test-user", accessToken.getPreferredUsername()); - Assert.assertEquals("test-user@localhost", accessToken.getEmail()); + Assertions.assertEquals("test-user", accessToken.getPreferredUsername()); + Assertions.assertEquals("test-user@localhost", accessToken.getEmail()); // Assert pairwise client has different subject than userId String pairwiseUserId = accessToken.getSubject(); - Assert.assertNotEquals(pairwiseUserId, user.getId()); + Assertions.assertNotEquals(pairwiseUserId, user.getId()); // Send request to userInfo endpoint Client jaxrsClient = AdminClientUtil.createResteasyClient(); @@ -366,7 +367,7 @@ public void loginUserToPairwiseClient() throws Exception { Response userInfoResponse = UserInfoClientUtil.executeUserInfoRequest_getMethod(jaxrsClient, accessTokenResponse.getAccessToken()); UserInfo userInfo = UserInfoClientUtil.testSuccessfulUserInfoResponse(userInfoResponse, "test-user", "test-user@localhost"); String userInfoSubId = userInfo.getSubject(); - Assert.assertEquals(pairwiseUserId, userInfoSubId); + Assertions.assertEquals(pairwiseUserId, userInfoSubId); } finally { jaxrsClient.close(); } @@ -394,21 +395,21 @@ public void refreshPairwiseToken() throws Exception { // If an ID Token is returned as a result of a token refresh request, the following requirements apply: // its iss Claim Value MUST be the same as in the ID Token issued when the original authentication occurred - Assert.assertEquals(idToken.getIssuer(), refreshedRefreshToken.getIssuer()); + Assertions.assertEquals(idToken.getIssuer(), refreshedRefreshToken.getIssuer()); // its sub Claim Value MUST be the same as in the ID Token issued when the original authentication occurred - Assert.assertEquals(idToken.getSubject(), refreshedRefreshToken.getSubject()); + Assertions.assertEquals(idToken.getSubject(), refreshedRefreshToken.getSubject()); // its iat Claim MUST represent the time that the new ID Token is issued - Assert.assertEquals(refreshedIdToken.getIat(), refreshedRefreshToken.getIat()); + Assertions.assertEquals(refreshedIdToken.getIat(), refreshedRefreshToken.getIat()); // if the ID Token contains an auth_time Claim, its value MUST represent the time of the original authentication // - not the time that the new ID token is issued - Assert.assertEquals(idToken.getAuth_time(), refreshedIdToken.getAuth_time()); + Assertions.assertEquals(idToken.getAuth_time(), refreshedIdToken.getAuth_time()); // its azp Claim Value MUST be the same as in the ID Token issued when the original authentication occurred; if // no azp Claim was present in the original ID Token, one MUST NOT be present in the new ID Token - Assert.assertEquals(idToken.getIssuedFor(), refreshedIdToken.getIssuedFor()); + Assertions.assertEquals(idToken.getIssuedFor(), refreshedIdToken.getIssuedFor()); } @Test @@ -420,8 +421,8 @@ public void introspectPairwiseAccessToken() throws Exception { AccessTokenResponse accessTokenResponse = login(pairwiseClient, "test-user@localhost", "password"); JsonNode jsonNode = oauth.client(pairwiseClient.getClientId(), pairwiseClient.getClientSecret()).doIntrospectionAccessTokenRequest(accessTokenResponse.getAccessToken()).asJsonNode(); - Assert.assertEquals(true, jsonNode.get("active").asBoolean()); - Assert.assertEquals("test-user@localhost", jsonNode.get("email").asText()); + Assertions.assertEquals(true, jsonNode.get("active").asBoolean()); + Assertions.assertEquals("test-user@localhost", jsonNode.get("email").asText()); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/RegistrationAccessTokenTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/RegistrationAccessTokenTest.java index 6b31a920ecca..743d7c104641 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/RegistrationAccessTokenTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/RegistrationAccessTokenTest.java @@ -25,11 +25,11 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Stian Thorgersen diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/SAMLClientRegistrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/SAMLClientRegistrationTest.java index d84ed12d0b36..ca9e1853921c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/SAMLClientRegistrationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/SAMLClientRegistrationTest.java @@ -35,12 +35,12 @@ import org.keycloak.representations.idm.ProtocolMapperRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.RoleRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.KeycloakModelUtils; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.auth.page.AuthRealm.TEST; @@ -113,13 +113,13 @@ private void assertClientCreation(String entityDescriptor) throws ClientRegistra assertThat(response.getAttributes().get(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_SOAP_ATTRIBUTE), is("https://LoadBalancer-9.siroe.com:3443/federation/SPSloSoap/metaAlias/sp")); assertThat(response.getAttributes().get(SamlConfigAttributes.SAML_ARTIFACT_BINDING_IDENTIFIER), is(ArtifactBindingUtils.computeArtifactBindingIdentifierString("loadbalancer-9.siroe.com"))); - Assert.assertNotNull(response.getProtocolMappers()); - Assert.assertEquals(1,response.getProtocolMappers().size()); + Assertions.assertNotNull(response.getProtocolMappers()); + Assertions.assertEquals(1,response.getProtocolMappers().size()); ProtocolMapperRepresentation mapper = response.getProtocolMappers().get(0); - Assert.assertEquals("saml-user-attribute-mapper",mapper.getProtocolMapper()); - Assert.assertEquals("urn:oid:2.5.4.42",mapper.getConfig().get(AttributeStatementHelper.SAML_ATTRIBUTE_NAME)); - Assert.assertEquals("givenName",mapper.getConfig().get(AttributeStatementHelper.FRIENDLY_NAME)); - Assert.assertEquals(AttributeStatementHelper.URI_REFERENCE,mapper.getConfig().get(AttributeStatementHelper.SAML_ATTRIBUTE_NAMEFORMAT)); + Assertions.assertEquals("saml-user-attribute-mapper",mapper.getProtocolMapper()); + Assertions.assertEquals("urn:oid:2.5.4.42",mapper.getConfig().get(AttributeStatementHelper.SAML_ATTRIBUTE_NAME)); + Assertions.assertEquals("givenName",mapper.getConfig().get(AttributeStatementHelper.FRIENDLY_NAME)); + Assertions.assertEquals(AttributeStatementHelper.URI_REFERENCE,mapper.getConfig().get(AttributeStatementHelper.SAML_ATTRIBUTE_NAMEFORMAT)); adminClient.realm(REALM_NAME).clients().get(response.getId()).remove(); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/AbstractClientPoliciesTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/AbstractClientPoliciesTest.java index a53bc0c01141..d746c55431f6 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/AbstractClientPoliciesTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/AbstractClientPoliciesTest.java @@ -123,7 +123,6 @@ import org.keycloak.services.clientpolicy.executor.SecureSigningAlgorithmExecutorFactory; import org.keycloak.services.clientpolicy.executor.SecureSigningAlgorithmForSignedJwtExecutorFactory; import org.keycloak.testsuite.AbstractKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.admin.ApiUtil; @@ -168,6 +167,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.admin.AdminApiUtil.findUserByUsername; import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientAccessTypeConditionConfig; @@ -183,11 +183,11 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Takashi Norimatsu @@ -1066,38 +1066,38 @@ protected void assertExpectedConditions(List expectedConditions, ClientP protected void assertExpectedClientAccessTypeCondition(List type, ClientPolicyRepresentation policyRep) { ClientAccessTypeCondition.Configuration cfg = getConfigAsExpectedType(policyRep, ClientAccessTypeConditionFactory.PROVIDER_ID, ClientAccessTypeCondition.Configuration.class); - Assert.assertEquals(cfg.getType(), type); + Assertions.assertEquals(cfg.getType(), type); } protected void assertExpectedClientRolesCondition(List roles, ClientPolicyRepresentation policyRep) { ClientRolesCondition.Configuration cfg = getConfigAsExpectedType(policyRep, ClientRolesConditionFactory.PROVIDER_ID, ClientRolesCondition.Configuration.class); - Assert.assertEquals(cfg.getRoles(), roles); + Assertions.assertEquals(cfg.getRoles(), roles); } protected void assertExpectedClientScopesCondition(String type, List scopes, ClientPolicyRepresentation policyRep) { ClientScopesCondition.Configuration cfg = getConfigAsExpectedType(policyRep, ClientScopesConditionFactory.PROVIDER_ID, ClientScopesCondition.Configuration.class); - Assert.assertEquals(cfg.getType(), type); - Assert.assertEquals(cfg.getScopes(), scopes); + Assertions.assertEquals(cfg.getType(), type); + Assertions.assertEquals(cfg.getScopes(), scopes); } protected void assertExpectedClientUpdateContextCondition(List updateClientSources, ClientPolicyRepresentation policyRep) { ClientUpdaterContextCondition.Configuration cfg = getConfigAsExpectedType(policyRep, ClientUpdaterContextConditionFactory.PROVIDER_ID, ClientUpdaterContextCondition.Configuration.class); - Assert.assertEquals(cfg.getUpdateClientSource(), updateClientSources); + Assertions.assertEquals(cfg.getUpdateClientSource(), updateClientSources); } protected void assertExpectedClientUpdateSourceGroupsCondition(List groups, ClientPolicyRepresentation policyRep) { ClientUpdaterSourceGroupsCondition.Configuration cfg = getConfigAsExpectedType(policyRep, ClientUpdaterSourceGroupsConditionFactory.PROVIDER_ID, ClientUpdaterSourceGroupsCondition.Configuration.class); - Assert.assertEquals(cfg.getGroups(), groups); + Assertions.assertEquals(cfg.getGroups(), groups); } protected void assertExpectedClientUpdateSourceHostsCondition(List trustedHosts, ClientPolicyRepresentation policyRep) { ClientUpdaterSourceHostsCondition.Configuration cfg = getConfigAsExpectedType(policyRep, ClientUpdaterSourceHostsConditionFactory.PROVIDER_ID, ClientUpdaterSourceHostsCondition.Configuration.class); - Assert.assertEquals(cfg.getTrustedHosts(), trustedHosts); + Assertions.assertEquals(cfg.getTrustedHosts(), trustedHosts); } protected void assertExpectedClientUpdateSourceRolesCondition(List roles, ClientPolicyRepresentation policyRep) { ClientUpdaterSourceRolesCondition.Configuration cfg = getConfigAsExpectedType(policyRep, ClientUpdaterSourceRolesConditionFactory.PROVIDER_ID, ClientUpdaterSourceRolesCondition.Configuration.class); - Assert.assertEquals(cfg.getRoles(), roles); + Assertions.assertEquals(cfg.getRoles(), roles); } private CFG getConfigAsExpectedType(ClientPolicyRepresentation policyRep, String conditionProviderId, Class configClass) { @@ -1134,7 +1134,7 @@ private T getCompoundRepresentation(R rep, String name, Function adminClient.realm(REALM_NAME).clientPoliciesPoliciesResource().updatePolicies(clientPolicies)); ErrorRepresentation error = e.getResponse().readEntity(ErrorRepresentation.class); - Assert.assertEquals("Invalid client-scopes configuration - Client scopes not allowed: [fake-client-scope]", error.getErrorMessage()); + Assertions.assertEquals("Invalid client-scopes configuration - Client scopes not allowed: [fake-client-scope]", error.getErrorMessage()); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesExecutorTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesExecutorTest.java index 1fa5cdd7e554..051a1043d2a0 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesExecutorTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesExecutorTest.java @@ -124,8 +124,8 @@ import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.util.ClientPoliciesUtil.createAnyClientConditionConfig; @@ -139,10 +139,10 @@ import static org.hamcrest.Matchers.emptyOrNullString; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * This test class is for testing an executor of client policies. @@ -263,7 +263,7 @@ public void testSecureClientAuthenticatorDuringLogin() throws Exception { ClientResource clientResource = AdminApiUtil.findClientByClientId(adminClient.realm(REALM_NAME), clientId); assert clientResource != null; ClientRepresentation clientRep = clientResource.toRepresentation(); - Assert.assertEquals(ClientIdAndSecretAuthenticator.PROVIDER_ID, clientRep.getClientAuthenticatorType()); + Assertions.assertEquals(ClientIdAndSecretAuthenticator.PROVIDER_ID, clientRep.getClientAuthenticatorType()); clientResource.roles().create(RoleBuilder.create().name(roleAlphaName).build()); // Not allowed to client authentication with clientIdAndSecret anymore. Client matches policy now @@ -459,15 +459,15 @@ public void testSecureResponseTypeExecutorAllowTokenResponseType() throws Except IDToken idToken = oauth.verifyIDToken(authorizationEndpointResponse.getIdToken()); // confirm ID token as detached signature does not include authenticated user's claims - Assert.assertNull(idToken.getEmailVerified()); - Assert.assertNull(idToken.getName()); - Assert.assertNull(idToken.getPreferredUsername()); - Assert.assertNull(idToken.getGivenName()); - Assert.assertNull(idToken.getFamilyName()); - Assert.assertNull(idToken.getEmail()); + Assertions.assertNull(idToken.getEmailVerified()); + Assertions.assertNull(idToken.getName()); + Assertions.assertNull(idToken.getPreferredUsername()); + Assertions.assertNull(idToken.getGivenName()); + Assertions.assertNull(idToken.getFamilyName()); + Assertions.assertNull(idToken.getEmail()); assertEquals("LIVieviDie028f", idToken.getNonce()); // confirm an access token not returned - Assert.assertNull(authorizationEndpointResponse.getAccessToken()); + Assertions.assertNull(authorizationEndpointResponse.getAccessToken()); AccessTokenResponse res = oauth.doAccessTokenRequest(code); assertEquals(200, res.getStatusCode()); @@ -964,7 +964,7 @@ public void testSecureSessionEnforceExecutorWithAccountConsole() throws Exceptio .codeChallenge(PkceGenerator.s256()) .open(); loginPage.assertCurrent(); - Assert.assertEquals("Sign in to your account", loginPage.getTitleText()); + Assertions.assertEquals("Sign in to your account", loginPage.getTitleText()); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesExtendedEventTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesExtendedEventTest.java index 11da5ec4fe77..8bbe73c6a849 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesExtendedEventTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesExtendedEventTest.java @@ -65,8 +65,8 @@ import org.keycloak.testsuite.util.oauth.device.DeviceAuthorizationResponse; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.admin.AdminApiUtil.findUserByUsername; @@ -78,11 +78,11 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * This test class is for testing a newly supported event for client policies. @@ -281,7 +281,7 @@ public void testExtendedClientPolicyInterfacesForDeviceTokenRequest() throws Exc oauth.client(DEVICE_APP, "secret"); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); @@ -336,7 +336,7 @@ public void testExtendedClientPolicyInterfacesForDeviceTokenResponse() throws Ex oauth.client(DEVICE_APP, "secret"); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); @@ -533,9 +533,9 @@ public void testExtendedClientPolicyInterfacesForTokenRefreshResponseWithOffline updatePolicies(json); // now the online session should be removed as it's an offline first request - NotFoundException nfe = Assert.assertThrows(NotFoundException.class, + NotFoundException nfe = Assertions.assertThrows(NotFoundException.class, () -> adminClient.realm(REALM_NAME).deleteSession(token.getSessionId(), false)); - Assert.assertEquals(404, nfe.getResponse().getStatus()); + Assertions.assertEquals(404, nfe.getResponse().getStatus()); String refreshTokenString = res.getRefreshToken(); AccessTokenResponse accessTokenResponseRefreshed = oauth.doRefreshTokenRequest(refreshTokenString); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesFeatureTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesFeatureTest.java index 811884e2c4a7..e101fd67fa8d 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesFeatureTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesFeatureTest.java @@ -28,15 +28,15 @@ import org.keycloak.services.clientpolicy.executor.ClientPolicyExecutorSpi; import org.keycloak.services.clientpolicy.executor.SecureResponseTypeExecutorFactory; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.arquillian.annotation.DisableFeature; import org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.common.Profile.Feature.CLIENT_POLICIES; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * This test class is for enabling and disabling client policies by feature mechanism. @@ -65,7 +65,7 @@ public void testFeatureDoesntWorkWhenDisabled() { private void checkIfFeatureWorks(boolean shouldWork) { try { ClientPoliciesRepresentation clientPolicies = testRealm().clientPoliciesPoliciesResource().getPolicies(); - Assert.assertTrue(clientPolicies.getPolicies().isEmpty()); + Assertions.assertTrue(clientPolicies.getPolicies().isEmpty()); if (!shouldWork) fail("Feature is available, but at this moment should be disabled"); @@ -81,11 +81,11 @@ private void checkIfFeatureWorks(boolean shouldWork) { Set conditionProviderIds = serverInfo.getProviders().get(ClientPolicyConditionSpi.SPI_NAME).getProviders().keySet(); if (shouldWork) { - Assert.assertTrue(executorProviderIds.contains(SecureResponseTypeExecutorFactory.PROVIDER_ID)); - Assert.assertTrue(conditionProviderIds.contains(ClientUpdaterContextConditionFactory.PROVIDER_ID)); + Assertions.assertTrue(executorProviderIds.contains(SecureResponseTypeExecutorFactory.PROVIDER_ID)); + Assertions.assertTrue(conditionProviderIds.contains(ClientUpdaterContextConditionFactory.PROVIDER_ID)); } else { - Assert.assertFalse(executorProviderIds.contains(SecureResponseTypeExecutorFactory.PROVIDER_ID)); - Assert.assertFalse(conditionProviderIds.contains(ClientUpdaterContextConditionFactory.PROVIDER_ID)); + Assertions.assertFalse(executorProviderIds.contains(SecureResponseTypeExecutorFactory.PROVIDER_ID)); + Assertions.assertFalse(conditionProviderIds.contains(ClientUpdaterContextConditionFactory.PROVIDER_ID)); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesLoadUpdateTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesLoadUpdateTest.java index 39e034876472..4edc6fde637d 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesLoadUpdateTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesLoadUpdateTest.java @@ -41,7 +41,6 @@ import org.keycloak.services.clientpolicy.executor.SecureClientAuthenticatorExecutorFactory; import org.keycloak.services.clientpolicy.executor.SecureClientUrisExecutorFactory; import org.keycloak.services.clientpolicy.executor.SecureSessionEnforceExecutorFactory; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPoliciesBuilder; import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPolicyBuilder; import org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfileBuilder; @@ -49,6 +48,7 @@ import org.hamcrest.Matchers; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.util.ClientPoliciesUtil.createClientAccessTypeConditionConfig; @@ -57,8 +57,8 @@ import static org.keycloak.testsuite.util.ClientPoliciesUtil.createSecureClientAuthenticatorExecutorConfig; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * This test class is for testing loading and updating profiles and policies file of client policies. @@ -107,7 +107,7 @@ public void testLoadBuiltinProfilesAndPolicies() throws Exception { // No global policies expected assertExpectedPolicies(Collections.emptyList(), actualPoliciesRep); ClientPolicyRepresentation actualPolicyRep = getPolicyRepresentation(actualPoliciesRep, "builtin-default-policy"); - Assert.assertNull(actualPolicyRep); + Assertions.assertNull(actualPolicyRep); } @Test @@ -264,7 +264,7 @@ public void testUpdatingGlobalProfilesNotAllowed() throws Exception { // Doublecheck global profiles were not changed clientProfilesRep = adminClient.realm(REALM_NAME).clientPoliciesProfilesResource().getProfiles(true); - Assert.assertEquals(origGlobalProfiles, clientProfilesRep.getGlobalProfiles()); + Assertions.assertEquals(origGlobalProfiles, clientProfilesRep.getGlobalProfiles()); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesTest.java index f577dca3e7a6..8889f8d7c40f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/ClientPoliciesTest.java @@ -113,9 +113,9 @@ import com.fasterxml.jackson.databind.node.TextNode; import org.apache.http.impl.client.CloseableHttpClient; import org.jboss.logging.Logger; -import org.junit.Assert; import org.junit.Assume; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.OAuth2Constants.SCOPE_PHONE; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; @@ -144,11 +144,11 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Takashi Norimatsu @@ -612,7 +612,7 @@ public void testSuppressRefreshTokenRotationWithHolderOfKeyToken() throws Except cau.update(); // Check login. AuthorizationEndpointResponse loginResponse = oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD); - Assert.assertNull(loginResponse.getError()); + Assertions.assertNull(loginResponse.getError()); String code = oauth.parseLoginResponse().getCode(); @@ -847,14 +847,14 @@ public void testConsentRequiredExecutorWithClientRolesCondition() throws Excepti clientRep.setImplicitFlowEnabled(Boolean.FALSE); clientRep.setConsentRequired(Boolean.FALSE); }); - Assert.assertFalse(getClientByAdmin(cid).isConsentRequired()); + Assertions.assertFalse(getClientByAdmin(cid).isConsentRequired()); // add the role to the client to execute condition adminClient.realm(REALM_NAME).clients().get(cid).roles().create(RoleBuilder.create().name(SAMPLE_CLIENT_ROLE).build()); // update with consent to false should be updated to true by autoconfigure updateClientByAdmin(cid, (ClientRepresentation cRep) -> cRep.setConsentRequired(Boolean.FALSE)); - Assert.assertTrue(getClientByAdmin(cid).isConsentRequired()); + Assertions.assertTrue(getClientByAdmin(cid).isConsentRequired()); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/SamlClientPoliciesExecutorTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/SamlClientPoliciesExecutorTest.java index a9e9c9df5424..d3029eb78302 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/SamlClientPoliciesExecutorTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/SamlClientPoliciesExecutorTest.java @@ -59,8 +59,8 @@ import org.apache.http.util.EntityUtils; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @@ -276,7 +276,7 @@ private void testAuthenticationPostSignatureSuccess(RealmResource realm, ClientR String kid = keysMetadata.getActive().get(Constants.DEFAULT_SIGNATURE_ALGORITHM); KeyMetadataRepresentation keyMetadata = keysMetadata.getKeys().stream() .filter(k -> kid.equals(k.getKid())).findAny().orElse(null); - Assert.assertNotNull(keyMetadata); + Assertions.assertNotNull(keyMetadata); new SamlClientBuilder() .authnRequest(RealmsResource.protocolUrl(UriBuilder.fromUri(getAuthServerRoot())).build(TEST_REALM_NAME, SamlProtocol.LOGIN_PROTOCOL), @@ -301,7 +301,7 @@ private void testAuthenticationPostError(ClientRepresentation client, String ass client.getClientId(), assertionUrl, SamlClient.Binding.POST) .build() .executeAndTransform(response -> { - Assert.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusLine().getStatusCode()); + Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusLine().getStatusCode()); MatcherAssert.assertThat(EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8), Matchers.containsString("Invalid Request")); return null; @@ -331,7 +331,7 @@ private void testAuthenticationRedirectPostError(ClientRepresentation client) { client.getClientId(), client.getAdminUrl(), SamlClient.Binding.REDIRECT) .build() .executeAndTransform(response -> { - Assert.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusLine().getStatusCode()); + Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusLine().getStatusCode()); MatcherAssert.assertThat(EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8), Matchers.containsString("Invalid Request")); return null; @@ -343,12 +343,12 @@ private void testClientOperation(ClientRepresentation client, String errorPrefix if (errorPrefix == null) { if (response != null) { // create returns 201, update returns null - Assert.assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus()); + Assertions.assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus()); } } else { - Assert.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); OAuth2ErrorRepresentation error = response.readEntity(OAuth2ErrorRepresentation.class); - Assert.assertEquals(OAuthErrorException.INVALID_CLIENT_METADATA, error.getError()); + Assertions.assertEquals(OAuthErrorException.INVALID_CLIENT_METADATA, error.getError()); MatcherAssert.assertThat(error.getErrorDescription(), Matchers.startsWith(errorPrefix)); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/SecureRedirectUrisEnforcerExecutorTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/SecureRedirectUrisEnforcerExecutorTest.java index b65dbf965a5c..495e5b461879 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/SecureRedirectUrisEnforcerExecutorTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/policies/SecureRedirectUrisEnforcerExecutorTest.java @@ -35,16 +35,16 @@ import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.keycloak.testsuite.util.oauth.AuthorizationEndpointResponse; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.util.ClientPoliciesUtil.createAnyClientConditionConfig; import static org.keycloak.testsuite.util.ClientPoliciesUtil.createSecureRedirectUrisEnforcerExecutorConfig; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class SecureRedirectUrisEnforcerExecutorTest extends AbstractClientPoliciesTest { @@ -581,8 +581,8 @@ public void testSecureRedirectUrisEnforcerExecutor_postLogoutRedirectUris() thro clientRep.setPostLogoutRedirectUris(List.of("+")); }); OIDCClientRepresentation clientRepp = reg.oidc().get(clientId); - Assert.assertEquals(List.of("https://oauth.redirect/some"), clientRepp.getRedirectUris()); - Assert.assertEquals(List.of("https://oauth.redirect/some"), clientRepp.getPostLogoutRedirectUris()); + Assertions.assertEquals(List.of("https://oauth.redirect/some"), clientRepp.getRedirectUris()); + Assertions.assertEquals(List.of("https://oauth.redirect/some"), clientRepp.getPostLogoutRedirectUris()); // Fail - incorrect domain for post-logout redirect uri try { @@ -601,8 +601,8 @@ public void testSecureRedirectUrisEnforcerExecutor_postLogoutRedirectUris() thro clientRep.setPostLogoutRedirectUris(List.of("https://oauth.redirect/some-post-logout")); }); clientRepp = reg.oidc().get(clientId); - Assert.assertEquals(List.of("https://oauth.redirect/some"), clientRepp.getRedirectUris()); - Assert.assertEquals(List.of("https://oauth.redirect/some-post-logout"), clientRepp.getPostLogoutRedirectUris()); + Assertions.assertEquals(List.of("https://oauth.redirect/some"), clientRepp.getRedirectUris()); + Assertions.assertEquals(List.of("https://oauth.redirect/some-post-logout"), clientRepp.getPostLogoutRedirectUris()); } @@ -704,7 +704,7 @@ private void testSecureRedirectUrisEnforcerExecutor_successAuthorizationRequest( oauth.client(clientId, "secret"); oauth.redirectUri(redirectUri); AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response.getCode()); + Assertions.assertNotNull(response.getCode()); AccessTokenResponse res = oauth.doAccessTokenRequest(response.getCode()); assertEquals(200, res.getStatusCode()); oauth.doLogout(res.getRefreshToken()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AbstractClusterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AbstractClusterTest.java index c1bff4158a62..d9eb5f937cbb 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AbstractClusterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AbstractClusterTest.java @@ -25,7 +25,7 @@ import static org.keycloak.testsuite.auth.page.AuthRealm.MASTER; import static org.keycloak.testsuite.util.WaitUtils.pause; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AbstractFailoverClusterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AbstractFailoverClusterTest.java index 7a92b3690b80..70ad491853ed 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AbstractFailoverClusterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AbstractFailoverClusterTest.java @@ -21,7 +21,6 @@ import org.keycloak.models.UserModel; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.pages.AppPage; import org.keycloak.testsuite.pages.InfoPage; @@ -36,17 +35,18 @@ import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.Cookie; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.util.WaitUtils.pause; import static org.keycloak.testsuite.util.oauth.OAuthClient.AUTH_SERVER_ROOT; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public abstract class AbstractFailoverClusterTest extends AbstractClusterTest { @@ -147,7 +147,7 @@ protected void logout() { // Info page present infoPage.assertCurrent(); - Assert.assertEquals("You are logged out", infoPage.getInfo()); + Assertions.assertEquals("You are logged out", infoPage.getInfo()); } protected Cookie verifyLoggedIn(Cookie sessionCookieForVerification) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AbstractInvalidationClusterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AbstractInvalidationClusterTest.java index 7287623ab027..053687d86eba 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AbstractInvalidationClusterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AbstractInvalidationClusterTest.java @@ -19,7 +19,7 @@ import static org.keycloak.common.util.reflections.Reflections.setAccessible; import static org.keycloak.common.util.reflections.Reflections.unsetAccessible; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AuthenticationSessionClusterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AuthenticationSessionClusterTest.java index d0c5c7eff1cd..d9ddc6f62575 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AuthenticationSessionClusterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AuthenticationSessionClusterTest.java @@ -42,10 +42,10 @@ import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Marek Posolda diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AuthenticationSessionFailoverClusterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AuthenticationSessionFailoverClusterTest.java index 046a7086b020..36635ec30d25 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AuthenticationSessionFailoverClusterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/AuthenticationSessionFailoverClusterTest.java @@ -22,18 +22,18 @@ import jakarta.mail.MessagingException; import org.keycloak.cookie.CookieType; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.pages.LoginPasswordUpdatePage; import org.keycloak.testsuite.pages.LoginUpdateProfilePage; import org.jboss.arquillian.graphene.page.Page; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.Cookie; import org.openqa.selenium.WebDriver; import static org.keycloak.testsuite.util.WaitUtils.pause; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Marek Posolda @@ -72,7 +72,7 @@ protected void failoverTest(boolean expectSuccessfulFailover) throws IOException updateProfilePage.assertCurrent(); // Route didn't change - Assert.assertEquals(cookieValue1, getAuthSessionCookieValue(driver)); + Assertions.assertEquals(cookieValue1, getAuthSessionCookieValue(driver)); log.info("Authentication session cookie: " + cookieValue1); @@ -94,14 +94,14 @@ protected void failoverTest(boolean expectSuccessfulFailover) throws IOException log.info("Authentication session cookie after failover: " + cookieValue2); // Cookie was moved to the second node - Assert.assertEquals(cookieValue1.substring(0, 36), cookieValue2.substring(0, 36)); - Assert.assertNotEquals(cookieValue1, cookieValue2); + Assertions.assertEquals(cookieValue1.substring(0, 36), cookieValue2.substring(0, 36)); + Assertions.assertNotEquals(cookieValue1, cookieValue2); } else { loginPage.assertCurrent(); String error = loginPage.getError(); log.info("Failover not successful as expected. Error on login page: " + error); - Assert.assertNotNull(error); + Assertions.assertNotNull(error); loginPage.login("login-test", "password"); updateProfilePage.prepareUpdate().firstName("John").lastName("Doe3").email("john@doe3.com").submit(); @@ -117,7 +117,7 @@ protected void failoverTest(boolean expectSuccessfulFailover) throws IOException public static String getAuthSessionCookieValue(WebDriver driver) { Cookie authSessionCookie = driver.manage().getCookieNamed(CookieType.AUTH_SESSION_ID.getName()); - Assert.assertNotNull(authSessionCookie); + Assertions.assertNotNull(authSessionCookie); return authSessionCookie.getValue(); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/ClientInvalidationClusterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/ClientInvalidationClusterTest.java index 975806a2f12c..030729f38d00 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/ClientInvalidationClusterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/ClientInvalidationClusterTest.java @@ -12,7 +12,7 @@ import org.apache.commons.lang.RandomStringUtils; import org.junit.Before; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/ClientScopeInvalidationClusterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/ClientScopeInvalidationClusterTest.java index 78af28b60528..7d138d34779c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/ClientScopeInvalidationClusterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/ClientScopeInvalidationClusterTest.java @@ -27,7 +27,7 @@ import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.arquillian.ContainerInfo; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; public class ClientScopeInvalidationClusterTest extends AbstractInvalidationClusterTestWithTestRealm { @Override diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/ComponentInvalidationClusterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/ComponentInvalidationClusterTest.java index 589e82f01d13..fa0193438775 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/ComponentInvalidationClusterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/ComponentInvalidationClusterTest.java @@ -24,7 +24,7 @@ import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/GroupInvalidationClusterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/GroupInvalidationClusterTest.java index 7f9498311c6d..caa4125c6542 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/GroupInvalidationClusterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/GroupInvalidationClusterTest.java @@ -21,9 +21,9 @@ import static org.keycloak.testsuite.Assert.assertNames; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/JGroupsCertificateRotationClusterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/JGroupsCertificateRotationClusterTest.java index a365474d00f0..289f2d30f871 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/JGroupsCertificateRotationClusterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/JGroupsCertificateRotationClusterTest.java @@ -15,9 +15,9 @@ import org.junit.Assume; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class JGroupsCertificateRotationClusterTest extends AbstractClusterTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/PermissionTicketInvalidationClusterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/PermissionTicketInvalidationClusterTest.java index 7df4930602ce..94b51289f14c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/PermissionTicketInvalidationClusterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/PermissionTicketInvalidationClusterTest.java @@ -29,7 +29,7 @@ import org.apache.commons.lang.RandomStringUtils; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class PermissionTicketInvalidationClusterTest extends AbstractInvalidationClusterTestWithTestRealm { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/RealmInvalidationClusterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/RealmInvalidationClusterTest.java index b5743a240cdd..c8f3043e9308 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/RealmInvalidationClusterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/RealmInvalidationClusterTest.java @@ -7,8 +7,8 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.arquillian.ContainerInfo; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/RoleInvalidationClusterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/RoleInvalidationClusterTest.java index d459851fede4..0244a497cf58 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/RoleInvalidationClusterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/RoleInvalidationClusterTest.java @@ -43,8 +43,8 @@ import static org.keycloak.common.util.reflections.Reflections.setAccessible; import static org.keycloak.common.util.reflections.Reflections.unsetAccessible; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; /** * diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/SessionFailoverClusterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/SessionFailoverClusterTest.java index 4282f169d0bd..68ca5400688c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/SessionFailoverClusterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/SessionFailoverClusterTest.java @@ -6,7 +6,7 @@ import static org.keycloak.testsuite.util.WaitUtils.pause; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/UserFederationInvalidationClusterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/UserFederationInvalidationClusterTest.java index 3c6939066ef8..192f67a0bb68 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/UserFederationInvalidationClusterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/UserFederationInvalidationClusterTest.java @@ -14,7 +14,7 @@ import org.apache.commons.lang.RandomStringUtils; import org.junit.Before; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; public class UserFederationInvalidationClusterTest extends AbstractInvalidationClusterTestWithTestRealm { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/UserInvalidationClusterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/UserInvalidationClusterTest.java index 11d77b3ae3eb..201b982cfa19 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/UserInvalidationClusterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cluster/UserInvalidationClusterTest.java @@ -11,7 +11,7 @@ import org.apache.commons.lang.RandomStringUtils; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/composites/CompositeImportRoleTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/composites/CompositeImportRoleTest.java index bda767830e75..a9f698f510a5 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/composites/CompositeImportRoleTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/composites/CompositeImportRoleTest.java @@ -24,8 +24,8 @@ import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; @@ -54,18 +54,18 @@ public void testAppCompositeUser() throws Exception { String code = oauth.parseLoginResponse().getCode(); AccessTokenResponse response = oauth.doAccessTokenRequest(code); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); - Assert.assertEquals("Bearer", response.getTokenType()); + Assertions.assertEquals("Bearer", response.getTokenType()); AccessToken token = oauth.verifyToken(response.getAccessToken()); - Assert.assertEquals(getUserId("APP_COMPOSITE_USER"), token.getSubject()); + Assertions.assertEquals(getUserId("APP_COMPOSITE_USER"), token.getSubject()); - Assert.assertEquals(1, token.getResourceAccess("APP_ROLE_APPLICATION").getRoles().size()); - Assert.assertEquals(1, token.getRealmAccess().getRoles().size()); - Assert.assertTrue(token.getResourceAccess("APP_ROLE_APPLICATION").isUserInRole("APP_ROLE_1")); - Assert.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1")); + Assertions.assertEquals(1, token.getResourceAccess("APP_ROLE_APPLICATION").getRoles().size()); + Assertions.assertEquals(1, token.getRealmAccess().getRoles().size()); + Assertions.assertTrue(token.getResourceAccess("APP_ROLE_APPLICATION").isUserInRole("APP_ROLE_1")); + Assertions.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1")); } @@ -78,16 +78,16 @@ public void testRealmAppCompositeUser() throws Exception { String code = oauth.parseLoginResponse().getCode(); AccessTokenResponse response = oauth.doAccessTokenRequest(code); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); - Assert.assertEquals("Bearer", response.getTokenType()); + Assertions.assertEquals("Bearer", response.getTokenType()); AccessToken token = oauth.verifyToken(response.getAccessToken()); - Assert.assertEquals(getUserId("REALM_APP_COMPOSITE_USER"), token.getSubject()); + Assertions.assertEquals(getUserId("REALM_APP_COMPOSITE_USER"), token.getSubject()); - Assert.assertEquals(1, token.getResourceAccess("APP_ROLE_APPLICATION").getRoles().size()); - Assert.assertTrue(token.getResourceAccess("APP_ROLE_APPLICATION").isUserInRole("APP_ROLE_1")); + Assertions.assertEquals(1, token.getResourceAccess("APP_ROLE_APPLICATION").getRoles().size()); + Assertions.assertTrue(token.getResourceAccess("APP_ROLE_APPLICATION").isUserInRole("APP_ROLE_1")); } @@ -101,17 +101,17 @@ public void testRealmOnlyWithUserCompositeAppComposite() throws Exception { String code = oauth.parseLoginResponse().getCode(); AccessTokenResponse response = oauth.doAccessTokenRequest(code); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); - Assert.assertEquals("Bearer", response.getTokenType()); + Assertions.assertEquals("Bearer", response.getTokenType()); AccessToken token = oauth.verifyToken(response.getAccessToken()); - Assert.assertEquals(getUserId("REALM_COMPOSITE_1_USER"), token.getSubject()); + Assertions.assertEquals(getUserId("REALM_COMPOSITE_1_USER"), token.getSubject()); - Assert.assertEquals(2, token.getRealmAccess().getRoles().size()); - Assert.assertTrue(token.getRealmAccess().isUserInRole("REALM_COMPOSITE_1")); - Assert.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1")); + Assertions.assertEquals(2, token.getRealmAccess().getRoles().size()); + Assertions.assertTrue(token.getRealmAccess().isUserInRole("REALM_COMPOSITE_1")); + Assertions.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1")); } @Test @@ -123,16 +123,16 @@ public void testRealmOnlyWithUserCompositeAppRole() throws Exception { String code = oauth.parseLoginResponse().getCode(); AccessTokenResponse response = oauth.doAccessTokenRequest(code); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); - Assert.assertEquals("Bearer", response.getTokenType()); + Assertions.assertEquals("Bearer", response.getTokenType()); AccessToken token = oauth.verifyToken(response.getAccessToken()); - Assert.assertEquals(getUserId("REALM_COMPOSITE_1_USER"), token.getSubject()); + Assertions.assertEquals(getUserId("REALM_COMPOSITE_1_USER"), token.getSubject()); - Assert.assertEquals(1, token.getRealmAccess().getRoles().size()); - Assert.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1")); + Assertions.assertEquals(1, token.getRealmAccess().getRoles().size()); + Assertions.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1")); } @Test @@ -144,16 +144,16 @@ public void testRealmOnlyWithUserRoleAppComposite() throws Exception { String code = oauth.parseLoginResponse().getCode(); AccessTokenResponse response = oauth.doAccessTokenRequest(code); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); - Assert.assertEquals("Bearer", response.getTokenType()); + Assertions.assertEquals("Bearer", response.getTokenType()); AccessToken token = oauth.verifyToken(response.getAccessToken()); - Assert.assertEquals(getUserId("REALM_ROLE_1_USER"), token.getSubject()); + Assertions.assertEquals(getUserId("REALM_ROLE_1_USER"), token.getSubject()); - Assert.assertEquals(1, token.getRealmAccess().getRoles().size()); - Assert.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1")); + Assertions.assertEquals(1, token.getRealmAccess().getRoles().size()); + Assertions.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1")); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/composites/CompositeRoleTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/composites/CompositeRoleTest.java index 717049959b80..cae19ee415a6 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/composites/CompositeRoleTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/composites/CompositeRoleTest.java @@ -40,6 +40,7 @@ import org.jboss.arquillian.graphene.page.Page; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @author Stian Thorgersen @@ -227,21 +228,21 @@ public void testAppCompositeUser() throws Exception { String code = oauth.parseLoginResponse().getCode(); AccessTokenResponse response = oauth.doAccessTokenRequest(code); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); - Assert.assertEquals("Bearer", response.getTokenType()); + Assertions.assertEquals("Bearer", response.getTokenType()); AccessToken token = oauth.verifyToken(response.getAccessToken()); - Assert.assertEquals(getUserId("APP_COMPOSITE_USER"), token.getSubject()); + Assertions.assertEquals(getUserId("APP_COMPOSITE_USER"), token.getSubject()); - Assert.assertEquals(1, token.getResourceAccess("APP_ROLE_APPLICATION").getRoles().size()); - Assert.assertEquals(1, token.getRealmAccess().getRoles().size()); - Assert.assertTrue(token.getResourceAccess("APP_ROLE_APPLICATION").isUserInRole("APP_ROLE_1")); - Assert.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1")); + Assertions.assertEquals(1, token.getResourceAccess("APP_ROLE_APPLICATION").getRoles().size()); + Assertions.assertEquals(1, token.getRealmAccess().getRoles().size()); + Assertions.assertTrue(token.getResourceAccess("APP_ROLE_APPLICATION").isUserInRole("APP_ROLE_1")); + Assertions.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1")); AccessTokenResponse refreshResponse = oauth.doRefreshTokenRequest(response.getRefreshToken()); - Assert.assertEquals(200, refreshResponse.getStatusCode()); + Assertions.assertEquals(200, refreshResponse.getStatusCode()); } @@ -254,19 +255,19 @@ public void testRealmAppCompositeUser() throws Exception { String code = oauth.parseLoginResponse().getCode(); AccessTokenResponse response = oauth.doAccessTokenRequest(code); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); - Assert.assertEquals("Bearer", response.getTokenType()); + Assertions.assertEquals("Bearer", response.getTokenType()); AccessToken token = oauth.verifyToken(response.getAccessToken()); - Assert.assertEquals(getUserId("REALM_APP_COMPOSITE_USER"), token.getSubject()); + Assertions.assertEquals(getUserId("REALM_APP_COMPOSITE_USER"), token.getSubject()); - Assert.assertEquals(1, token.getResourceAccess("APP_ROLE_APPLICATION").getRoles().size()); - Assert.assertTrue(token.getResourceAccess("APP_ROLE_APPLICATION").isUserInRole("APP_ROLE_1")); + Assertions.assertEquals(1, token.getResourceAccess("APP_ROLE_APPLICATION").getRoles().size()); + Assertions.assertTrue(token.getResourceAccess("APP_ROLE_APPLICATION").isUserInRole("APP_ROLE_1")); AccessTokenResponse refreshResponse = oauth.doRefreshTokenRequest(response.getRefreshToken()); - Assert.assertEquals(200, refreshResponse.getStatusCode()); + Assertions.assertEquals(200, refreshResponse.getStatusCode()); } @Test @@ -278,20 +279,20 @@ public void testRealmOnlyWithUserCompositeAppComposite() throws Exception { String code = oauth.parseLoginResponse().getCode(); AccessTokenResponse response = oauth.doAccessTokenRequest(code); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); - Assert.assertEquals("Bearer", response.getTokenType()); + Assertions.assertEquals("Bearer", response.getTokenType()); AccessToken token = oauth.verifyToken(response.getAccessToken()); - Assert.assertEquals(getUserId("REALM_COMPOSITE_1_USER"), token.getSubject()); + Assertions.assertEquals(getUserId("REALM_COMPOSITE_1_USER"), token.getSubject()); - Assert.assertEquals(2, token.getRealmAccess().getRoles().size()); - Assert.assertTrue(token.getRealmAccess().isUserInRole("REALM_COMPOSITE_1")); - Assert.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1")); + Assertions.assertEquals(2, token.getRealmAccess().getRoles().size()); + Assertions.assertTrue(token.getRealmAccess().isUserInRole("REALM_COMPOSITE_1")); + Assertions.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1")); AccessTokenResponse refreshResponse = oauth.doRefreshTokenRequest(response.getRefreshToken()); - Assert.assertEquals(200, refreshResponse.getStatusCode()); + Assertions.assertEquals(200, refreshResponse.getStatusCode()); } @Test @@ -303,19 +304,19 @@ public void testRealmOnlyWithUserCompositeAppRole() throws Exception { String code = oauth.parseLoginResponse().getCode(); AccessTokenResponse response = oauth.doAccessTokenRequest(code); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); - Assert.assertEquals("Bearer", response.getTokenType()); + Assertions.assertEquals("Bearer", response.getTokenType()); AccessToken token = oauth.verifyToken(response.getAccessToken()); - Assert.assertEquals(getUserId("REALM_COMPOSITE_1_USER"), token.getSubject()); + Assertions.assertEquals(getUserId("REALM_COMPOSITE_1_USER"), token.getSubject()); - Assert.assertEquals(1, token.getRealmAccess().getRoles().size()); - Assert.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1")); + Assertions.assertEquals(1, token.getRealmAccess().getRoles().size()); + Assertions.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1")); AccessTokenResponse refreshResponse = oauth.doRefreshTokenRequest(response.getRefreshToken()); - Assert.assertEquals(200, refreshResponse.getStatusCode()); + Assertions.assertEquals(200, refreshResponse.getStatusCode()); } @Test @@ -327,19 +328,19 @@ public void testRealmOnlyWithUserRoleAppComposite() throws Exception { String code = oauth.parseLoginResponse().getCode(); AccessTokenResponse response = oauth.doAccessTokenRequest(code); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); - Assert.assertEquals("Bearer", response.getTokenType()); + Assertions.assertEquals("Bearer", response.getTokenType()); AccessToken token = oauth.verifyToken(response.getAccessToken()); - Assert.assertEquals(getUserId("REALM_ROLE_1_USER"), token.getSubject()); + Assertions.assertEquals(getUserId("REALM_ROLE_1_USER"), token.getSubject()); - Assert.assertEquals(1, token.getRealmAccess().getRoles().size()); - Assert.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1")); + Assertions.assertEquals(1, token.getRealmAccess().getRoles().size()); + Assertions.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1")); AccessTokenResponse refreshResponse = oauth.doRefreshTokenRequest(response.getRefreshToken()); - Assert.assertEquals(200, refreshResponse.getStatusCode()); + Assertions.assertEquals(200, refreshResponse.getStatusCode()); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/CookieTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/CookieTest.java index e10f6f50034c..4f34cd61bdc6 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/CookieTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/CookieTest.java @@ -59,8 +59,8 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @@ -201,7 +201,7 @@ public void testNoDuplicationsWhenExpiringCookies() throws IOException { Set cookies = new HashSet<>(); for (Header header : headers) { - assertTrue("Cookie '" + header.getValue() + "' is duplicated", cookies.add(header.getValue())); + assertTrue(cookies.add(header.getValue()), "Cookie '" + header.getValue() + "' is duplicated"); } assertFalse(cookies.isEmpty()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/DefaultCookieProviderTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/DefaultCookieProviderTest.java index 200169ed22c8..167fa3be7c5b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/DefaultCookieProviderTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cookies/DefaultCookieProviderTest.java @@ -19,9 +19,9 @@ import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; public class DefaultCookieProviderTest extends AbstractKeycloakTest { @@ -55,7 +55,7 @@ public void testCookieDefaults() { cookies.set(CookieType.SESSION, "my-session", 444); cookies.set(CookieType.WELCOME_CSRF, "my-welcome-csrf"); }); - Assert.assertEquals(9, response.getCookies().size()); + Assertions.assertEquals(9, response.getCookies().size()); assertCookie(response, "AUTH_SESSION_ID", "my-auth-session-id", "/auth/realms/master/", -1, true, true, "None", true); assertCookie(response, "KC_AUTH_SESSION_HASH", "my-kc-auth-session", "/auth/realms/master/", 60, true, false, "None", true); assertCookie(response, "KC_RESTART", "my-auth-restart", "/auth/realms/master/", -1, true, true, "None", false); @@ -83,7 +83,7 @@ public void testCookieDefaultsWithInsecureContext() { cookies.set(CookieType.SESSION, "my-session", 444); cookies.set(CookieType.WELCOME_CSRF, "my-welcome-csrf"); }); - Assert.assertEquals(9, response.getCookies().size()); + Assertions.assertEquals(9, response.getCookies().size()); assertCookie(response, "AUTH_SESSION_ID", "my-auth-session-id", "/auth/realms/master/", -1, false, true, "Lax", true); assertCookie(response, "KC_AUTH_SESSION_HASH", "my-kc-auth-session", "/auth/realms/master/", 60, false, false, "Lax", true); assertCookie(response, "KC_RESTART", "my-auth-restart", "/auth/realms/master/", -1, false, true, "Lax", false); @@ -105,11 +105,11 @@ public void testSessionCookieValue() { }); // Cookie values from response.getCookies() removes quotes - Assert.assertEquals(sessionValue, response.getCookies().get(CookieType.SESSION.getName()).getValue()); + Assertions.assertEquals(sessionValue, response.getCookies().get(CookieType.SESSION.getName()).getValue()); // Cookie values from the Set-Cookie header includes quotes String setHeader = getSetHeader(response, CookieType.SESSION.getName()); - Assert.assertTrue(setHeader.startsWith(CookieType.SESSION.getName() + "=\"" + sessionValue + "\";")); + Assertions.assertTrue(setHeader.startsWith(CookieType.SESSION.getName() + "=\"" + sessionValue + "\";")); // Send Cookie header with quoted value for cookie filter.setHeader("Cookie", "KEYCLOAK_SESSION=\"" + sessionValue + "\";"); @@ -117,7 +117,7 @@ public void testSessionCookieValue() { // Check cookie value matches original value without quotes testing.server().run(session -> { String cookieValue = session.getProvider(CookieProvider.class).get(CookieType.SESSION); - Assert.assertEquals(sessionValue, cookieValue); + Assertions.assertEquals(sessionValue, cookieValue); }); } @@ -131,7 +131,7 @@ public void testExpire() { }); Map cookies = response.getCookies(); - Assert.assertEquals(1, cookies.size()); + Assertions.assertEquals(1, cookies.size()); assertCookie(response, "AUTH_SESSION_ID", "", "/auth/realms/master/", 0, false, false, null, false); } @@ -141,7 +141,7 @@ public void testCookieHeaderWithSpaces() { testing.server().run(session -> { String authSessionId = session.getProvider(CookieProvider.class).get(CookieType.AUTH_SESSION_ID); - Assert.assertEquals("55000981-8b5e-4c8d-853f-ee4c582c1d0d4", authSessionId); + Assertions.assertEquals("55000981-8b5e-4c8d-853f-ee4c582c1d0d4", authSessionId); }); } @@ -150,13 +150,13 @@ public void testExpireOldUnused() { filter.setHeader("Cookie", "AUTH_SESSION_ID_LEGACY=legacy; KEYCLOAK_IDENTITY_LEGACY=legacy; KEYCLOAK_SESSION_LEGACY=ignore"); Response response = testing.server().runWithResponse(session -> { - Assert.assertNull(session.getProvider(CookieProvider.class).get(CookieType.AUTH_SESSION_ID)); - Assert.assertNull(session.getProvider(CookieProvider.class).get(CookieType.IDENTITY)); - Assert.assertNull(session.getProvider(CookieProvider.class).get(CookieType.SESSION)); + Assertions.assertNull(session.getProvider(CookieProvider.class).get(CookieType.AUTH_SESSION_ID)); + Assertions.assertNull(session.getProvider(CookieProvider.class).get(CookieType.IDENTITY)); + Assertions.assertNull(session.getProvider(CookieProvider.class).get(CookieType.SESSION)); }); Map cookies = response.getCookies(); - Assert.assertEquals(3, cookies.size()); + Assertions.assertEquals(3, cookies.size()); assertCookie(response, "AUTH_SESSION_ID_LEGACY", "", "/auth/realms/master/", 0, false, false, null, false); assertCookie(response, "KEYCLOAK_IDENTITY_LEGACY", "", "/auth/realms/master/", 0, false, false, null, false); assertCookie(response, "KEYCLOAK_SESSION_LEGACY", "", "/auth/realms/master/", 0, false, false, null, false); @@ -174,7 +174,7 @@ public void testCustomCookie() { }); Map cookies = response.getCookies(); - Assert.assertEquals(1, cookies.size()); + Assertions.assertEquals(1, cookies.size()); assertCookie(response, "mycookie", "myvalue", "/auth/realms/master/testing/run-on-server", 1232, false, false, null, false); } @@ -200,7 +200,7 @@ public void testSafariQuirks() { }); } - Assert.assertEquals(9, response.getCookies().size()); + Assertions.assertEquals(9, response.getCookies().size()); assertCookie(response, "AUTH_SESSION_ID", "my-auth-session-id", "/auth/realms/master/", -1, false, true, "Lax", true); assertCookie(response, "KC_AUTH_SESSION_HASH", "my-kc-auth-session", "/auth/realms/master/", 60, false, false, "Lax", true); assertCookie(response, "KC_RESTART", "my-auth-restart", "/auth/realms/master/", -1, false, true, "Lax", false); @@ -215,22 +215,22 @@ public void testSafariQuirks() { private void assertCookie(Response response, String name, String value, String path, int maxAge, boolean secure, boolean httpOnly, String sameSite, boolean verifyLegacyNotSent) { Map cookies = response.getCookies(); NewCookie cookie = cookies.get(name); - Assert.assertNotNull(cookie); - Assert.assertEquals(value, cookie.getValue()); - Assert.assertEquals(path, cookie.getPath()); - Assert.assertEquals(maxAge, cookie.getMaxAge()); - Assert.assertEquals(secure, cookie.isSecure()); - Assert.assertEquals(httpOnly, cookie.isHttpOnly()); + Assertions.assertNotNull(cookie); + Assertions.assertEquals(value, cookie.getValue()); + Assertions.assertEquals(path, cookie.getPath()); + Assertions.assertEquals(maxAge, cookie.getMaxAge()); + Assertions.assertEquals(secure, cookie.isSecure()); + Assertions.assertEquals(httpOnly, cookie.isHttpOnly()); String setHeader = getSetHeader(response, name); if (sameSite == null) { - Assert.assertFalse(setHeader.contains("SameSite")); + Assertions.assertFalse(setHeader.contains("SameSite")); } else { - Assert.assertTrue("Expected SameSite=" + sameSite + ", header was: " + setHeader, setHeader.contains("SameSite=" + sameSite)); + Assertions.assertTrue(setHeader.contains("SameSite=" + sameSite), "Expected SameSite=" + sameSite + ", header was: " + setHeader); } if (verifyLegacyNotSent) { - Assert.assertNull(response.getCookies().get(name + "_LEGACY")); + Assertions.assertNull(response.getCookies().get(name + "_LEGACY")); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/docker/DockerClientTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/docker/DockerClientTest.java index 4800174fde6c..e84a459db826 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/docker/DockerClientTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/docker/DockerClientTest.java @@ -27,10 +27,10 @@ import org.keycloak.testsuite.arquillian.annotation.EnableFeature; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.slf4j.LoggerFactory; import org.testcontainers.containers.BindMode; import org.testcontainers.containers.Container; @@ -80,7 +80,7 @@ public static void verifyEnvironment() { hostIp = foundHostIp.get(); } } - Assert.assertNotNull("Could not resolve host machine's IP address for docker adapter, and 'host.ip' system poperty not set. Client will not be able to authenticate against the keycloak server!", hostIp); + Assertions.assertNotNull(hostIp, "Could not resolve host machine's IP address for docker adapter, and 'host.ip' system poperty not set. Client will not be able to authenticate against the keycloak server!"); } @Override diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/domainextension/CustomExtensionTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/domainextension/CustomExtensionTest.java index ff0727ef5be8..c007a51c7149 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/domainextension/CustomExtensionTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/domainextension/CustomExtensionTest.java @@ -23,11 +23,11 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.AbstractKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.client.resources.TestExampleCompanyResource; import org.keycloak.testsuite.util.RealmBuilder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @author Marek Posolda @@ -76,9 +76,9 @@ private void assertCompanyNames(List companies, String... names.add(comp.getName()); } - Assert.assertEquals(expectedNames.length, names.size()); + Assertions.assertEquals(expectedNames.length, names.size()); for (String expectedName : expectedNames) { - Assert.assertTrue(names.contains(expectedName)); + Assertions.assertTrue(names.contains(expectedName)); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/error/UncaughtErrorPageTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/error/UncaughtErrorPageTest.java index ca0ff8a752aa..153d5756bbe1 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/error/UncaughtErrorPageTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/error/UncaughtErrorPageTest.java @@ -37,8 +37,8 @@ import org.apache.http.util.EntityUtils; import org.hamcrest.CoreMatchers; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import static org.keycloak.utils.MediaType.APPLICATION_JSON; @@ -46,10 +46,10 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public class UncaughtErrorPageTest extends AbstractKeycloakTest { @@ -84,7 +84,7 @@ public void uncaughtErrorJson() throws IOException { InputStream is = (InputStream) response.getEntity(); String responseString = StreamUtil.readString(is, StandardCharsets.UTF_8); - Assert.assertTrue(responseString.contains("An internal server error has occurred")); + Assertions.assertTrue(responseString.contains("An internal server error has occurred")); } @Test @@ -100,7 +100,7 @@ public void uncaughtErrorClientRegistration() throws IOException { OAuth2ErrorRepresentation error = JsonSerialization.readValue(response.getEntity().getContent(), OAuth2ErrorRepresentation.class); assertEquals(OAuthErrorException.INVALID_REQUEST, error.getError()); - assertNotNull("found error with " + error.getError() + "/" + error.getErrorDescription(), error.getErrorDescription()); + assertNotNull(error.getErrorDescription(), "found error with " + error.getError() + "/" + error.getErrorDescription()); } } } @@ -121,7 +121,7 @@ public void uncaughtErrorAdmin() throws IOException { OAuth2ErrorRepresentation error = JsonSerialization.readValue(response.getEntity().getContent(), OAuth2ErrorRepresentation.class); assertEquals(OAuthErrorException.INVALID_REQUEST, error.getError()); - assertNotNull("found error with " + error.getError() + "/" + error.getErrorDescription(), error.getErrorDescription()); + assertNotNull(error.getErrorDescription(), "found error with " + error.getError() + "/" + error.getErrorDescription()); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/exportimport/ExportImportTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/exportimport/ExportImportTest.java index 462b75bfcd54..644fabc68d3a 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/exportimport/ExportImportTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/exportimport/ExportImportTest.java @@ -68,6 +68,7 @@ import org.jboss.arquillian.container.spi.client.container.LifecycleException; import org.junit.After; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; @@ -76,9 +77,9 @@ import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @@ -145,10 +146,10 @@ private void setEventsConfig(RealmRepresentation realm) { } private void checkEventsConfig(RealmEventsConfigRepresentation config) { - Assert.assertTrue(config.isEventsEnabled()); - Assert.assertTrue(config.isAdminEventsEnabled()); - Assert.assertTrue(config.isAdminEventsDetailsEnabled()); - Assert.assertEquals((Long) 600L, config.getEventsExpiration()); + Assertions.assertTrue(config.isEventsEnabled()); + Assertions.assertTrue(config.isAdminEventsEnabled()); + Assertions.assertTrue(config.isAdminEventsDetailsEnabled()); + Assertions.assertEquals((Long) 600L, config.getEventsExpiration()); Assert.assertNames(new HashSet<>(config.getEnabledEventTypes()),"REGISTER", "REGISTER_ERROR", "LOGIN", "LOGIN_ERROR", "LOGOUT_ERROR"); } @@ -223,7 +224,7 @@ public void testSingleFileFullExportImport() throws Throwable { } private static void assertExportContainsGoogleClientSecret(String targetFilePath) throws IOException { - assertTrue("Expected an export file to exist", new File(targetFilePath).exists()); + assertTrue(new File(targetFilePath).exists(), "Expected an export file to exist"); Map realms; try (FileInputStream fis = new FileInputStream(targetFilePath)) { @@ -268,17 +269,17 @@ public void testSingleFileRealmWithoutBuiltinsImport() throws Throwable { public void testImportFromPartialExport() { // import a realm with clients without roles importRealmFromFile("/import/partial-import.json"); - Assert.assertTrue("Imported realm hasn't been found!", isRealmPresent("partial-import")); + Assertions.assertTrue(isRealmPresent("partial-import"), "Imported realm hasn't been found!"); addTestRealmToTestRealmReps("partial-import"); // import a realm with clients without roles importRealmFromFile("/import/import-without-roles.json"); - Assert.assertTrue("Imported realm hasn't been found!", isRealmPresent("import-without-roles")); + Assertions.assertTrue(isRealmPresent("import-without-roles"), "Imported realm hasn't been found!"); addTestRealmToTestRealmReps("import-without-roles"); // import a realm with roles without clients importRealmFromFile("/import/import-without-clients.json"); - Assert.assertTrue("Imported realm hasn't been found!", isRealmPresent("import-without-clients")); + Assertions.assertTrue(isRealmPresent("import-without-clients"), "Imported realm hasn't been found!"); addTestRealmToTestRealmReps("import-without-clients"); } @@ -286,13 +287,13 @@ public void testImportFromPartialExport() { public void testImportFromRealmWithPartialAuthenticationFlows() { // import a realm with no built-in authentication flows importRealmFromFile("/import/partial-authentication-flows-import.json"); - Assert.assertTrue("Imported realm hasn't been found!", isRealmPresent("partial-authentication-flows-import")); + Assertions.assertTrue(isRealmPresent("partial-authentication-flows-import"), "Imported realm hasn't been found!"); } @Test public void testImportWithNullAuthenticatorConfigAndNoDefaultBrowserFlow() { importRealmFromFile("/import/testrealm-authenticator-config-null.json"); - Assert.assertTrue("Imported realm hasn't been found!", isRealmPresent("cez")); + Assertions.assertTrue(isRealmPresent("cez"), "Imported realm hasn't been found!"); } @Test @@ -341,8 +342,8 @@ public void testRealmImportWithOID4VCICredentialOfferCreateRole() throws Throwab // Verify the role exists after creation RealmResource realmResource = adminClient.realm(testRealmName); RoleRepresentation credentialOfferCreateRole = realmResource.roles().get(OID4VCIConstants.CREDENTIAL_OFFER_CREATE.getName()).toRepresentation(); - assertNotNull("credential-offer-create role should exist after realm creation", credentialOfferCreateRole); - assertEquals("Role name should match", OID4VCIConstants.CREDENTIAL_OFFER_CREATE.getName(), credentialOfferCreateRole.getName()); + assertNotNull(credentialOfferCreateRole, "credential-offer-create role should exist after realm creation"); + assertEquals(OID4VCIConstants.CREDENTIAL_OFFER_CREATE.getName(), credentialOfferCreateRole.getName(), "Role name should match"); // Export the realm TestingExportImportResource exportImport = testingClient.testing().exportImport(); @@ -359,12 +360,12 @@ public void testRealmImportWithOID4VCICredentialOfferCreateRole() throws Throwab exportedRealms = ImportUtils.getRealmsFromStream(JsonSerialization.mapper, fis); } RealmRepresentation exportedRealm = exportedRealms.get(testRealmName); - assertNotNull("Exported realm should exist", exportedRealm); - assertTrue("Exported realm should contain credential-offer-create role", - exportedRealm.getRoles() != null && + assertNotNull(exportedRealm, "Exported realm should exist"); + assertTrue(exportedRealm.getRoles() != null && exportedRealm.getRoles().getRealm() != null && exportedRealm.getRoles().getRealm().stream() - .anyMatch(role -> OID4VCIConstants.CREDENTIAL_OFFER_CREATE.getName().equals(role.getName()))); + .anyMatch(role -> OID4VCIConstants.CREDENTIAL_OFFER_CREATE.getName().equals(role.getName())), + "Exported realm should contain credential-offer-create role"); // Remove the realm removeRealm(testRealmName); @@ -375,12 +376,12 @@ public void testRealmImportWithOID4VCICredentialOfferCreateRole() throws Throwab // Verify the realm was imported successfully RealmResource importedRealmResource = adminClient.realm(testRealmName); - assertNotNull("Imported realm should exist", importedRealmResource); + assertNotNull(importedRealmResource, "Imported realm should exist"); // Verify the role still exists after import RoleRepresentation importedRole = importedRealmResource.roles().get(OID4VCIConstants.CREDENTIAL_OFFER_CREATE.getName()).toRepresentation(); - assertNotNull("credential-offer-create role should exist after import", importedRole); - assertEquals("Role name should match", OID4VCIConstants.CREDENTIAL_OFFER_CREATE.getName(), importedRole.getName()); + assertNotNull(importedRole, "credential-offer-create role should exist after import"); + assertEquals(OID4VCIConstants.CREDENTIAL_OFFER_CREATE.getName(), importedRole.getName(), "Role name should match"); // Cleanup removeRealm(testRealmName); @@ -411,7 +412,7 @@ public void testImportIgnoreExistingMissingClientId() { FileUtils.copyFile(testRealm, newFile); FileUtils.copyFileToDirectory(newFile, dest); } catch (IOException e) { - Assert.fail("Cannot copy file. Details: " + e.getMessage()); + Assertions.fail("Cannot copy file. Details: " + e.getMessage()); } File existingFile = FileUtils.getFile(dest, newFile.getName()); @@ -424,7 +425,7 @@ public void testImportIgnoreExistingMissingClientId() { resource.runImport(); resource.runImport(); } catch (Exception e) { - Assert.fail("Error with realm importing twice. Details: " + e.getMessage()); + Assertions.fail("Error with realm importing twice. Details: " + e.getMessage()); } } finally { DirExportProvider.recursiveDeleteDir(dest); @@ -456,7 +457,7 @@ public void testImportNameMismatch() { FileUtils.copyFile(testRealm, newFile); FileUtils.copyFileToDirectory(newFile, dest); } catch (IOException e) { - Assert.fail("Cannot copy file. Details: " + e.getMessage()); + Assertions.fail("Cannot copy file. Details: " + e.getMessage()); } File existingFile = FileUtils.getFile(dest, newFile.getName()); @@ -597,7 +598,7 @@ private void testRealmExportImport() throws LifecycleException { String[] authFlowObjectIdsAfterImport = getSomeAuthenticationFlowsObjectIds(); // Test that IDs of authentication-flows (both top level and nested) and authenticationConfiguration was preserved - Assert.assertArrayEquals(authFlowObjectIdsBeforeImport, authFlowObjectIdsAfterImport); + Assertions.assertArrayEquals(authFlowObjectIdsBeforeImport, authFlowObjectIdsAfterImport); List componentsImported = adminClient.realm("test").components().query(); assertComponents(components, componentsImported); @@ -666,13 +667,13 @@ private String[] getSomeAuthenticationFlowsObjectIds() { .findFirst().get().getId(); List authExecutions = adminClient.realm("test").flows().getExecutions("User creation or linking"); - Assert.assertEquals("idp-create-user-if-unique", authExecutions.get(0).getProviderId()); + Assertions.assertEquals("idp-create-user-if-unique", authExecutions.get(0).getProviderId()); String authConfigId = authExecutions.get(0).getAuthenticationConfig(); - Assert.assertEquals("create unique user config", adminClient.realm("test").flows().getAuthenticatorConfig(authConfigId).getAlias()); + Assertions.assertEquals("create unique user config", adminClient.realm("test").flows().getAuthenticatorConfig(authConfigId).getAlias()); String handleExistingAccountSubflowId = authExecutions.get(1).getFlowId(); - Assert.assertEquals("Handle Existing Account", adminClient.realm("test").flows().getFlow(handleExistingAccountSubflowId).getAlias()); + Assertions.assertEquals("Handle Existing Account", adminClient.realm("test").flows().getFlow(handleExistingAccountSubflowId).getAlias()); return new String[] {firstBrokerLoginFlowID, handleExistingAccountSubflowId, authConfigId }; } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/exportimport/ExportImportUtil.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/exportimport/ExportImportUtil.java index 8d62c5abb57d..6f455192715a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/exportimport/ExportImportUtil.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/exportimport/ExportImportUtil.java @@ -81,7 +81,7 @@ import org.hamcrest.Matcher; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import static org.hamcrest.MatcherAssert.assertThat; @@ -94,18 +94,18 @@ public class ExportImportUtil { // In the old testsuite, this method exists as a public method of ImportTest from the model package. // However, model package is not ready to be migrated yet. public static void assertDataImportedInRealm(Keycloak adminClient, KeycloakTestingClient testingClient, RealmRepresentation realm) throws IOException { - Assert.assertTrue(realm.isVerifyEmail()); - Assert.assertEquals((Integer)3600000, realm.getOfflineSessionIdleTimeout()); - Assert.assertEquals((Integer)1500, realm.getAccessTokenLifespanForImplicitFlow()); - Assert.assertEquals((Integer)1800, realm.getSsoSessionIdleTimeout()); - Assert.assertEquals((Integer)36000, realm.getSsoSessionMaxLifespan()); - Assert.assertEquals((Integer)3600, realm.getSsoSessionIdleTimeoutRememberMe()); - Assert.assertEquals((Integer)172800, realm.getSsoSessionMaxLifespanRememberMe()); + Assertions.assertTrue(realm.isVerifyEmail()); + Assertions.assertEquals((Integer)3600000, realm.getOfflineSessionIdleTimeout()); + Assertions.assertEquals((Integer)1500, realm.getAccessTokenLifespanForImplicitFlow()); + Assertions.assertEquals((Integer)1800, realm.getSsoSessionIdleTimeout()); + Assertions.assertEquals((Integer)36000, realm.getSsoSessionMaxLifespan()); + Assertions.assertEquals((Integer)3600, realm.getSsoSessionIdleTimeoutRememberMe()); + Assertions.assertEquals((Integer)172800, realm.getSsoSessionMaxLifespanRememberMe()); Set creds = realm.getRequiredCredentials(); - Assert.assertEquals(1, creds.size()); + Assertions.assertEquals(1, creds.size()); String cred = (String)creds.iterator().next(); - Assert.assertEquals("password", cred); + Assertions.assertEquals("password", cred); RealmResource realmRsc = adminClient.realm(realm.getRealm()); @@ -114,13 +114,13 @@ public static void assertDataImportedInRealm(Keycloak adminClient, KeycloakTesti realmRsc.users().userProfile().update(upConfig); UserRepresentation user = findByUsername(realmRsc, "loginclient"); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); UserResource userRsc = realmRsc.users().get(user.getId()); - Assert.assertEquals(0, userRsc.getFederatedIdentity().size()); + Assertions.assertEquals(0, userRsc.getFederatedIdentity().size()); List resources = realmRsc.clients().findAll(); - Assert.assertEquals(10, resources.size()); + Assertions.assertEquals(10, resources.size()); // Test applications imported ClientRepresentation application = AdminApiUtil.findClientByClientId(realmRsc, "Application").toRepresentation(); @@ -128,122 +128,122 @@ public static void assertDataImportedInRealm(Keycloak adminClient, KeycloakTesti ClientRepresentation accountApp = AdminApiUtil.findClientByClientId(realmRsc, Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).toRepresentation(); ClientRepresentation testAppAuthzApp = AdminApiUtil.findClientByClientId(realmRsc, "test-app-authz").toRepresentation(); ClientResource nonExisting = AdminApiUtil.findClientByClientId(realmRsc, "NonExisting"); - Assert.assertNotNull(application); - Assert.assertNotNull(otherApp); - Assert.assertNull(nonExisting); + Assertions.assertNotNull(application); + Assertions.assertNotNull(otherApp); + Assertions.assertNull(nonExisting); List clients = realmRsc.clients().findAll(); - Assert.assertEquals(10, clients.size()); - Assert.assertTrue(hasClient(clients, application)); - Assert.assertTrue(hasClient(clients, otherApp)); - Assert.assertTrue(hasClient(clients, accountApp)); + Assertions.assertEquals(10, clients.size()); + Assertions.assertTrue(hasClient(clients, application)); + Assertions.assertTrue(hasClient(clients, otherApp)); + Assertions.assertTrue(hasClient(clients, accountApp)); - Assert.assertEquals("Applicationn", application.getName()); - Assert.assertEquals((Integer)50, application.getNodeReRegistrationTimeout()); + Assertions.assertEquals("Applicationn", application.getName()); + Assertions.assertEquals((Integer)50, application.getNodeReRegistrationTimeout()); Map appRegisteredNodes = application.getRegisteredNodes(); - Assert.assertEquals(2, appRegisteredNodes.size()); - Assert.assertTrue(10 == appRegisteredNodes.get("node1")); - Assert.assertTrue(20 == appRegisteredNodes.get("172.10.15.20")); + Assertions.assertEquals(2, appRegisteredNodes.size()); + Assertions.assertTrue(10 == appRegisteredNodes.get("node1")); + Assertions.assertTrue(20 == appRegisteredNodes.get("172.10.15.20")); // test clientAuthenticatorType - Assert.assertEquals("client-secret", application.getClientAuthenticatorType()); - Assert.assertEquals("client-jwt", otherApp.getClientAuthenticatorType()); + Assertions.assertEquals("client-secret", application.getClientAuthenticatorType()); + Assertions.assertEquals("client-jwt", otherApp.getClientAuthenticatorType()); // test authenticationFlowBindingOverrides Map flowMap = otherApp.getAuthenticationFlowBindingOverrides(); - Assert.assertNotNull(flowMap); - Assert.assertEquals(1, flowMap.size()); - Assert.assertTrue(flowMap.containsKey("browser")); + Assertions.assertNotNull(flowMap); + Assertions.assertEquals(1, flowMap.size()); + Assertions.assertTrue(flowMap.containsKey("browser")); // if the authentication flows were correctly imported there must be a flow whose id matches the one in the authenticationFlowBindingOverrides AuthenticationFlowRepresentation flowRep = realmRsc.flows().getFlow(flowMap.get("browser")); - Assert.assertNotNull(flowRep); - Assert.assertEquals("browser", flowRep.getAlias()); + Assertions.assertNotNull(flowRep); + Assertions.assertEquals("browser", flowRep.getAlias()); // Test finding applications by ID - Assert.assertNull(AdminApiUtil.findClientResourceById(realmRsc, "982734")); - Assert.assertEquals(application.getId(), AdminApiUtil.findClientResourceById(realmRsc, application.getId()).toRepresentation().getId()); + Assertions.assertNull(AdminApiUtil.findClientResourceById(realmRsc, "982734")); + Assertions.assertEquals(application.getId(), AdminApiUtil.findClientResourceById(realmRsc, application.getId()).toRepresentation().getId()); // Test role mappings UserRepresentation admin = findByUsername(realmRsc, "admin"); - Assert.assertNotNull(admin.getCreatedTimestamp()); + Assertions.assertNotNull(admin.getCreatedTimestamp()); Set allRoles = allRoles(realmRsc, admin); - Assert.assertEquals(3, allRoles.size()); - Assert.assertTrue(containsRole(allRoles, findRealmRole(realmRsc, "admin"))); - Assert.assertTrue(containsRole(allRoles, findClientRole(realmRsc, application.getId(), "app-admin"))); - Assert.assertTrue(containsRole(allRoles, findClientRole(realmRsc, otherApp.getId(), "otherapp-admin"))); + Assertions.assertEquals(3, allRoles.size()); + Assertions.assertTrue(containsRole(allRoles, findRealmRole(realmRsc, "admin"))); + Assertions.assertTrue(containsRole(allRoles, findClientRole(realmRsc, application.getId(), "app-admin"))); + Assertions.assertTrue(containsRole(allRoles, findClientRole(realmRsc, otherApp.getId(), "otherapp-admin"))); UserRepresentation wburke = findByUsername(realmRsc, "wburke"); // user with creation timestamp in import - Assert.assertEquals(Long.valueOf(123654), wburke.getCreatedTimestamp()); + Assertions.assertEquals(Long.valueOf(123654), wburke.getCreatedTimestamp()); allRoles = allRoles(realmRsc, wburke); - Assert.assertEquals(2, allRoles.size()); - Assert.assertFalse(containsRole(allRoles, findRealmRole(realmRsc, "admin"))); - Assert.assertTrue(containsRole(allRoles, findClientRole(realmRsc, application.getId(), "app-user"))); - Assert.assertTrue(containsRole(allRoles, findClientRole(realmRsc, otherApp.getId(), "otherapp-user"))); + Assertions.assertEquals(2, allRoles.size()); + Assertions.assertFalse(containsRole(allRoles, findRealmRole(realmRsc, "admin"))); + Assertions.assertTrue(containsRole(allRoles, findClientRole(realmRsc, application.getId(), "app-user"))); + Assertions.assertTrue(containsRole(allRoles, findClientRole(realmRsc, otherApp.getId(), "otherapp-user"))); - Assert.assertNull(realmRsc.users().get(wburke.getId()).roles().getAll().getRealmMappings()); + Assertions.assertNull(realmRsc.users().get(wburke.getId()).roles().getAll().getRealmMappings()); - Assert.assertEquals((Object) 159, wburke.getNotBefore()); + Assertions.assertEquals((Object) 159, wburke.getNotBefore()); UserRepresentation loginclient = findByUsername(realmRsc, "loginclient"); // user with creation timestamp as string in import - Assert.assertEquals(Long.valueOf(123655), loginclient.getCreatedTimestamp()); + Assertions.assertEquals(Long.valueOf(123655), loginclient.getCreatedTimestamp()); UserRepresentation hashedPasswordUser = findByUsername(realmRsc, "hashedpassworduser"); CredentialRepresentation password = realmRsc.users().get(hashedPasswordUser.getId()).credentials().stream() .filter(credential -> PasswordCredentialModel.TYPE.equals(credential.getType())) .findFirst().get(); PasswordCredentialData credentialData = JsonSerialization.readValue(password.getCredentialData(), PasswordCredentialData.class); - Assert.assertEquals(1234, credentialData.getHashIterations()); + Assertions.assertEquals(1234, credentialData.getHashIterations()); List realmRoles = realmRolesForUser(realmRsc, admin); - Assert.assertEquals(1, realmRoles.size()); - Assert.assertEquals("admin", realmRoles.iterator().next().getName()); + Assertions.assertEquals(1, realmRoles.size()); + Assertions.assertEquals("admin", realmRoles.iterator().next().getName()); List appRoles = clientRolesForUser(realmRsc, application, admin); - Assert.assertEquals(1, appRoles.size()); - Assert.assertEquals("app-admin", appRoles.iterator().next().getName()); + Assertions.assertEquals(1, appRoles.size()); + Assertions.assertEquals("app-admin", appRoles.iterator().next().getName()); // Test attributes Map> attrs = wburke.getAttributes(); - Assert.assertEquals(1, attrs.size()); + Assertions.assertEquals(1, attrs.size()); List attrVals = attrs.get("old-email"); - Assert.assertEquals(1, attrVals.size()); - Assert.assertEquals("bburke@redhat.com", attrVals.get(0)); + Assertions.assertEquals(1, attrVals.size()); + Assertions.assertEquals("bburke@redhat.com", attrVals.get(0)); attrs = admin.getAttributes(); - Assert.assertEquals(2, attrs.size()); + Assertions.assertEquals(2, attrs.size()); attrVals = attrs.get("key1"); - Assert.assertEquals(1, attrVals.size()); - Assert.assertEquals("val1", attrVals.get(0)); + Assertions.assertEquals(1, attrVals.size()); + Assertions.assertEquals("val1", attrVals.get(0)); attrVals = attrs.get("key2"); - Assert.assertEquals(2, attrVals.size()); - Assert.assertTrue(attrVals.contains("val21") && attrVals.contains("val22")); + Assertions.assertEquals(2, attrVals.size()); + Assertions.assertTrue(attrVals.contains("val21") && attrVals.contains("val22")); // Test client ClientResource oauthClient = AdminApiUtil.findClientResourceByClientId(realmRsc, "oauthclient"); ClientRepresentation oauthClientRep = oauthClient.toRepresentation(); - Assert.assertEquals("clientpassword", oauthClient.getSecret().getValue()); - Assert.assertTrue(oauthClientRep.isEnabled()); - Assert.assertNotNull(oauthClientRep); + Assertions.assertEquals("clientpassword", oauthClient.getSecret().getValue()); + Assertions.assertTrue(oauthClientRep.isEnabled()); + Assertions.assertNotNull(oauthClientRep); // Test scope relationship Set allScopes = allScopeMappings(oauthClient); - Assert.assertEquals(2, allScopes.size()); - Assert.assertTrue(containsRole(allScopes, findRealmRole(realmRsc, "admin"))); - Assert.assertTrue(containsRole(allScopes, findClientRole(realmRsc, application.getId(), "app-user"))); + Assertions.assertEquals(2, allScopes.size()); + Assertions.assertTrue(containsRole(allScopes, findRealmRole(realmRsc, "admin"))); + Assertions.assertTrue(containsRole(allScopes, findClientRole(realmRsc, application.getId(), "app-user"))); List realmScopes = realmScopeMappings(oauthClient); - Assert.assertTrue(containsRole(realmScopes, findRealmRole(realmRsc, "admin"))); + Assertions.assertTrue(containsRole(realmScopes, findRealmRole(realmRsc, "admin"))); List appScopes = clientScopeMappings(oauthClient); - Assert.assertTrue(containsRole(appScopes, findClientRole(realmRsc, application.getId(), "app-user"))); + Assertions.assertTrue(containsRole(appScopes, findClientRole(realmRsc, application.getId(), "app-user"))); // Test social linking UserResource socialUser = realmRsc.users().get(findByUsername(realmRsc, "mySocialUser").getId()); List socialLinks = socialUser.getFederatedIdentity(); - Assert.assertEquals(3, socialLinks.size()); + Assertions.assertEquals(3, socialLinks.size()); boolean facebookFound = false; boolean googleFound = false; boolean twitterFound = false; @@ -252,114 +252,114 @@ public static void assertDataImportedInRealm(Keycloak adminClient, KeycloakTesti if ("facebook1".equals(federatedIdentityRep.getIdentityProvider())) { facebookFound = true; facebookIdentityRep = federatedIdentityRep; - Assert.assertEquals("facebook1",federatedIdentityRep.getUserId()); - Assert.assertEquals("fbuser1", federatedIdentityRep.getUserName()); + Assertions.assertEquals("facebook1",federatedIdentityRep.getUserId()); + Assertions.assertEquals("fbuser1", federatedIdentityRep.getUserName()); } else if ("google1".equals(federatedIdentityRep.getIdentityProvider())) { googleFound = true; - Assert.assertEquals("google1", federatedIdentityRep.getUserId()); - Assert.assertEquals("mySocialUser@gmail.com", federatedIdentityRep.getUserName()); + Assertions.assertEquals("google1", federatedIdentityRep.getUserId()); + Assertions.assertEquals("mySocialUser@gmail.com", federatedIdentityRep.getUserName()); } else if ("twitter1".equals(federatedIdentityRep.getIdentityProvider())) { twitterFound = true; - Assert.assertEquals("twitter1", federatedIdentityRep.getUserId()); - Assert.assertEquals("twuser1", federatedIdentityRep.getUserName()); + Assertions.assertEquals("twitter1", federatedIdentityRep.getUserId()); + Assertions.assertEquals("twuser1", federatedIdentityRep.getUserName()); } } - Assert.assertTrue(facebookFound && twitterFound && googleFound); + Assertions.assertTrue(facebookFound && twitterFound && googleFound); // make sure the username format is the same when importing UserResource socialUserLowercase = realmRsc.users().get(findByUsername(realmRsc, "lowercasesocialuser").getId()); List socialLowercaseLinks = socialUserLowercase.getFederatedIdentity(); - Assert.assertEquals(1, socialLowercaseLinks.size()); - Assert.assertEquals("lowercasesocialuser@gmail.com", socialLowercaseLinks.get(0).getUserName()); + Assertions.assertEquals(1, socialLowercaseLinks.size()); + Assertions.assertEquals("lowercasesocialuser@gmail.com", socialLowercaseLinks.get(0).getUserName()); UserRepresentation foundSocialUser = testingClient.testing(realm.getRealm()).getUserByFederatedIdentity(realm.getRealm(), "facebook1", "facebook1", "fbuser1"); - Assert.assertEquals(foundSocialUser.getUsername(), socialUser.toRepresentation().getUsername()); - Assert.assertNull(testingClient.testing(realm.getRealm()).getUserByFederatedIdentity(realm.getRealm(), "facebook", "not-existing", "not-existing")); + Assertions.assertEquals(foundSocialUser.getUsername(), socialUser.toRepresentation().getUsername()); + Assertions.assertNull(testingClient.testing(realm.getRealm()).getUserByFederatedIdentity(realm.getRealm(), "facebook", "not-existing", "not-existing")); - Assert.assertEquals("facebook1", facebookIdentityRep.getUserId()); - Assert.assertEquals("fbuser1", facebookIdentityRep.getUserName()); - Assert.assertEquals("facebook1", facebookIdentityRep.getIdentityProvider()); + Assertions.assertEquals("facebook1", facebookIdentityRep.getUserId()); + Assertions.assertEquals("fbuser1", facebookIdentityRep.getUserName()); + Assertions.assertEquals("facebook1", facebookIdentityRep.getIdentityProvider()); // Test remove/add social link socialUser.removeFederatedIdentity("facebook1"); - Assert.assertEquals(2, socialUser.getFederatedIdentity().size()); + Assertions.assertEquals(2, socialUser.getFederatedIdentity().size()); socialUser.addFederatedIdentity("facebook1", facebookIdentityRep); - Assert.assertEquals(3, socialUser.getFederatedIdentity().size()); + Assertions.assertEquals(3, socialUser.getFederatedIdentity().size()); // Test smtp config Map smtpConfig = realm.getSmtpServer(); - Assert.assertTrue(smtpConfig.size() == 3); - Assert.assertEquals("auto@keycloak.org", smtpConfig.get("from")); - Assert.assertEquals("localhost", smtpConfig.get("host")); - Assert.assertEquals("3025", smtpConfig.get("port")); + Assertions.assertTrue(smtpConfig.size() == 3); + Assertions.assertEquals("auto@keycloak.org", smtpConfig.get("from")); + Assertions.assertEquals("localhost", smtpConfig.get("host")); + Assertions.assertEquals("3025", smtpConfig.get("port")); // Test identity providers List identityProviders = realmRsc.identityProviders().findAll(); - Assert.assertEquals(4, identityProviders.size()); + Assertions.assertEquals(4, identityProviders.size()); IdentityProviderRepresentation google = null; for (IdentityProviderRepresentation idpRep : identityProviders) { if (idpRep.getAlias().equals("google1")) google = idpRep; } - Assert.assertNotNull(google); - Assert.assertEquals("google1", google.getAlias()); - Assert.assertEquals("google", google.getProviderId()); - Assert.assertTrue(google.isEnabled()); - Assert.assertEquals("googleId", google.getConfig().get("clientId")); - Assert.assertEquals("**********", google.getConfig().get("clientSecret")); // secret is masked in GET call + Assertions.assertNotNull(google); + Assertions.assertEquals("google1", google.getAlias()); + Assertions.assertEquals("google", google.getProviderId()); + Assertions.assertTrue(google.isEnabled()); + Assertions.assertEquals("googleId", google.getConfig().get("clientId")); + Assertions.assertEquals("**********", google.getConfig().get("clientSecret")); // secret is masked in GET call ////////////////// // Test federation providers // on import should convert UserfederationProviderRepresentation to Component model List fedProviders = realm.getUserFederationProviders(); - Assert.assertTrue(fedProviders == null || fedProviders.size() == 0); + Assertions.assertTrue(fedProviders == null || fedProviders.size() == 0); List storageProviders = realmRsc.components().query(realm.getId(), UserStorageProvider.class.getName()); - Assert.assertTrue(storageProviders.size() == 2); + Assertions.assertTrue(storageProviders.size() == 2); ComponentRepresentation ldap1 = storageProviders.get(0); ComponentRepresentation ldap2 = storageProviders.get(1); if (!"MyLDAPProvider1".equals(ldap1.getName())) { ldap2 = ldap1; ldap1 = storageProviders.get(1); } - Assert.assertEquals("MyLDAPProvider1", ldap1.getName()); - Assert.assertEquals("ldap", ldap1.getProviderId()); - Assert.assertEquals("1", ldap1.getConfig().getFirst("priority")); - Assert.assertEquals("ldap://foo", ldap1.getConfig().getFirst(LDAPConstants.CONNECTION_URL)); + Assertions.assertEquals("MyLDAPProvider1", ldap1.getName()); + Assertions.assertEquals("ldap", ldap1.getProviderId()); + Assertions.assertEquals("1", ldap1.getConfig().getFirst("priority")); + Assertions.assertEquals("ldap://foo", ldap1.getConfig().getFirst(LDAPConstants.CONNECTION_URL)); - Assert.assertEquals("MyLDAPProvider2", ldap2.getName()); - Assert.assertEquals("ldap://bar", ldap2.getConfig().getFirst(LDAPConstants.CONNECTION_URL)); + Assertions.assertEquals("MyLDAPProvider2", ldap2.getName()); + Assertions.assertEquals("ldap://bar", ldap2.getConfig().getFirst(LDAPConstants.CONNECTION_URL)); // Test federation mappers List fedMappers1 = realmRsc.components().query(ldap1.getId(), LDAPStorageMapper.class.getName()); ComponentRepresentation fullNameMapper = fedMappers1.iterator().next(); - Assert.assertEquals("FullNameMapper", fullNameMapper.getName()); - Assert.assertEquals(FullNameLDAPStorageMapperFactory.PROVIDER_ID, fullNameMapper.getProviderId()); - Assert.assertEquals("cn", fullNameMapper.getConfig().getFirst(FullNameLDAPStorageMapper.LDAP_FULL_NAME_ATTRIBUTE)); + Assertions.assertEquals("FullNameMapper", fullNameMapper.getName()); + Assertions.assertEquals(FullNameLDAPStorageMapperFactory.PROVIDER_ID, fullNameMapper.getProviderId()); + Assertions.assertEquals("cn", fullNameMapper.getConfig().getFirst(FullNameLDAPStorageMapper.LDAP_FULL_NAME_ATTRIBUTE)); ///////////////// // Assert that federation link wasn't created during import - Assert.assertNull(testingClient.testing(realm.getRealm()).getUserByUsernameFromFedProviderFactory(realm.getRealm(), "wburke")); + Assertions.assertNull(testingClient.testing(realm.getRealm()).getUserByUsernameFromFedProviderFactory(realm.getRealm(), "wburke")); // Test builtin authentication flows AuthenticationFlowRepresentation clientFlow = testingClient.testing(realm.getRealm()).getClientAuthFlow(realm.getRealm()); - Assert.assertEquals(DefaultAuthenticationFlows.CLIENT_AUTHENTICATION_FLOW, clientFlow.getAlias()); - Assert.assertNotNull(realmRsc.flows().getFlow(clientFlow.getId())); - Assert.assertTrue(realmRsc.flows().getExecutions(clientFlow.getAlias()).size() > 0); + Assertions.assertEquals(DefaultAuthenticationFlows.CLIENT_AUTHENTICATION_FLOW, clientFlow.getAlias()); + Assertions.assertNotNull(realmRsc.flows().getFlow(clientFlow.getId())); + Assertions.assertTrue(realmRsc.flows().getExecutions(clientFlow.getAlias()).size() > 0); AuthenticationFlowRepresentation resetFlow = testingClient.testing(realm.getRealm()).getResetCredFlow(realm.getRealm()); - Assert.assertEquals(DefaultAuthenticationFlows.RESET_CREDENTIALS_FLOW, resetFlow.getAlias()); - Assert.assertNotNull(realmRsc.flows().getFlow(resetFlow.getId())); - Assert.assertTrue(realmRsc.flows().getExecutions(resetFlow.getAlias()).size() > 0); + Assertions.assertEquals(DefaultAuthenticationFlows.RESET_CREDENTIALS_FLOW, resetFlow.getAlias()); + Assertions.assertNotNull(realmRsc.flows().getFlow(resetFlow.getId())); + Assertions.assertTrue(realmRsc.flows().getExecutions(resetFlow.getAlias()).size() > 0); // Test protocol mappers. Default application doesn't have any builtin protocol mappers. OtherApp just gss credential List applicationMappers = application.getProtocolMappers(); - Assert.assertNull(findMapperByName(applicationMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, "username"));//application.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, "username")); - Assert.assertNull(findMapperByName(applicationMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, "email")); - Assert.assertNull(findMapperByName(applicationMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, "given name")); - Assert.assertNull(findMapperByName(applicationMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, KerberosConstants.GSS_DELEGATION_CREDENTIAL_DISPLAY_NAME)); + Assertions.assertNull(findMapperByName(applicationMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, "username"));//application.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, "username")); + Assertions.assertNull(findMapperByName(applicationMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, "email")); + Assertions.assertNull(findMapperByName(applicationMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, "given name")); + Assertions.assertNull(findMapperByName(applicationMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, KerberosConstants.GSS_DELEGATION_CREDENTIAL_DISPLAY_NAME)); - Assert.assertEquals(1, otherApp.getProtocolMappers().size()); + Assertions.assertEquals(1, otherApp.getProtocolMappers().size()); List otherAppMappers = otherApp.getProtocolMappers(); - Assert.assertNull(findMapperByName(otherAppMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, "username")); + Assertions.assertNull(findMapperByName(otherAppMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, "username")); ProtocolMapperRepresentation gssCredentialMapper = findMapperByName(otherAppMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, KerberosConstants.GSS_DELEGATION_CREDENTIAL_DISPLAY_NAME); assertGssProtocolMapper(gssCredentialMapper); @@ -370,31 +370,31 @@ public static void assertDataImportedInRealm(Keycloak adminClient, KeycloakTesti return "foo_scope".equals(clientScope1.getName()); }).findFirst().get(); - Assert.assertEquals("foo_scope", clientScope.getName()); - Assert.assertEquals("foo scope-desc", clientScope.getDescription()); - Assert.assertEquals(OIDCLoginProtocol.LOGIN_PROTOCOL, clientScope.getProtocol()); - Assert.assertEquals(1, clientScope.getProtocolMappers().size()); + Assertions.assertEquals("foo_scope", clientScope.getName()); + Assertions.assertEquals("foo scope-desc", clientScope.getDescription()); + Assertions.assertEquals(OIDCLoginProtocol.LOGIN_PROTOCOL, clientScope.getProtocol()); + Assertions.assertEquals(1, clientScope.getProtocolMappers().size()); List clientScopeMappers = clientScope.getProtocolMappers(); ProtocolMapperRepresentation scopeGssCredentialMapper = findMapperByName(clientScopeMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, KerberosConstants.GSS_DELEGATION_CREDENTIAL_DISPLAY_NAME); assertGssProtocolMapper(scopeGssCredentialMapper); // Test client scope - scopes Set allClientScopeScopes = allScopeMappings(realmRsc.clientScopes().get(clientScope.getId())); - Assert.assertEquals(3, allClientScopeScopes.size()); - Assert.assertTrue(containsRole(allClientScopeScopes, findRealmRole(realmRsc, "admin"))); - Assert.assertTrue(containsRole(allClientScopeScopes, findClientRole(realmRsc, application.getId(), "app-user"))); - Assert.assertTrue(containsRole(allClientScopeScopes, findClientRole(realmRsc, application.getId(), "app-admin"))); + Assertions.assertEquals(3, allClientScopeScopes.size()); + Assertions.assertTrue(containsRole(allClientScopeScopes, findRealmRole(realmRsc, "admin"))); + Assertions.assertTrue(containsRole(allClientScopeScopes, findClientRole(realmRsc, application.getId(), "app-user"))); + Assertions.assertTrue(containsRole(allClientScopeScopes, findClientRole(realmRsc, application.getId(), "app-admin"))); List clientScopeRealmScopes = realmScopeMappings(realmRsc.clientScopes().get(clientScope.getId())); - Assert.assertTrue(containsRole(clientScopeRealmScopes, findRealmRole(realmRsc, "admin"))); + Assertions.assertTrue(containsRole(clientScopeRealmScopes, findRealmRole(realmRsc, "admin"))); List clientScopeAppScopes = clientScopeMappings(realmRsc.clientScopes().get(clientScope.getId())); - Assert.assertTrue(containsRole(clientScopeAppScopes, findClientRole(realmRsc, application.getId(), "app-user"))); - Assert.assertTrue(containsRole(clientScopeAppScopes, findClientRole(realmRsc, application.getId(), "app-admin"))); + Assertions.assertTrue(containsRole(clientScopeAppScopes, findClientRole(realmRsc, application.getId(), "app-user"))); + Assertions.assertTrue(containsRole(clientScopeAppScopes, findClientRole(realmRsc, application.getId(), "app-admin"))); // Test client scopes assignment - Assert.assertTrue(otherApp.getDefaultClientScopes().contains("foo_scope")); - Assert.assertFalse(application.getDefaultClientScopes().contains("foo_scope")); + Assertions.assertTrue(otherApp.getDefaultClientScopes().contains("foo_scope")); + Assertions.assertFalse(application.getDefaultClientScopes().contains("foo_scope")); // Test builtin client scopes testRealmDefaultClientScopes(realmRsc); @@ -402,42 +402,42 @@ public static void assertDataImportedInRealm(Keycloak adminClient, KeycloakTesti // Test user consents UserResource adminRsc = realmRsc.users().get(admin.getId()); List> consents = adminRsc.getConsents(); - Assert.assertEquals(2, consents.size());//.getConsents().size()); + Assertions.assertEquals(2, consents.size());//.getConsents().size()); Map appAdminConsent = findConsentByClientId(consents, application.getClientId()); - Assert.assertNotNull(appAdminConsent); - Assert.assertTrue(isClientScopeGranted(appAdminConsent, OAuth2Constants.OFFLINE_ACCESS, "roles", "profile", "email", "account", "web-origins")); + Assertions.assertNotNull(appAdminConsent); + Assertions.assertTrue(isClientScopeGranted(appAdminConsent, OAuth2Constants.OFFLINE_ACCESS, "roles", "profile", "email", "account", "web-origins")); Map otherAppAdminConsent = findConsentByClientId(consents, otherApp.getClientId());//admin.getConsentByClient(otherApp.getId()); - Assert.assertFalse(isClientScopeGranted(otherAppAdminConsent, OAuth2Constants.OFFLINE_ACCESS)); + Assertions.assertFalse(isClientScopeGranted(otherAppAdminConsent, OAuth2Constants.OFFLINE_ACCESS)); - Assert.assertTrue(application.isStandardFlowEnabled()); - Assert.assertTrue(application.isImplicitFlowEnabled()); - Assert.assertTrue(application.isDirectAccessGrantsEnabled()); - Assert.assertFalse(otherApp.isStandardFlowEnabled()); - Assert.assertFalse(otherApp.isImplicitFlowEnabled()); - Assert.assertFalse(otherApp.isDirectAccessGrantsEnabled()); + Assertions.assertTrue(application.isStandardFlowEnabled()); + Assertions.assertTrue(application.isImplicitFlowEnabled()); + Assertions.assertTrue(application.isDirectAccessGrantsEnabled()); + Assertions.assertFalse(otherApp.isStandardFlowEnabled()); + Assertions.assertFalse(otherApp.isImplicitFlowEnabled()); + Assertions.assertFalse(otherApp.isDirectAccessGrantsEnabled()); // Test service accounts - Assert.assertFalse(application.isServiceAccountsEnabled()); - Assert.assertTrue(otherApp.isServiceAccountsEnabled()); + Assertions.assertFalse(application.isServiceAccountsEnabled()); + Assertions.assertTrue(otherApp.isServiceAccountsEnabled()); if (ProfileAssume.isFeatureEnabled(Profile.Feature.AUTHORIZATION)) { - Assert.assertTrue(testAppAuthzApp.isServiceAccountsEnabled()); - Assert.assertNull(testingClient.testing(realm.getRealm()).getUserByServiceAccountClient(realm.getRealm(), application.getClientId()));//session.users().getUserByServiceAccountClient(application)); + Assertions.assertTrue(testAppAuthzApp.isServiceAccountsEnabled()); + Assertions.assertNull(testingClient.testing(realm.getRealm()).getUserByServiceAccountClient(realm.getRealm(), application.getClientId()));//session.users().getUserByServiceAccountClient(application)); UserRepresentation otherAppSA = testingClient.testing(realm.getRealm()).getUserByServiceAccountClient(realm.getRealm(), otherApp.getClientId());//session.users().getUserByServiceAccountClient(otherApp); - Assert.assertNotNull(otherAppSA); - Assert.assertEquals("service-account-otherapp", otherAppSA.getUsername()); + Assertions.assertNotNull(otherAppSA); + Assertions.assertEquals("service-account-otherapp", otherAppSA.getUsername()); UserRepresentation testAppAuthzSA = testingClient.testing(realm.getRealm()).getUserByServiceAccountClient(realm.getRealm(), testAppAuthzApp.getClientId()); - Assert.assertNotNull(testAppAuthzSA); - Assert.assertEquals("service-account-test-app-authz", testAppAuthzSA.getUsername()); + Assertions.assertNotNull(testAppAuthzSA); + Assertions.assertEquals("service-account-test-app-authz", testAppAuthzSA.getUsername()); // test service account maintains the roles in OtherApp allRoles = allRoles(realmRsc, otherAppSA); - Assert.assertEquals(3, allRoles.size()); - Assert.assertTrue(containsRole(allRoles, findRealmRole(realmRsc, "user"))); - Assert.assertTrue(containsRole(allRoles, findClientRole(realmRsc, otherApp.getId(), "otherapp-user"))); - Assert.assertTrue(containsRole(allRoles, findClientRole(realmRsc, otherApp.getId(), "otherapp-admin"))); + Assertions.assertEquals(3, allRoles.size()); + Assertions.assertTrue(containsRole(allRoles, findRealmRole(realmRsc, "user"))); + Assertions.assertTrue(containsRole(allRoles, findClientRole(realmRsc, otherApp.getId(), "otherapp-user"))); + Assertions.assertTrue(containsRole(allRoles, findClientRole(realmRsc, otherApp.getId(), "otherapp-admin"))); assertAuthorizationSettingsOtherApp(realmRsc); assertAuthorizationSettingsTestAppAuthz(realmRsc); @@ -445,8 +445,8 @@ public static void assertDataImportedInRealm(Keycloak adminClient, KeycloakTesti // Test Message Bundle Map localizations = adminClient.realm(realm.getRealm()).localization().getRealmLocalizationTexts("en"); - Assert.assertEquals("value1", localizations.get("key1")); - Assert.assertEquals("value2", localizations.get("key2")); + Assertions.assertEquals("value1", localizations.get("key1")); + Assertions.assertEquals("value2", localizations.get("key2")); } @@ -464,13 +464,13 @@ private static Map findConsentByClientId(List mappers, String type, String name) { @@ -602,7 +602,7 @@ private static boolean containsRole(Collection roles, RoleRe private static void assertAuthorizationSettingsOtherApp(RealmResource realmRsc) { AuthorizationResource authzResource = AdminApiUtil.findAuthorizationSettings(realmRsc, "OtherApp"); - Assert.assertNotNull(authzResource); + Assertions.assertNotNull(authzResource); List resources = authzResource.resources().resources(); assertThat(resources.stream().map(ResourceRepresentation::getName).collect(Collectors.toList()), @@ -616,52 +616,52 @@ private static void assertAuthorizationSettingsOtherApp(RealmResource realmRsc) private static void assertAuthorizationSettingsTestAppAuthz(RealmResource realmRsc) { AuthorizationResource authzResource = AdminApiUtil.findAuthorizationSettings(realmRsc, "test-app-authz"); - Assert.assertNotNull(authzResource); + Assertions.assertNotNull(authzResource); List resources = authzResource.resources().resources(); - Assert.assertEquals(4, resources.size()); + Assertions.assertEquals(4, resources.size()); ResourceServerRepresentation authzSettings = authzResource.getSettings(); List> resourcePredicates = new ArrayList<>(); resourcePredicates.add(resourceRep -> { if ("Admin Resource".equals(resourceRep.getName())) { - Assert.assertEquals(authzSettings.getClientId(), resourceRep.getOwner().getId()); - Assert.assertEquals("/protected/admin/*", resourceRep.getUri()); - Assert.assertEquals("http://test-app-authz/protected/admin", resourceRep.getType()); - Assert.assertEquals("http://icons.com/icon-admin", resourceRep.getIconUri()); - Assert.assertEquals(1, resourceRep.getScopes().size()); + Assertions.assertEquals(authzSettings.getClientId(), resourceRep.getOwner().getId()); + Assertions.assertEquals("/protected/admin/*", resourceRep.getUri()); + Assertions.assertEquals("http://test-app-authz/protected/admin", resourceRep.getType()); + Assertions.assertEquals("http://icons.com/icon-admin", resourceRep.getIconUri()); + Assertions.assertEquals(1, resourceRep.getScopes().size()); return true; } return false; }); resourcePredicates.add(resourceRep -> { if ("Protected Resource".equals(resourceRep.getName())) { - Assert.assertEquals(authzSettings.getClientId(), resourceRep.getOwner().getId()); - Assert.assertEquals("/*", resourceRep.getUri()); - Assert.assertEquals("http://test-app-authz/protected/resource", resourceRep.getType()); - Assert.assertEquals("http://icons.com/icon-resource", resourceRep.getIconUri()); - Assert.assertEquals(1, resourceRep.getScopes().size()); + Assertions.assertEquals(authzSettings.getClientId(), resourceRep.getOwner().getId()); + Assertions.assertEquals("/*", resourceRep.getUri()); + Assertions.assertEquals("http://test-app-authz/protected/resource", resourceRep.getType()); + Assertions.assertEquals("http://icons.com/icon-resource", resourceRep.getIconUri()); + Assertions.assertEquals(1, resourceRep.getScopes().size()); return true; } return false; }); resourcePredicates.add(resourceRep -> { if ("Premium Resource".equals(resourceRep.getName())) { - Assert.assertEquals(authzSettings.getClientId(), resourceRep.getOwner().getId()); - Assert.assertEquals("/protected/premium/*", resourceRep.getUri()); - Assert.assertEquals("urn:test-app-authz:protected:resource", resourceRep.getType()); - Assert.assertEquals("http://icons.com/icon-premium", resourceRep.getIconUri()); - Assert.assertEquals(1, resourceRep.getScopes().size()); + Assertions.assertEquals(authzSettings.getClientId(), resourceRep.getOwner().getId()); + Assertions.assertEquals("/protected/premium/*", resourceRep.getUri()); + Assertions.assertEquals("urn:test-app-authz:protected:resource", resourceRep.getType()); + Assertions.assertEquals("http://icons.com/icon-premium", resourceRep.getIconUri()); + Assertions.assertEquals(1, resourceRep.getScopes().size()); return true; } return false; }); resourcePredicates.add(resourceRep -> { if ("Main Page".equals(resourceRep.getName())) { - Assert.assertEquals(authzSettings.getClientId(), resourceRep.getOwner().getId()); - Assert.assertNull(resourceRep.getUri()); - Assert.assertEquals("urn:test-app-authz:protected:resource", resourceRep.getType()); - Assert.assertEquals("http://icons.com/icon-main-page", resourceRep.getIconUri()); - Assert.assertEquals(3, resourceRep.getScopes().size()); + Assertions.assertEquals(authzSettings.getClientId(), resourceRep.getOwner().getId()); + Assertions.assertNull(resourceRep.getUri()); + Assertions.assertEquals("urn:test-app-authz:protected:resource", resourceRep.getType()); + Assertions.assertEquals("http://icons.com/icon-main-page", resourceRep.getIconUri()); + Assertions.assertEquals(3, resourceRep.getScopes().size()); return true; } return false; @@ -669,7 +669,7 @@ private static void assertAuthorizationSettingsTestAppAuthz(RealmResource realmR assertPredicate(resources, resourcePredicates); List scopes = authzResource.scopes().scopes(); - Assert.assertEquals(6, scopes.size()); + Assertions.assertEquals(6, scopes.size()); List> scopePredicates = new ArrayList<>(); scopePredicates.add(scopeRepresentation -> "admin-access".equals(scopeRepresentation.getName())); scopePredicates.add(scopeRepresentation -> "resource-access".equals(scopeRepresentation.getName())); @@ -680,7 +680,7 @@ private static void assertAuthorizationSettingsTestAppAuthz(RealmResource realmR assertPredicate(scopes, scopePredicates); List policies = authzResource.policies().policies(); - Assert.assertEquals(14, policies.size()); + Assertions.assertEquals(14, policies.size()); List> policyPredicates = new ArrayList<>(); policyPredicates.add(policyRepresentation -> "Any Admin Policy".equals(policyRepresentation.getName())); policyPredicates.add(policyRepresentation -> "Any User Policy".equals(policyRepresentation.getName())); @@ -700,7 +700,7 @@ private static void assertAuthorizationSettingsTestAppAuthz(RealmResource realmR } private static void assertPredicate(List source, List> predicate) { - Assert.assertTrue(!source.stream().filter(object -> !predicate.stream().filter(predicate1 -> predicate1.test(object)).findFirst().isPresent()).findAny().isPresent()); + Assertions.assertTrue(!source.stream().filter(object -> !predicate.stream().filter(predicate1 -> predicate1.test(object)).findFirst().isPresent()).findAny().isPresent()); } private static Matcher> getDefaultClientScopeNameMatcher(ClientRepresentation rep) { @@ -747,7 +747,7 @@ public static void testRealmDefaultClientScopes(RealmResource realm) { org.keycloak.testsuite.Assert.assertNames(protocolMappers.keySet(), OIDCLoginProtocolFactory.EMAIL, OIDCLoginProtocolFactory.EMAIL_VERIFIED); ClientScopeRepresentation offlineScope = clientScopesMap.get(OAuth2Constants.OFFLINE_ACCESS); - org.keycloak.testsuite.Assert.assertTrue(offlineScope.getProtocolMappers()==null || offlineScope.getProtocolMappers().isEmpty()); + Assertions.assertTrue(offlineScope.getProtocolMappers()==null || offlineScope.getProtocolMappers().isEmpty()); List offlineRoleScopes = realm.clientScopes().get(offlineScope.getId()).getScopeMappings().realmLevel().listAll(); org.keycloak.testsuite.Assert.assertNames(offlineRoleScopes, OAuth2Constants.OFFLINE_ACCESS); @@ -778,7 +778,7 @@ public static void testDefaultPostLogoutRedirectUris(RealmResource realm) { List redirectUris = client.getRedirectUris(); if(redirectUris != null && !redirectUris.isEmpty()) { String postLogoutRedirectUris = client.getAttributes().get(OIDCConfigAttributes.POST_LOGOUT_REDIRECT_URIS); - Assert.assertEquals("+", postLogoutRedirectUris); + Assertions.assertEquals("+", postLogoutRedirectUris); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/UserStorageGracefulDegradationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/UserStorageGracefulDegradationTest.java index bb388349d039..c148af9778fd 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/UserStorageGracefulDegradationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/UserStorageGracefulDegradationTest.java @@ -34,9 +34,9 @@ import org.keycloak.testsuite.arquillian.annotation.ModelTest; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -140,7 +140,7 @@ public void testGracefulDegradationOnSearchFailure(KeycloakSession session) { hasItems("local-user1", "local-user2", "local-admin")); // Should have at least our 3 local users - Assert.assertTrue("Should have at least 3 users, found: " + usernames.size(), usernames.size() >= 3); + Assertions.assertTrue(usernames.size() >= 3, "Should have at least 3 users, found: " + usernames.size()); } @@ -159,7 +159,7 @@ public void testGracefulDegradationWithSearchString(KeycloakSession session) { List usernames = users.map(UserModel::getUsername).toList(); // Should find users from working providers that match the search - Assert.assertFalse("Should find some users matching 'user'", usernames.isEmpty()); + Assertions.assertFalse(usernames.isEmpty(), "Should find some users matching 'user'"); // Verify all returned users have "user" in their username for (String username : usernames) { @@ -181,7 +181,7 @@ public void testGracefulDegradationOnCountFailure(KeycloakSession session) { // Should count users from local storage despite failing provider // At least 3 users: 3 local users - Assert.assertTrue("User count should be at least 3, but was: " + userCount, userCount >= 3); + Assertions.assertTrue(userCount >= 3, "User count should be at least 3, but was: " + userCount); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/AbstractKerberosSingleRealmTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/AbstractKerberosSingleRealmTest.java index 1a615c1df062..56499dac20d8 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/AbstractKerberosSingleRealmTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/AbstractKerberosSingleRealmTest.java @@ -36,7 +36,6 @@ import org.keycloak.representations.idm.ProtocolMapperRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.storage.UserStorageProvider; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.pages.AppPage; import org.keycloak.testsuite.util.AccountHelper; @@ -47,6 +46,7 @@ import org.jboss.arquillian.graphene.page.Page; import org.junit.Assume; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.admin.AdminApiUtil.findClientByClientId; @@ -67,8 +67,8 @@ public void spnegoNotAvailableTest() throws Exception { String kcLoginPageLocation = oauth.loginForm().build(); Response response = client.target(kcLoginPageLocation).request().get(); - Assert.assertEquals(401, response.getStatus()); - Assert.assertEquals(KerberosConstants.NEGOTIATE, response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE)); + Assertions.assertEquals(401, response.getStatus()); + Assertions.assertEquals(KerberosConstants.NEGOTIATE, response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE)); String responseText = response.readEntity(String.class); response.close(); } @@ -97,11 +97,11 @@ the login page (username/password) and return status 200. It should not return 4 */ Response spnegoResponse = spnegoLogin("hnelson", "secret"); - Assert.assertEquals(200, spnegoResponse.getStatus()); + Assertions.assertEquals(200, spnegoResponse.getStatus()); String context = spnegoResponse.readEntity(String.class); spnegoResponse.close(); - org.junit.Assert.assertTrue(context.contains("Sign in to test")); + Assertions.assertTrue(context.contains("Sign in to test")); events.clear(); } finally { @@ -118,7 +118,7 @@ public void spnegoLoginWithRequiredKerberosAuthExecutionTest() { Response response = spnegoLogin("hnelson", "secret"); updateKerberosAuthExecutionRequirement(oldRequirement); - Assert.assertEquals(302, response.getStatus()); + Assertions.assertEquals(302, response.getStatus()); } @@ -136,30 +136,30 @@ public void usernamePasswordLoginTest() throws Exception { TestAppHelper testAppHelper = new TestAppHelper(oauth, loginPage, appPage); - Assert.assertTrue(testAppHelper.login("jduke", "theduke")); - Assert.assertTrue(testAppHelper.logout()); + Assertions.assertTrue(testAppHelper.login("jduke", "theduke")); + Assertions.assertTrue(testAppHelper.logout()); // Change password is not possible as editMode is READ_ONLY - Assert.assertFalse(AccountHelper.updatePassword(testRealmResource(), "jduke", "newPass")); + Assertions.assertFalse(AccountHelper.updatePassword(testRealmResource(), "jduke", "newPass")); - Assert.assertFalse(testAppHelper.login("jduke", "newPass")); + Assertions.assertFalse(testAppHelper.login("jduke", "newPass")); // Change editMode to UNSYNCED updateProviderEditMode(UserStorageProvider.EditMode.UNSYNCED); // Successfully change password now - Assert.assertTrue(AccountHelper.updatePassword(testRealmResource(), "jduke", "newPass")); + Assertions.assertTrue(AccountHelper.updatePassword(testRealmResource(), "jduke", "newPass")); // Login with old password doesn't work, but with new password works - Assert.assertFalse(testAppHelper.login("jduke", "theduke")); - Assert.assertTrue(testAppHelper.login("jduke", "newPass")); + Assertions.assertFalse(testAppHelper.login("jduke", "theduke")); + Assertions.assertTrue(testAppHelper.login("jduke", "newPass")); testAppHelper.logout(); // Assert SPNEGO login still with the old password as mode is unsynced events.clear(); Response spnegoResponse = spnegoLogin("jduke", "theduke"); - Assert.assertEquals(302, spnegoResponse.getStatus()); + Assertions.assertEquals(302, spnegoResponse.getStatus()); List users = testRealmResource().users().search("jduke", 0, 1); String userId = users.get(0).getId(); events.expectLogin() @@ -194,14 +194,14 @@ public void credentialDelegationTest() throws Exception { // Assert kerberos ticket in the accessToken can be re-used to authenticate against other 3rd party kerberos service (ApacheDS Server in this case) String serializedGssCredential = (String) token.getOtherClaims().get(KerberosConstants.GSS_DELEGATION_CREDENTIAL); - Assert.assertNotNull(serializedGssCredential); + Assertions.assertNotNull(serializedGssCredential); GSSCredential gssCredential = KerberosSerializationUtils.deserializeCredential(serializedGssCredential); String ldapResponse = invokeLdap(gssCredential, token.getPreferredUsername()); - Assert.assertEquals("Horatio Nelson", ldapResponse); + Assertions.assertEquals("Horatio Nelson", ldapResponse); // Assert kerberos ticket also in userinfo endpoint UserInfo userInfo = oauth.doUserInfoRequest(tokenResponse.getAccessToken()).getUserInfo(); - Assert.assertEquals(serializedGssCredential, userInfo.getOtherClaims().get(KerberosConstants.GSS_DELEGATION_CREDENTIAL)); + Assertions.assertEquals(serializedGssCredential, userInfo.getOtherClaims().get(KerberosConstants.GSS_DELEGATION_CREDENTIAL)); // Clear USER_INFO_REQUEST event events.poll(); @@ -215,9 +215,9 @@ public void credentialDelegationTest() throws Exception { // Login and assert delegated credential not anymore tokenResponse = assertSuccessfulSpnegoLogin("hnelson", "hnelson", "secret"); token = oauth.verifyToken(tokenResponse.getAccessToken()); - Assert.assertFalse(token.getOtherClaims().containsKey(KerberosConstants.GSS_DELEGATION_CREDENTIAL)); + Assertions.assertFalse(token.getOtherClaims().containsKey(KerberosConstants.GSS_DELEGATION_CREDENTIAL)); userInfo = oauth.doUserInfoRequest(tokenResponse.getAccessToken()).getUserInfo(); - Assert.assertFalse(userInfo.getOtherClaims().containsKey(KerberosConstants.GSS_DELEGATION_CREDENTIAL)); + Assertions.assertFalse(userInfo.getOtherClaims().containsKey(KerberosConstants.GSS_DELEGATION_CREDENTIAL)); events.clear(); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/AbstractKerberosTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/AbstractKerberosTest.java index 7b6220a0644b..c97b0b2a45e2 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/AbstractKerberosTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/AbstractKerberosTest.java @@ -54,7 +54,6 @@ import org.keycloak.storage.UserStorageProvider; import org.keycloak.storage.UserStorageProviderModel; import org.keycloak.testsuite.AbstractAuthTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.admin.ApiUtil; @@ -84,6 +83,7 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.auth.page.AuthRealm.TEST; @@ -198,7 +198,7 @@ protected AccessTokenResponse assertSuccessfulSpnegoLogin(String clientId, Strin events.clear(); oauth.clientId(clientId); Response spnegoResponse = spnegoLogin(loginUsername, password); - Assert.assertEquals(302, spnegoResponse.getStatus()); + Assertions.assertEquals(302, spnegoResponse.getStatus()); List users = testRealmResource().users().search(expectedUsername, 0, 1); String userId = users.get(0).getId(); @@ -213,8 +213,8 @@ protected AccessTokenResponse assertSuccessfulSpnegoLogin(String clientId, Strin AccessTokenResponse tokenResponse = assertAuthenticationSuccess(codeUrl); AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken()); - Assert.assertEquals(userId, token.getSubject()); - Assert.assertEquals(expectedUsername, token.getPreferredUsername()); + Assertions.assertEquals(userId, token.getSubject()); + Assertions.assertEquals(expectedUsername, token.getPreferredUsername()); return tokenResponse; } @@ -292,7 +292,7 @@ protected void removeAllUsers() { realm.users().get(user.getId()).remove(); } } - Assert.assertEquals(1, realm.users().search("", 0, -1).size()); + Assertions.assertEquals(1, realm.users().search("", 0, -1).size()); } @@ -301,22 +301,22 @@ protected UserRepresentation assertUser(String expectedUsername, String expected String expectedLastname, String expectedKerberosPrincipal, boolean updateProfileActionExpected) { try { UserRepresentation user = AdminApiUtil.findUserByUsername(testRealmResource(), expectedUsername); - Assert.assertNotNull(user); - Assert.assertEquals(expectedEmail, user.getEmail()); - Assert.assertEquals(expectedFirstname, user.getFirstName()); - Assert.assertEquals(expectedLastname, user.getLastName()); + Assertions.assertNotNull(user); + Assertions.assertEquals(expectedEmail, user.getEmail()); + Assertions.assertEquals(expectedFirstname, user.getFirstName()); + Assertions.assertEquals(expectedLastname, user.getLastName()); if (expectedKerberosPrincipal == null) { - Assert.assertNull(user.getAttributes().get(KerberosConstants.KERBEROS_PRINCIPAL)); + Assertions.assertNull(user.getAttributes().get(KerberosConstants.KERBEROS_PRINCIPAL)); } else { - Assert.assertEquals(expectedKerberosPrincipal, user.getAttributes().get(KerberosConstants.KERBEROS_PRINCIPAL).get(0)); + Assertions.assertEquals(expectedKerberosPrincipal, user.getAttributes().get(KerberosConstants.KERBEROS_PRINCIPAL).get(0)); } if (updateProfileActionExpected) { - Assert.assertEquals(UserModel.RequiredAction.UPDATE_PROFILE.toString(), + Assertions.assertEquals(UserModel.RequiredAction.UPDATE_PROFILE.toString(), user.getRequiredActions().iterator().next()); } else { - Assert.assertTrue(user.getRequiredActions().isEmpty()); + Assertions.assertTrue(user.getRequiredActions().isEmpty()); } return user; } finally { @@ -324,9 +324,9 @@ protected UserRepresentation assertUser(String expectedUsername, String expected } protected void assertUserStorageProvider(UserRepresentation user, String providerName) { - if (user.getFederationLink() == null) Assert.fail("Federation link on user " + user.getUsername() + " was null"); + if (user.getFederationLink() == null) Assertions.fail("Federation link on user " + user.getUsername() + " was null"); ComponentRepresentation rep = testRealmResource().components().component(user.getFederationLink()).toRepresentation(); - Assert.assertEquals(providerName, rep.getName()); + Assertions.assertEquals(providerName, rep.getName()); } @@ -341,10 +341,10 @@ protected AccessTokenResponse assertAuthenticationSuccess(String codeUrl) throws state = pair.getValue(); } } - Assert.assertNotNull(code); - Assert.assertNotNull(state); + Assertions.assertNotNull(code); + Assertions.assertNotNull(state); AccessTokenResponse response = oauth.doAccessTokenRequest(code); - Assert.assertNotNull(response.getAccessToken()); + Assertions.assertNotNull(response.getAccessToken()); events.clear(); return response; } @@ -366,7 +366,7 @@ protected void updateProviderValidatePasswordPolicy(Boolean validatePasswordPoli protected void updateUserStorageProvider(Consumer updater) { String parentId = testRealmResource().toRepresentation().getId(); List reps = testRealmResource().components().query(parentId, UserStorageProvider.class.getName()); - Assert.assertEquals(1, reps.size()); + Assertions.assertEquals(1, reps.size()); ComponentRepresentation kerberosProvider = reps.get(0); updater.accept(kerberosProvider); @@ -387,7 +387,7 @@ public static AuthenticationExecutionModel.Requirement updateKerberosAuthExecuti .filter(e -> e.getProviderId().equals(SpnegoAuthenticatorFactory.PROVIDER_ID)) .findFirst(); - Assert.assertTrue(kerberosAuthExecutionOpt.isPresent()); + Assertions.assertTrue(kerberosAuthExecutionOpt.isPresent()); AuthenticationExecutionInfoRepresentation kerberosAuthExecution = kerberosAuthExecutionOpt.get(); String oldRequirementStr = kerberosAuthExecution.getRequirement(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosLdapCrossRealmTrustTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosLdapCrossRealmTrustTest.java index ae012702ec2e..9b7bc667920b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosLdapCrossRealmTrustTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosLdapCrossRealmTrustTest.java @@ -25,7 +25,6 @@ import org.keycloak.representations.idm.ComponentRepresentation; import org.keycloak.storage.ldap.LDAPStorageProviderFactory; import org.keycloak.storage.ldap.kerberos.LDAPProviderKerberosConfig; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.KerberosEmbeddedServer; import org.keycloak.testsuite.util.KerberosRule; import org.keycloak.testsuite.util.TestAppHelper; @@ -34,6 +33,7 @@ import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; /** @@ -74,7 +74,7 @@ public void test01SpnegoLoginCRTSuccess() throws Exception { AccessTokenResponse tokenResponse = assertSuccessfulSpnegoLogin("hnelson2@KC2.COM", "hnelson2", "secret"); AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken()); - Assert.assertEquals(token.getEmail(), "hnelson2@kc2.com"); + Assertions.assertEquals(token.getEmail(), "hnelson2@kc2.com"); assertUser("hnelson2", "hnelson2@kc2.com", "Horatio", "Nelson", "hnelson2@KC2.COM", false); // Logout @@ -90,7 +90,7 @@ public void test02SpnegoLoginCorrectKerberosPrincipalUserFound() throws Exceptio AccessTokenResponse tokenResponse = assertSuccessfulSpnegoLogin("jduke@KC2.COM", "jduke2", "theduke2"); AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken()); - Assert.assertEquals(token.getEmail(), "jduke2@kc2.com"); + Assertions.assertEquals(token.getEmail(), "jduke2@kc2.com"); assertUser("jduke2", "jduke2@kc2.com", "Java", "Duke", "jduke@KC2.COM", false); // Logout @@ -100,7 +100,7 @@ public void test02SpnegoLoginCorrectKerberosPrincipalUserFound() throws Exceptio // Another login to check the scenario when user is in local storage tokenResponse = assertSuccessfulSpnegoLogin("jduke@KC2.COM", "jduke2", "theduke2"); token = oauth.verifyToken(tokenResponse.getAccessToken()); - Assert.assertEquals(token.getEmail(), "jduke2@kc2.com"); + Assertions.assertEquals(token.getEmail(), "jduke2@kc2.com"); // Logout oauth.logoutForm().idTokenHint(tokenResponse.getIdToken()).open(); @@ -112,12 +112,12 @@ public void test02SpnegoLoginCorrectKerberosPrincipalUserFound() throws Exceptio public void test03SpnegoLoginUsernamePassword() throws Exception { // User jduke@KC2.COM TestAppHelper testAppHelper = new TestAppHelper(oauth, loginPage, appPage); - Assert.assertFalse(testAppHelper.login("jduke2", "theduke")); - Assert.assertTrue(testAppHelper.login("jduke2", "theduke2")); - Assert.assertTrue(testAppHelper.logout()); + Assertions.assertFalse(testAppHelper.login("jduke2", "theduke")); + Assertions.assertTrue(testAppHelper.login("jduke2", "theduke2")); + Assertions.assertTrue(testAppHelper.logout()); // User jduke@KEYCLOAK.ORG - Assert.assertTrue(testAppHelper.login("jduke", "theduke")); + Assertions.assertTrue(testAppHelper.login("jduke", "theduke")); // Logout testAppHelper.logout(); @@ -133,7 +133,7 @@ public void test04SpnegoLoginWithoutKerberosPrincipalAttrConfigured() throws Exc AccessTokenResponse tokenResponse = assertSuccessfulSpnegoLogin("jduke@KC2.COM", "jduke", "theduke2"); AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken()); - Assert.assertEquals(token.getEmail(), "jduke@keycloak.org"); + Assertions.assertEquals(token.getEmail(), "jduke@keycloak.org"); assertUser("jduke", "jduke@keycloak.org", "Java", "Duke", null, false); // Logout @@ -144,7 +144,7 @@ public void test04SpnegoLoginWithoutKerberosPrincipalAttrConfigured() throws Exc tokenResponse = assertSuccessfulSpnegoLogin("jduke@KEYCLOAK.ORG", "jduke", "theduke"); token = oauth.verifyToken(tokenResponse.getAccessToken()); - Assert.assertEquals(token.getEmail(), "jduke@keycloak.org"); + Assertions.assertEquals(token.getEmail(), "jduke@keycloak.org"); // Logout oauth.logoutForm().idTokenHint(tokenResponse.getIdToken()).open(); @@ -162,7 +162,7 @@ public void test05DisableTrust() throws Exception { // as it's not possible to start GSS context ( initSecContext ) due the missing trust among realms. try { Response spnegoResponse = spnegoLogin("hnelson2@KC2.COM", "secret"); - Assert.fail("Not expected to successfully login"); + Assertions.fail("Not expected to successfully login"); } catch (Exception e) { // Expected } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosLdapMultipleLDAPProvidersTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosLdapMultipleLDAPProvidersTest.java index 81a11be1e99a..7801bf411d6c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosLdapMultipleLDAPProvidersTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosLdapMultipleLDAPProvidersTest.java @@ -30,7 +30,6 @@ import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.storage.ldap.LDAPStorageProviderFactory; import org.keycloak.storage.ldap.kerberos.LDAPProviderKerberosConfig; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.KerberosEmbeddedServer; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.util.KerberosRule; @@ -39,6 +38,7 @@ import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; /** @@ -89,7 +89,7 @@ public void test01spnegoWith1stProviderBrokenKerberosConfiguration() throws Exce AccessTokenResponse tokenResponse = assertSuccessfulSpnegoLogin("hnelson2@KC2.COM", "hnelson2", "secret"); AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken()); - Assert.assertEquals(token.getEmail(), "hnelson2@kc2.com"); + Assertions.assertEquals(token.getEmail(), "hnelson2@kc2.com"); UserRepresentation user = assertUser("hnelson2", "hnelson2@kc2.com", "Horatio", "Nelson", "hnelson2@KC2.COM", false); assertUserStorageProvider(user, "kerberos-ldap"); } @@ -108,7 +108,7 @@ public void test02spnegoWith1stProviderBrokenLookupOfKerberosUser() throws Excep AccessTokenResponse tokenResponse = assertSuccessfulSpnegoLogin("hnelson2@KC2.COM", "hnelson2", "secret"); AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken()); - Assert.assertEquals(token.getEmail(), "hnelson2@kc2.com"); + Assertions.assertEquals(token.getEmail(), "hnelson2@kc2.com"); UserRepresentation user = assertUser("hnelson2", "hnelson2@kc2.com", "Horatio", "Nelson", "hnelson2@KC2.COM", false); assertUserStorageProvider(user, "kerberos-ldap"); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosLdapTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosLdapTest.java index 0bdb9d9999ae..d4685da12567 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosLdapTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosLdapTest.java @@ -46,9 +46,9 @@ import org.keycloak.testsuite.util.TestAppHelper; import org.keycloak.testsuite.util.oauth.AccessTokenResponse; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.common.constants.KerberosConstants.KERBEROS_PRINCIPAL; @@ -113,7 +113,7 @@ public void changeKerberosPrincipalWhenUserChangesInLDAPTest() throws Exception // Trigger sync KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory(); SynchronizationResult syncResult = UserStoragePrivateUtil.runFullSync(sessionFactory, ctx.getLdapModel()); - Assert.assertEquals(0, syncResult.getFailed()); + Assertions.assertEquals(0, syncResult.getFailed()); }); testingClient.server().run(session -> { @@ -124,17 +124,17 @@ public void changeKerberosPrincipalWhenUserChangesInLDAPTest() throws Exception LDAPTestAsserts.assertUserImported(session.users(), testRealm, "hnelson2", "Horatio", "Nelson", "hnelson2@keycloak.org", null); UserModel updatedLocalUser = userProvider.getUserByUsername(testRealm, "hnelson2"); LDAPObject ldapUser = ctx.getLdapProvider().loadLDAPUserByUsername(testRealm, "hnelson2"); - Assert.assertNull(userProvider.getUserByUsername(testRealm, "hnelson")); + Assertions.assertNull(userProvider.getUserByUsername(testRealm, "hnelson")); // Assert UUID didn't change - Assert.assertEquals(updatedLocalUser.getAttributeStream(LDAPConstants.LDAP_ID).findFirst().get(), ldapUser.getUuid()); + Assertions.assertEquals(updatedLocalUser.getAttributeStream(LDAPConstants.LDAP_ID).findFirst().get(), ldapUser.getUuid()); // Assert Kerberos principal was changed in Keycloak - Assert.assertEquals(updatedLocalUser.getAttributeStream(KERBEROS_PRINCIPAL).findFirst().get(), ldapUser.getAttributeAsString(ctx.getLdapProvider().getKerberosConfig().getKerberosPrincipalAttribute())); + Assertions.assertEquals(updatedLocalUser.getAttributeStream(KERBEROS_PRINCIPAL).findFirst().get(), ldapUser.getAttributeAsString(ctx.getLdapProvider().getKerberosConfig().getKerberosPrincipalAttribute())); }); // login not possible with old user oauth.openLoginForm(); loginPage.login("hnelson", "secret2"); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); // login after update successful assertSuccessfulSpnegoLogin("hnelson2", "hnelson2", "secret2"); @@ -177,13 +177,13 @@ public void validatePasswordPolicyTest() throws Exception{ updateProviderValidatePasswordPolicy(true); - Assert.assertFalse(AccountHelper.updatePassword(testRealmResource(), "jduke", "jduke")); + Assertions.assertFalse(AccountHelper.updatePassword(testRealmResource(), "jduke", "jduke")); updateProviderValidatePasswordPolicy(false); - Assert.assertTrue(AccountHelper.updatePassword(testRealmResource(), "jduke", "jduke")); + Assertions.assertTrue(AccountHelper.updatePassword(testRealmResource(), "jduke", "jduke")); // Change password back - Assert.assertTrue(AccountHelper.updatePassword(testRealmResource(), "jduke", "theduke")); + Assertions.assertTrue(AccountHelper.updatePassword(testRealmResource(), "jduke", "theduke")); } @Test @@ -194,7 +194,7 @@ public void writableEditModeTest() throws Exception { updateProviderEditMode(UserStorageProvider.EditMode.WRITABLE); // Successfully change password now - Assert.assertTrue(AccountHelper.updatePassword(testRealmResource(), "jduke", "newPass")); + Assertions.assertTrue(AccountHelper.updatePassword(testRealmResource(), "jduke", "newPass")); // Only needed if you are providing a click thru to bypass kerberos. Currently there is a javascript // to forward the user if kerberos isn't enabled. @@ -203,14 +203,14 @@ public void writableEditModeTest() throws Exception { // Login with old password doesn't work, but with new password works - Assert.assertFalse(testAppHelper.login("jduke", "theduke")); - Assert.assertTrue(testAppHelper.login("jduke", "newPass")); + Assertions.assertFalse(testAppHelper.login("jduke", "theduke")); + Assertions.assertTrue(testAppHelper.login("jduke", "newPass")); // Assert SPNEGO login with the new password as mode is writable events.clear(); Response spnegoResponse = spnegoLogin("jduke", "newPass"); - org.keycloak.testsuite.Assert.assertEquals(302, spnegoResponse.getStatus()); - org.keycloak.testsuite.Assert.assertEquals(302, spnegoResponse.getStatus()); + Assertions.assertEquals(302, spnegoResponse.getStatus()); + Assertions.assertEquals(302, spnegoResponse.getStatus()); List users = testRealmResource().users().search("jduke", 0, 1); String userId = users.get(0).getId(); events.expectLogin() @@ -224,6 +224,6 @@ public void writableEditModeTest() throws Exception { assertAuthenticationSuccess(codeUrl); // Change password back - Assert.assertTrue(AccountHelper.updatePassword(testRealmResource(), "jduke", "theduke")); + Assertions.assertTrue(AccountHelper.updatePassword(testRealmResource(), "jduke", "theduke")); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosStandaloneCrossRealmTrustTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosStandaloneCrossRealmTrustTest.java index e1c4947d341a..f7840455bc76 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosStandaloneCrossRealmTrustTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosStandaloneCrossRealmTrustTest.java @@ -21,7 +21,6 @@ import org.keycloak.federation.kerberos.KerberosConfig; import org.keycloak.federation.kerberos.KerberosFederationProviderFactory; import org.keycloak.representations.idm.ComponentRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.KerberosEmbeddedServer; import org.keycloak.testsuite.util.KerberosRule; import org.keycloak.testsuite.util.TestAppHelper; @@ -30,6 +29,7 @@ import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; /** @@ -92,12 +92,12 @@ public void test02spnegoLoginDifferentRealmTest() throws Exception { public void test03SpnegoLoginWithCorrectKerberosPrincipalRealm() throws Exception { // Login in username/password form as "jduke@KEYCLOAK.ORG" TestAppHelper testAppHelper = new TestAppHelper(oauth, loginPage, appPage); - Assert.assertTrue(testAppHelper.login("jduke", "theduke")); - Assert.assertTrue(testAppHelper.logout()); + Assertions.assertTrue(testAppHelper.login("jduke", "theduke")); + Assertions.assertTrue(testAppHelper.logout()); // Login in username/password form as "jduke@KC2.COM" - Assert.assertTrue(testAppHelper.login("jduke@kc2.com", "theduke2")); - Assert.assertTrue(testAppHelper.logout()); + Assertions.assertTrue(testAppHelper.login("jduke@kc2.com", "theduke2")); + Assertions.assertTrue(testAppHelper.logout()); assertUser("jduke", "jduke@keycloak.org", null, null, "jduke@KEYCLOAK.ORG", false); assertUser("jduke@kc2.com", "jduke@kc2.com", null, null, "jduke@KC2.COM", false); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosStandaloneMultipleProvidersTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosStandaloneMultipleProvidersTest.java index 12abaf6ff845..7303d962b972 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosStandaloneMultipleProvidersTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosStandaloneMultipleProvidersTest.java @@ -31,7 +31,6 @@ import org.keycloak.representations.idm.ComponentRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.storage.ldap.LDAPStorageProviderFactory; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.KerberosEmbeddedServer; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.util.KerberosRule; @@ -40,6 +39,7 @@ import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; /** @@ -91,7 +91,7 @@ public void test01spnegoWith1stProviderBrokenKerberosConfiguration() throws Exce AccessTokenResponse tokenResponse = assertSuccessfulSpnegoLogin("hnelson2@KC2.COM", "hnelson2@kc2.com", "secret"); AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken()); - Assert.assertEquals(token.getEmail(), "hnelson2@kc2.com"); + Assertions.assertEquals(token.getEmail(), "hnelson2@kc2.com"); UserRepresentation user = assertUser("hnelson2@kc2.com", "hnelson2@kc2.com", null, null, "hnelson2@KC2.COM", false); assertUserStorageProvider(user, "kerberos-standalone"); } @@ -111,7 +111,7 @@ public void test02spnegoWith1stProviderBrokenLookupOfKerberosUser() throws Excep AccessTokenResponse tokenResponse = assertSuccessfulSpnegoLogin("hnelson2@KC2.COM", "hnelson2@kc2.com", "secret"); AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken()); - Assert.assertEquals(token.getEmail(), "hnelson2@kc2.com"); + Assertions.assertEquals(token.getEmail(), "hnelson2@kc2.com"); UserRepresentation user = assertUser("hnelson2@kc2.com", "hnelson2@kc2.com", null, null, "hnelson2@KC2.COM",false); assertUserStorageProvider(user, "kerberos-standalone"); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosStandaloneTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosStandaloneTest.java index f41eabf6614b..2b07397f1b18 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosStandaloneTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/kerberos/KerberosStandaloneTest.java @@ -63,6 +63,7 @@ import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.userprofile.UserProfileUtil.USER_METADATA_GROUP; @@ -118,17 +119,17 @@ public void updateProfileEnabledTest() throws Exception { // Switch updateProfileOnFirstLogin to on String parentId = testRealmResource().toRepresentation().getId(); List reps = testRealmResource().components().query(parentId, UserStorageProvider.class.getName()); - Assert.assertEquals(1, reps.size()); + Assertions.assertEquals(1, reps.size()); ComponentRepresentation kerberosProvider = reps.get(0); kerberosProvider.getConfig().putSingle(KerberosConstants.UPDATE_PROFILE_FIRST_LOGIN, "true"); testRealmResource().components().component(kerberosProvider.getId()).update(kerberosProvider); // Assert update profile page is displayed Response spnegoResponse = spnegoLogin("hnelson", "secret"); - Assert.assertEquals(200, spnegoResponse.getStatus()); + Assertions.assertEquals(200, spnegoResponse.getStatus()); String responseText = spnegoResponse.readEntity(String.class); - Assert.assertTrue(responseText.contains("You need to update your user profile to activate your account.")); - Assert.assertTrue(responseText.contains("hnelson@" + kerberosRule.getConfig().get(KerberosConstants.KERBEROS_REALM).toLowerCase())); + Assertions.assertTrue(responseText.contains("You need to update your user profile to activate your account.")); + Assertions.assertTrue(responseText.contains("hnelson@" + kerberosRule.getConfig().get(KerberosConstants.KERBEROS_REALM).toLowerCase())); spnegoResponse.close(); // Assert user was imported and has required action on him @@ -152,7 +153,7 @@ public void updateProfileEnabledTest() throws Exception { public void noProvider() throws Exception { String parentId = testRealmResource().toRepresentation().getId(); List reps = testRealmResource().components().query(parentId, UserStorageProvider.class.getName()); - Assert.assertEquals(1, reps.size()); + Assertions.assertEquals(1, reps.size()); ComponentRepresentation kerberosProvider = reps.get(0); testRealmResource().components().component(kerberosProvider.getId()).remove(); @@ -166,7 +167,7 @@ public void noProvider() throws Exception { String context = spnegoResponse.readEntity(String.class); spnegoResponse.close(); - Assert.assertTrue(context.contains("Sign in to test")); + Assertions.assertTrue(context.contains("Sign in to test")); String url = ActionURIUtils.getActionURIFromPageSource(context); @@ -199,7 +200,7 @@ public void handleUnknownKerberosRealm() throws Exception { // Switch kerberos realm to "unavailable String parentId = testRealmResource().toRepresentation().getId(); List reps = testRealmResource().components().query(parentId, UserStorageProvider.class.getName()); - Assert.assertEquals(1, reps.size()); + Assertions.assertEquals(1, reps.size()); ComponentRepresentation kerberosProvider = reps.get(0); kerberosProvider.getConfig().putSingle(KerberosConstants.KERBEROS_REALM, "unavailable"); testRealmResource().components().component(kerberosProvider.getId()).update(kerberosProvider); @@ -208,9 +209,9 @@ public void handleUnknownKerberosRealm() throws Exception { UserRepresentation john = new UserRepresentation(); john.setUsername("john"); Response response = testRealmResource().users().create(john); - Assert.assertEquals(400, response.getStatus()); + Assertions.assertEquals(400, response.getStatus()); ErrorRepresentation error = response.readEntity(ErrorRepresentation.class); - Assert.assertEquals("Could not create user", error.getErrorMessage()); + Assertions.assertEquals("Could not create user", error.getErrorMessage()); response.close(); } @@ -225,18 +226,18 @@ public void testUserProfile() throws Exception { // KERBEROS_PRINCIPAL attribute should be read-only and should be in "User metadata" group UserProfileAttributeMetadata krbPrincipalAttribute = john.getUserProfileMetadata().getAttributeMetadata(KerberosConstants.KERBEROS_PRINCIPAL); - Assert.assertTrue(krbPrincipalAttribute.isReadOnly()); - Assert.assertEquals(USER_METADATA_GROUP, krbPrincipalAttribute.getGroup()); + Assertions.assertTrue(krbPrincipalAttribute.isReadOnly()); + Assertions.assertEquals(USER_METADATA_GROUP, krbPrincipalAttribute.getGroup()); // Test Update profile john.getRequiredActions().add(UserModel.RequiredAction.UPDATE_PROFILE.toString()); johnResource.update(john); Response spnegoResponse = spnegoLogin("hnelson", "secret"); - Assert.assertEquals(200, spnegoResponse.getStatus()); + Assertions.assertEquals(200, spnegoResponse.getStatus()); String responseText = spnegoResponse.readEntity(String.class); - Assert.assertTrue(responseText.contains("You need to update your user profile to activate your account.")); - Assert.assertFalse(responseText.contains("KERBEROS_PRINCIPAL")); + Assertions.assertTrue(responseText.contains("You need to update your user profile to activate your account.")); + Assertions.assertFalse(responseText.contains("KERBEROS_PRINCIPAL")); spnegoResponse.close(); john.getRequiredActions().remove(UserModel.RequiredAction.UPDATE_PROFILE.toString()); @@ -249,12 +250,12 @@ public void testResetCredentials() throws Exception { String resetUri = OAuthClient.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials"; String actionUri; try (Response response = client.target(resetUri).queryParam(Constants.CLIENT_ID, oauth.getClientId()).request().get()) { - Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); Document theResponsePage = Jsoup.parse(response.readEntity(String.class)); Elements forms = theResponsePage.select("form[id=kc-reset-password-form]"); - Assert.assertEquals(1, forms.size()); + Assertions.assertEquals(1, forms.size()); actionUri = forms.get(0).attr("action"); - Assert.assertNotNull(actionUri); + Assertions.assertNotNull(actionUri); } // continue the reset providing the user to change email @@ -262,13 +263,13 @@ public void testResetCredentials() throws Exception { Form form = new Form(); form.param("username", "test-user@localhost"); try (Response response = client.target(actionUri).request().post(Entity.form(form))) { - Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); MatcherAssert.assertThat(response.readEntity(String.class), Matchers.containsString("You should receive an email shortly with further instructions.")); } // get the email from green mail MimeMessage message = greenMail.getLastReceivedMessage(); - Assert.assertNotNull(message); + Assertions.assertNotNull(message); String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message); // perform the password change using the email url @@ -279,7 +280,7 @@ public void testResetCredentials() throws Exception { events.poll(); events.expectRequiredAction(EventType.UPDATE_PASSWORD).detail(Details.CREDENTIAL_TYPE, PasswordCredentialModel.TYPE).client(oauth.getClientId()).detail(Details.USERNAME, "test-user@localhost"); infoPage.assertCurrent(); - Assert.assertEquals("Your account has been updated.", infoPage.getInfo()); + Assertions.assertEquals("Your account has been updated.", infoPage.getInfo()); } @Test @@ -294,7 +295,7 @@ public void testRemoveUserTest() throws Exception { try { johnResource.toRepresentation(true); - Assert.fail("should remove the user"); + Assertions.fail("should remove the user"); } catch (NotFoundException expected) { } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/AbstractLDAPTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/AbstractLDAPTest.java index 7d5feb6255cc..6dda8cf4dd4f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/AbstractLDAPTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/AbstractLDAPTest.java @@ -23,7 +23,6 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.storage.ldap.mappers.LDAPStorageMapper; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.pages.AppPage; import org.keycloak.testsuite.pages.LoginPage; @@ -34,6 +33,7 @@ import org.jboss.arquillian.graphene.page.Page; import org.junit.Rule; +import org.junit.jupiter.api.Assertions; /** * @author Marek Posolda @@ -80,7 +80,7 @@ public void importTestRealms() { protected void createLDAPProvider() { Map cfg = getLDAPRule().getConfig(); ldapModelId = testingClient.testing().ldap(TEST_REALM_NAME).createLDAPProvider(cfg, isImportEnabled()); - Assert.assertEquals("Short ID not used for ldap id", 22, ldapModelId.length()); + Assertions.assertEquals(22, ldapModelId.length(), "Short ID not used for ldap id"); log.infof("LDAP Provider created"); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPAccountRestApiTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPAccountRestApiTest.java index 5219448ceee5..61718502a952 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPAccountRestApiTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPAccountRestApiTest.java @@ -45,17 +45,17 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Marek Posolda @@ -128,19 +128,19 @@ public void testUpdateProfile() throws IOException { UserRepresentation user = getProfile(); // Metadata attributes like LDAP_ID are not present - Assert.assertNull(user.getAttributes()); + Assertions.assertNull(user.getAttributes()); org.keycloak.representations.idm.UserRepresentation adminRestUserRep = testRealm().users() .search(user.getUsername()).get(0); List origLdapId = adminRestUserRep.getAttributes().get(LDAPConstants.LDAP_ID); List origLdapEntryDn = adminRestUserRep.getAttributes().get(LDAPConstants.LDAP_ENTRY_DN); - Assert.assertNotNull(origLdapId.get(0)); - Assert.assertNotNull(origLdapEntryDn.get(0)); + Assertions.assertNotNull(origLdapId.get(0)); + Assertions.assertNotNull(origLdapEntryDn.get(0)); adminRestUserRep = testRealm().users().get(adminRestUserRep.getId()).toRepresentation(); origLdapId = adminRestUserRep.getAttributes().get(LDAPConstants.LDAP_ID); origLdapEntryDn = adminRestUserRep.getAttributes().get(LDAPConstants.LDAP_ENTRY_DN); - Assert.assertNotNull(origLdapId.get(0)); - Assert.assertNotNull(origLdapEntryDn.get(0)); + Assertions.assertNotNull(origLdapId.get(0)); + Assertions.assertNotNull(origLdapEntryDn.get(0)); // Trying to add KERBEROS_PRINCIPAL (Adding attribute, which was not yet present). Request does not fail, but attribute is not updated user.setFirstName("JohnUpdated"); @@ -148,9 +148,9 @@ public void testUpdateProfile() throws IOException { user.singleAttribute(KerberosFederationProvider.KERBEROS_PRINCIPAL, "foo"); updateProfileExpectSuccess(user); user = getProfile(); - Assert.assertEquals("JohnUpdated", user.getFirstName()); - Assert.assertEquals("DoeUpdated", user.getLastName()); - Assert.assertNull(user.getAttributes()); + Assertions.assertEquals("JohnUpdated", user.getFirstName()); + Assertions.assertEquals("DoeUpdated", user.getLastName()); + Assertions.assertNull(user.getAttributes()); // Trying to update LDAP_ID should fail (Updating existing attribute, which is present on the user even if not visible to the user) user.singleAttribute(LDAPConstants.LDAP_ID, "123"); @@ -160,7 +160,7 @@ public void testUpdateProfile() throws IOException { user.getAttributes().remove(LDAPConstants.LDAP_ID); updateProfileExpectSuccess(user); user = getProfile(); - Assert.assertNull(user.getAttributes()); + Assertions.assertNull(user.getAttributes()); // Trying to update LDAP_ENTRY_DN should fail user.singleAttribute(LDAPConstants.LDAP_ENTRY_DN, "ou=foo,dc=bar"); @@ -173,7 +173,7 @@ public void testUpdateProfile() throws IOException { user = getProfile(); assertEquals("JohnUpdated", user.getFirstName()); assertEquals("DoeUpdated", user.getLastName()); - Assert.assertNull(user.getAttributes()); + Assertions.assertNull(user.getAttributes()); // Revert user.setFirstName("John"); @@ -191,14 +191,14 @@ public void testUpdateProfileUnmanagedAttributes() throws IOException { UserRepresentation user = getProfile(); // Metadata attributes like LDAP_ID are not present - Assert.assertNull(user.getAttributes()); + Assertions.assertNull(user.getAttributes()); org.keycloak.representations.idm.UserRepresentation adminRestUserRep = testRealm().users() .search(user.getUsername()).get(0); List origLdapId = adminRestUserRep.getAttributes().get(LDAPConstants.LDAP_ID); List origLdapEntryDn = adminRestUserRep.getAttributes().get(LDAPConstants.LDAP_ENTRY_DN); - Assert.assertNotNull(origLdapId.get(0)); - Assert.assertNotNull(origLdapEntryDn.get(0)); + Assertions.assertNotNull(origLdapId.get(0)); + Assertions.assertNotNull(origLdapEntryDn.get(0)); // Trying to add KERBEROS_PRINCIPAL should fail (Adding attribute, which was not yet present) user.setFirstName("JohnUpdated"); @@ -226,12 +226,12 @@ public void testUpdateProfileUnmanagedAttributes() throws IOException { user.getAttributes().remove(LDAPConstants.LDAP_ID); updateProfileExpectSuccess(user); user = getProfile(); - Assert.assertNull(user.getAttributes()); + Assertions.assertNull(user.getAttributes()); user = getProfile(); assertEquals("JohnUpdated", user.getFirstName()); assertEquals("DoeUpdated", user.getLastName()); - Assert.assertNull(user.getAttributes()); + Assertions.assertNull(user.getAttributes()); // Revert user.setFirstName("John"); @@ -247,15 +247,15 @@ public void testGetCredentials() throws IOException { List credentials = getCredentials(); AccountCredentialResource.CredentialContainer password = credentials.get(0); - Assert.assertEquals(PasswordCredentialModel.TYPE, password.getType()); - Assert.assertEquals(1, password.getUserCredentialMetadatas().size()); + Assertions.assertEquals(PasswordCredentialModel.TYPE, password.getType()); + Assertions.assertEquals(1, password.getUserCredentialMetadatas().size()); CredentialRepresentation userPassword = password.getUserCredentialMetadatas().get(0).getCredential(); // Password won't have createdDate and any metadata set - Assert.assertEquals(PasswordCredentialModel.TYPE, userPassword.getType()); - Assert.assertTrue(userPassword.getCreatedDate() > -1L); - Assert.assertNull(userPassword.getCredentialData()); - Assert.assertNull(userPassword.getSecretData()); + Assertions.assertEquals(PasswordCredentialModel.TYPE, userPassword.getType()); + Assertions.assertTrue(userPassword.getCreatedDate() > -1L); + Assertions.assertNull(userPassword.getCredentialData()); + Assertions.assertNull(userPassword.getSecretData()); } @@ -302,7 +302,7 @@ public void testIgnoreReadOnlyAttributes() throws IOException { assertFalse(usernew.isEmailVerified()); // No metadata attributes like LDAP_ID or LDAP_ENTRY_DN present in account REST API - Assert.assertNull(usernew.getAttributes()); + Assertions.assertNull(usernew.getAttributes()); //clean up usernew.setEmail("john@email.org"); @@ -321,7 +321,7 @@ public void testIgnoreReadOnlyAttributes() throws IOException { usernew = SimpleHttpDefault.doGet(getAccountUrl(null), httpClient).auth(tokenUtil.getToken()).asJson(UserRepresentation.class); // Metadata attributes still not present in account REST - Assert.assertNull(usernew.getAttributes()); + Assertions.assertNull(usernew.getAttributes()); // Metadata attributes still present in admin REST API userRep = testRealm().users().search(usernew.getUsername()).get(0); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPAdminRestApiTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPAdminRestApiTest.java index 93ebb270f2a8..02266700520c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPAdminRestApiTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPAdminRestApiTest.java @@ -46,10 +46,10 @@ import org.keycloak.testsuite.util.LDAPTestUtils; import org.keycloak.testsuite.util.UserBuilder; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import static org.keycloak.testsuite.util.userprofile.UserProfileUtil.setUserProfileConfiguration; @@ -59,11 +59,11 @@ import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @@ -151,8 +151,8 @@ public void updateUserWithAdminRest() throws Exception { List origLdapId = new ArrayList<>(user.getAttributes().get(LDAPConstants.LDAP_ID)); List origLdapEntryDn = new ArrayList<>(user.getAttributes().get(LDAPConstants.LDAP_ENTRY_DN)); - Assert.assertEquals(1, origLdapId.size()); - Assert.assertEquals(1, origLdapEntryDn.size()); + Assertions.assertEquals(1, origLdapId.size()); + Assertions.assertEquals(1, origLdapEntryDn.size()); assertThat(user.getAttributes().keySet(), not(contains(KerberosFederationProvider.KERBEROS_PRINCIPAL))); // Trying to add KERBEROS_PRINCIPAL should fail (Adding attribute, which was not yet present) @@ -217,14 +217,14 @@ private String createUserExpectSuccess(UserRepresentation user) { private void createUserExpectError(UserRepresentation user) { Response response = testRealm().users().create(user); - Assert.assertEquals(400, response.getStatus()); + Assertions.assertEquals(400, response.getStatus()); response.close(); } private void updateUserExpectError(UserResource userRes, UserRepresentation user) { try { userRes.update(user); - Assert.fail("Not expected to successfully update user"); + Assertions.fail("Not expected to successfully update user"); } catch (BadRequestException e) { // Expected } @@ -267,7 +267,7 @@ public void testErrorResponseWhenLdapIsFailing() { try { user1.setFirstName(user1.getFirstName() + " updated"); userResource.update(user1); - Assert.fail("Not expected to successfully update user"); + Assertions.fail("Not expected to successfully update user"); } catch (WebApplicationException expected) { Response response = expected.getResponse(); ErrorRepresentation error = response.readEntity(ErrorRepresentation.class); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPBinaryAttributesTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPBinaryAttributesTest.java index bbf6b8410e8e..7f6548e05a82 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPBinaryAttributesTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPBinaryAttributesTest.java @@ -50,10 +50,10 @@ import org.keycloak.validate.validators.LengthValidator; import org.junit.After; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import static org.hamcrest.CoreMatchers.equalTo; @@ -124,7 +124,7 @@ public void test01InvalidMapperConfiguration() { ldapComponentMapper.put(UserAttributeLDAPStorageMapper.IS_BINARY_ATTRIBUTE, true); try { appRealm.updateComponent(ldapComponentMapper); - Assert.fail("Not expected to successfully update mapper"); + Assertions.fail("Not expected to successfully update mapper"); } catch (ComponentValidationException cve) { // Expected } @@ -273,15 +273,15 @@ public Stream getAttributeStream(String name) { private UserRepresentation getUserAndAssertPhoto(String username, boolean isPhotoExpected) { List johns = adminClient.realm("test").users().search(username, 0, 10); - Assert.assertEquals(1, johns.size()); + Assertions.assertEquals(1, johns.size()); UserRepresentation john = johns.get(0); - Assert.assertEquals(username, john.getUsername()); - Assert.assertTrue(john.getAttributes().containsKey(LDAPConstants.LDAP_ID)); // Doublecheck it's the LDAP mapped user + Assertions.assertEquals(username, john.getUsername()); + Assertions.assertTrue(john.getAttributes().containsKey(LDAPConstants.LDAP_ID)); // Doublecheck it's the LDAP mapped user if (isPhotoExpected) { - Assert.assertEquals(JPEG_PHOTO_BASE64, john.getAttributes().get(LDAPConstants.JPEG_PHOTO).get(0)); + Assertions.assertEquals(JPEG_PHOTO_BASE64, john.getAttributes().get(LDAPConstants.JPEG_PHOTO).get(0)); } else { - Assert.assertFalse(john.getAttributes().containsKey(LDAPConstants.JPEG_PHOTO)); + Assertions.assertFalse(john.getAttributes().containsKey(LDAPConstants.JPEG_PHOTO)); } return john; } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPExternalChangesTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPExternalChangesTest.java index 63cb9b16a59f..3df189811dbc 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPExternalChangesTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPExternalChangesTest.java @@ -35,9 +35,9 @@ import org.junit.Test; import org.junit.runners.MethodSorters; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class LDAPExternalChangesTest extends AbstractLDAPTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapper2WaySyncTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapper2WaySyncTest.java index 0b909b161827..1a7ea03d2497 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapper2WaySyncTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapper2WaySyncTest.java @@ -31,11 +31,11 @@ import org.keycloak.testsuite.util.LDAPRule; import org.keycloak.testsuite.util.LDAPTestUtils; -import org.junit.Assert; import org.junit.Before; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; /** @@ -120,9 +120,9 @@ public void test01_syncNoPreserveGroupInheritance() throws Exception { // Delete all KC groups now removeAllModelGroups(realm); - Assert.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1")); - Assert.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group11")); - Assert.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group2")); + Assertions.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1")); + Assertions.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group11")); + Assertions.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group2")); }); @@ -151,12 +151,12 @@ public void test01_syncNoPreserveGroupInheritance() throws Exception { GroupModel kcGroup12 = KeycloakModelUtils.findGroupByPath(session, realm, "/group12"); GroupModel kcGroup2 = KeycloakModelUtils.findGroupByPath(session, realm, "/group2"); - Assert.assertEquals(0, kcGroup1.getSubGroupsStream().count()); + Assertions.assertEquals(0, kcGroup1.getSubGroupsStream().count()); - Assert.assertEquals("group1 - description1", kcGroup1.getFirstAttribute(descriptionAttrName)); - Assert.assertNull(kcGroup11.getFirstAttribute(descriptionAttrName)); - Assert.assertEquals("group12 - description12", kcGroup12.getFirstAttribute(descriptionAttrName)); - Assert.assertNull(kcGroup2.getFirstAttribute(descriptionAttrName)); + Assertions.assertEquals("group1 - description1", kcGroup1.getFirstAttribute(descriptionAttrName)); + Assertions.assertNull(kcGroup11.getFirstAttribute(descriptionAttrName)); + Assertions.assertEquals("group12 - description12", kcGroup12.getFirstAttribute(descriptionAttrName)); + Assertions.assertNull(kcGroup2.getFirstAttribute(descriptionAttrName)); // test drop non-existing works testDropNonExisting(session, ctx, mapperModel); @@ -188,9 +188,9 @@ public void test02_syncWithGroupInheritance() throws Exception { // Delete all KC groups now removeAllModelGroups(realm); - Assert.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1")); - Assert.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group11")); - Assert.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group2")); + Assertions.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1")); + Assertions.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group11")); + Assertions.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group2")); }); @@ -213,12 +213,12 @@ public void test02_syncWithGroupInheritance() throws Exception { GroupModel kcGroup12 = KeycloakModelUtils.findGroupByPath(session, realm, "/group1/group12"); GroupModel kcGroup2 = KeycloakModelUtils.findGroupByPath(session, realm, "/group2"); - Assert.assertEquals(2, kcGroup1.getSubGroupsStream().count()); + Assertions.assertEquals(2, kcGroup1.getSubGroupsStream().count()); - Assert.assertEquals("group1 - description1", kcGroup1.getFirstAttribute(descriptionAttrName)); - Assert.assertNull(kcGroup11.getFirstAttribute(descriptionAttrName)); - Assert.assertEquals("group12 - description12", kcGroup12.getFirstAttribute(descriptionAttrName)); - Assert.assertNull(kcGroup2.getFirstAttribute(descriptionAttrName)); + Assertions.assertEquals("group1 - description1", kcGroup1.getFirstAttribute(descriptionAttrName)); + Assertions.assertNull(kcGroup11.getFirstAttribute(descriptionAttrName)); + Assertions.assertEquals("group12 - description12", kcGroup12.getFirstAttribute(descriptionAttrName)); + Assertions.assertNull(kcGroup2.getFirstAttribute(descriptionAttrName)); // test drop non-existing works testDropNonExisting(session, ctx, mapperModel); @@ -239,7 +239,7 @@ private static void testDropNonExisting(KeycloakSession session, LDAPTestContext // Sync and assert our group is still in LDAP SynchronizationResult syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromKeycloakToFederationProvider(realm); LDAPTestAsserts.assertSyncEquals(syncResult, 0, 4, 0, 0); - Assert.assertNotNull(LDAPTestUtils.getGroupMapper(mapperModel, ctx.getLdapProvider(), realm).loadLDAPGroupByName("group3")); + Assertions.assertNotNull(LDAPTestUtils.getGroupMapper(mapperModel, ctx.getLdapProvider(), realm).loadLDAPGroupByName("group3")); // Change config to drop non-existing groups LDAPTestUtils.updateConfigOptions(mapperModel, GroupMapperConfig.DROP_NON_EXISTING_GROUPS_DURING_SYNC, "true"); @@ -248,6 +248,6 @@ private static void testDropNonExisting(KeycloakSession session, LDAPTestContext // Sync and assert group removed from LDAP syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromKeycloakToFederationProvider(realm); LDAPTestAsserts.assertSyncEquals(syncResult, 0, 4, 1, 0); - Assert.assertNull(LDAPTestUtils.getGroupMapper(mapperModel, ctx.getLdapProvider(), realm).loadLDAPGroupByName("group3")); + Assertions.assertNull(LDAPTestUtils.getGroupMapper(mapperModel, ctx.getLdapProvider(), realm).loadLDAPGroupByName("group3")); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperSyncTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperSyncTest.java index 54a139c6d458..9623ef5aa1a9 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperSyncTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperSyncTest.java @@ -48,13 +48,13 @@ import org.keycloak.testsuite.util.LDAPTestUtils; import org.jboss.logging.Logger; -import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import static org.keycloak.testsuite.util.LDAPTestUtils.getGroupDescriptionLDAPAttrName; @@ -129,9 +129,9 @@ private void testSyncNoPreserveGroupInheritance() throws Exception { try { new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(realm); - Assert.fail("Not expected group sync to pass"); + Assertions.fail("Not expected group sync to pass"); } catch (ModelException expected) { - Assert.assertTrue(expected.getMessage().contains("Recursion detected")); + Assertions.assertTrue(expected.getMessage().contains("Recursion detected")); } }); @@ -169,11 +169,11 @@ private void testSyncNoPreserveGroupInheritance() throws Exception { GroupModel kcGroup11 = KeycloakModelUtils.findGroupByPath(session, realm, "/group11"); GroupModel kcGroup12 = KeycloakModelUtils.findGroupByPath(session, realm, "/group12"); - Assert.assertEquals(0, kcGroup1.getSubGroupsStream().count()); + Assertions.assertEquals(0, kcGroup1.getSubGroupsStream().count()); - Assert.assertEquals("group1 - description", kcGroup1.getFirstAttribute(descriptionAttrName)); - Assert.assertNull(kcGroup11.getFirstAttribute(descriptionAttrName)); - Assert.assertEquals("group12 - description", kcGroup12.getFirstAttribute(descriptionAttrName)); + Assertions.assertEquals("group1 - description", kcGroup1.getFirstAttribute(descriptionAttrName)); + Assertions.assertNull(kcGroup11.getFirstAttribute(descriptionAttrName)); + Assertions.assertEquals("group12 - description", kcGroup12.getFirstAttribute(descriptionAttrName)); // Cleanup - remove recursive mapping in LDAP LDAPObject group1 = groupMapper.loadLDAPGroupByName("group1"); @@ -235,7 +235,7 @@ public void test03_syncWithGroupInheritance() throws Exception { // KEYCLOAK-11415 - This test requires the group mapper to be configured with preserve group inheritance // set to 'true' (the default setting). If preservation of group inheritance isn't configured, some of // the previous test(s) failed to cleanup properly. Check the requirement as part of running the test - Assert.assertEquals(mapperModel.getConfig().getFirst("preserve.group.inheritance"), "true"); + Assertions.assertEquals(mapperModel.getConfig().getFirst("preserve.group.inheritance"), "true"); // Sync groups with inheritance SynchronizationResult syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(realm); @@ -243,16 +243,16 @@ public void test03_syncWithGroupInheritance() throws Exception { // Assert groups are imported to keycloak including their inheritance from LDAP GroupModel kcGroup1 = KeycloakModelUtils.findGroupByPath(session, realm, "/group1"); - Assert.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group11")); - Assert.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group12")); + Assertions.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group11")); + Assertions.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group12")); GroupModel kcGroup11 = KeycloakModelUtils.findGroupByPath(session, realm, "/group1/group11"); GroupModel kcGroup12 = KeycloakModelUtils.findGroupByPath(session, realm, "/group1/group12"); - Assert.assertEquals(2, kcGroup1.getSubGroupsStream().count()); + Assertions.assertEquals(2, kcGroup1.getSubGroupsStream().count()); - Assert.assertEquals("group1 - description", kcGroup1.getFirstAttribute(descriptionAttrName)); - Assert.assertNull(kcGroup11.getFirstAttribute(descriptionAttrName)); - Assert.assertEquals("group12 - description", kcGroup12.getFirstAttribute(descriptionAttrName)); + Assertions.assertEquals("group1 - description", kcGroup1.getFirstAttribute(descriptionAttrName)); + Assertions.assertNull(kcGroup11.getFirstAttribute(descriptionAttrName)); + Assertions.assertEquals("group12 - description", kcGroup12.getFirstAttribute(descriptionAttrName)); // Update description attributes in LDAP LDAPObject group1 = groupMapper.loadLDAPGroupByName("group1"); @@ -270,8 +270,8 @@ public void test03_syncWithGroupInheritance() throws Exception { // Assert attributes changed in keycloak kcGroup1 = KeycloakModelUtils.findGroupByPath(session, realm, "/group1"); kcGroup12 = KeycloakModelUtils.findGroupByPath(session, realm, "/group1/group12"); - Assert.assertEquals("group1 - changed description", kcGroup1.getFirstAttribute(descriptionAttrName)); - Assert.assertNull(kcGroup12.getFirstAttribute(descriptionAttrName)); + Assertions.assertEquals("group1 - changed description", kcGroup1.getFirstAttribute(descriptionAttrName)); + Assertions.assertNull(kcGroup12.getFirstAttribute(descriptionAttrName)); }); } @@ -288,7 +288,7 @@ public void test04_syncWithDropNonExistingGroups() throws Exception { // KEYCLOAK-11415 - This test requires the group mapper to be configured with preserve group inheritance // set to 'true' (the default setting). If preservation of group inheritance isn't configured, some of // the previous test(s) failed to cleanup properly. Check the requirement as part of running the test - Assert.assertEquals(mapperModel.getConfig().getFirst("preserve.group.inheritance"), "true"); + Assertions.assertEquals(mapperModel.getConfig().getFirst("preserve.group.inheritance"), "true"); // Sync groups with inheritance SynchronizationResult syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(realm); @@ -296,10 +296,10 @@ public void test04_syncWithDropNonExistingGroups() throws Exception { // Assert groups are imported to keycloak including their inheritance from LDAP GroupModel kcGroup1 = KeycloakModelUtils.findGroupByPath(session, realm, "/group1"); - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1/group11")); - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1/group12")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1/group11")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1/group12")); - Assert.assertEquals(2, kcGroup1.getSubGroupsStream().count()); + Assertions.assertEquals(2, kcGroup1.getSubGroupsStream().count()); // Create some new groups in keycloak GroupModel model1 = realm.createGroup("model1"); @@ -309,10 +309,10 @@ public void test04_syncWithDropNonExistingGroups() throws Exception { syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(realm); LDAPTestAsserts.assertSyncEquals(syncResult, 0, 3, 0, 0); - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1/group11")); - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1/group12")); - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/model1")); - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1/model2")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1/group11")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1/group12")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/model1")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1/model2")); // Update group mapper to drop non-existing groups during sync LDAPTestUtils.updateConfigOptions(mapperModel, GroupMapperConfig.DROP_NON_EXISTING_GROUPS_DURING_SYNC, "true"); @@ -320,14 +320,14 @@ public void test04_syncWithDropNonExistingGroups() throws Exception { // Sync groups again from LDAP. Assert LDAP non-existing groups deleted syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(realm); - Assert.assertEquals(3, syncResult.getUpdated()); - Assert.assertTrue(syncResult.getRemoved() == 2); + Assertions.assertEquals(3, syncResult.getUpdated()); + Assertions.assertTrue(syncResult.getRemoved() == 2); // Sync and assert groups updated - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1/group11")); - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1/group12")); - Assert.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/model1")); - Assert.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1/model2")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1/group11")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1/group12")); + Assertions.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/model1")); + Assertions.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1/model2")); }); } @@ -362,9 +362,9 @@ public void test05_syncNoPreserveGroupInheritanceWithLazySync() throws Exception groupMapperConfig.getMembershipUserLdapAttribute(ldapProvider.getLdapIdentityStore().getConfig()), ldapGroup, johnLdap); // Assert groups not yet imported to Keycloak DB - Assert.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1")); - Assert.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group11")); - Assert.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group12")); + Assertions.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group1")); + Assertions.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group11")); + Assertions.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, "/group12")); // Load user from LDAP to Keycloak DB UserModel john = session.users().getUserByUsername(realm, "johnkeycloak"); @@ -374,12 +374,12 @@ public void test05_syncNoPreserveGroupInheritanceWithLazySync() throws Exception GroupModel group1 = KeycloakModelUtils.findGroupByPath(session, realm, "/group1"); GroupModel group11 = KeycloakModelUtils.findGroupByPath(session, realm, "/group11"); GroupModel group12 = KeycloakModelUtils.findGroupByPath(session, realm, "/group12"); - Assert.assertNull(group1); - Assert.assertNotNull(group11); - Assert.assertNull(group12); + Assertions.assertNull(group1); + Assertions.assertNotNull(group11); + Assertions.assertNull(group12); - Assert.assertEquals(1, johnGroups.size()); - Assert.assertTrue(johnGroups.contains(group11)); + Assertions.assertEquals(1, johnGroups.size()); + Assertions.assertTrue(johnGroups.contains(group11)); // Delete group mapping john.leaveGroup(group11); @@ -404,7 +404,7 @@ public void test06SyncRestAPI() { try { // testing KEYCLOAK-3980 which threw an NPE because I was looking up the factory wrong. SynchronizationResultRepresentation syncResultRep = adminClient.realm("test").userStorage().syncMapperData( ldapModelId, groupMapperRep.getId(), "error"); - Assert.fail("Should throw 400"); + Assertions.fail("Should throw 400"); } catch (BadRequestException e) { } } @@ -524,9 +524,9 @@ public void test08_flatSynchWithBatchSizeLessThanNumberOfGroups() { ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(realm, ctx.getLdapModel(), "groupsMapper"); // check right config is in place. - Assert.assertEquals(ctx.getLdapModel().getConfig().getFirst(LDAPConstants.PAGINATION), "true"); - Assert.assertEquals(ctx.getLdapModel().getConfig().getFirst(LDAPConstants.BATCH_SIZE_FOR_SYNC), "1"); - Assert.assertEquals(mapperModel.getConfig().getFirst(GroupMapperConfig.PRESERVE_GROUP_INHERITANCE), "false"); + Assertions.assertEquals(ctx.getLdapModel().getConfig().getFirst(LDAPConstants.PAGINATION), "true"); + Assertions.assertEquals(ctx.getLdapModel().getConfig().getFirst(LDAPConstants.BATCH_SIZE_FOR_SYNC), "1"); + Assertions.assertEquals(mapperModel.getConfig().getFirst(GroupMapperConfig.PRESERVE_GROUP_INHERITANCE), "false"); // synch groups a first time - imports all new groups into keycloak. LDAPStorageMapper groupMapper = new GroupLDAPStorageMapperFactory().create(session, mapperModel); @@ -536,8 +536,8 @@ public void test08_flatSynchWithBatchSizeLessThanNumberOfGroups() { // check all groups were imported as top level groups with no subgroups. Stream.of("/group1", "/group11", "/group12").forEach(path -> { GroupModel kcGroup = KeycloakModelUtils.findGroupByPath(session, realm, path); - Assert.assertNotNull(kcGroup); - Assert.assertEquals(0, kcGroup.getSubGroupsStream().count()); + Assertions.assertNotNull(kcGroup); + Assertions.assertEquals(0, kcGroup.getSubGroupsStream().count()); }); // re-synch groups, updating previously imported groups. diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperSyncWithGroupsPathTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperSyncWithGroupsPathTest.java index fb0687d866b2..5c0d7c9fda4d 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperSyncWithGroupsPathTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperSyncWithGroupsPathTest.java @@ -40,11 +40,11 @@ import org.keycloak.testsuite.util.LDAPRule; import org.keycloak.testsuite.util.LDAPTestUtils; -import org.junit.Assert; import org.junit.Before; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; @FixMethodOrder(MethodSorters.NAME_ASCENDING) @@ -118,7 +118,7 @@ public void test01_syncWithGroupInheritance() { // KEYCLOAK-11415 - This test requires the group mapper to be configured with preserve group inheritance // set to 'true' (the default setting). If preservation of group inheritance isn't configured, some of // the previous test(s) failed to cleanup properly. Check the requirement as part of running the test - Assert.assertEquals(mapperModel.getConfig().getFirst("preserve.group.inheritance"), "true"); + Assertions.assertEquals(mapperModel.getConfig().getFirst("preserve.group.inheritance"), "true"); // Sync groups with inheritance SynchronizationResult syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(realm); @@ -126,16 +126,16 @@ public void test01_syncWithGroupInheritance() { // Assert groups are imported to keycloak including their inheritance from LDAP GroupModel kcGroup1 = KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1"); - Assert.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group11")); - Assert.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group12")); + Assertions.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group11")); + Assertions.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group12")); GroupModel kcGroup11 = KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/group11"); GroupModel kcGroup12 = KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/group12"); - Assert.assertEquals(2, kcGroup1.getSubGroupsStream().count()); + Assertions.assertEquals(2, kcGroup1.getSubGroupsStream().count()); - Assert.assertEquals("group1 - description", kcGroup1.getFirstAttribute(descriptionAttrName)); - Assert.assertNull(kcGroup11.getFirstAttribute(descriptionAttrName)); - Assert.assertEquals("group12 - description", kcGroup12.getFirstAttribute(descriptionAttrName)); + Assertions.assertEquals("group1 - description", kcGroup1.getFirstAttribute(descriptionAttrName)); + Assertions.assertNull(kcGroup11.getFirstAttribute(descriptionAttrName)); + Assertions.assertEquals("group12 - description", kcGroup12.getFirstAttribute(descriptionAttrName)); // Update description attributes in LDAP LDAPObject group1 = groupMapper.loadLDAPGroupByName("group1"); @@ -153,8 +153,8 @@ public void test01_syncWithGroupInheritance() { // Assert attributes changed in keycloak kcGroup1 = KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1"); kcGroup12 = KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/group12"); - Assert.assertEquals("group1 - changed description", kcGroup1.getFirstAttribute(descriptionAttrName)); - Assert.assertNull(kcGroup12.getFirstAttribute(descriptionAttrName)); + Assertions.assertEquals("group1 - changed description", kcGroup1.getFirstAttribute(descriptionAttrName)); + Assertions.assertNull(kcGroup12.getFirstAttribute(descriptionAttrName)); }); } @@ -169,7 +169,7 @@ public void test02_syncWithDropNonExistingGroups() throws Exception { // KEYCLOAK-11415 - This test requires the group mapper to be configured with preserve group inheritance // set to 'true' (the default setting). If preservation of group inheritance isn't configured, some of // the previous test(s) failed to cleanup properly. Check the requirement as part of running the test - Assert.assertEquals(mapperModel.getConfig().getFirst("preserve.group.inheritance"), "true"); + Assertions.assertEquals(mapperModel.getConfig().getFirst("preserve.group.inheritance"), "true"); // Sync groups with inheritance SynchronizationResult syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(realm); @@ -177,10 +177,10 @@ public void test02_syncWithDropNonExistingGroups() throws Exception { // Assert groups are imported to keycloak including their inheritance from LDAP GroupModel kcGroup1 = KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1"); - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/group11")); - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/group12")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/group11")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/group12")); - Assert.assertEquals(2, kcGroup1.getSubGroupsStream().count()); + Assertions.assertEquals(2, kcGroup1.getSubGroupsStream().count()); // Create some new groups in keycloak GroupModel groupsPathGroup = KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH); @@ -192,11 +192,11 @@ public void test02_syncWithDropNonExistingGroups() throws Exception { syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(realm); LDAPTestAsserts.assertSyncEquals(syncResult, 0, 3, 0, 0); - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/group11")); - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/group12")); - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/model1")); - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/model2")); - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/outside")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/group11")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/group12")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/model1")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/model2")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/outside")); // Update group mapper to drop non-existing groups during sync LDAPTestUtils.updateConfigOptions(mapperModel, GroupMapperConfig.DROP_NON_EXISTING_GROUPS_DURING_SYNC, "true"); @@ -204,15 +204,15 @@ public void test02_syncWithDropNonExistingGroups() throws Exception { // Sync groups again from LDAP. Assert LDAP non-existing groups deleted syncResult = new GroupLDAPStorageMapperFactory().create(session, mapperModel).syncDataFromFederationProviderToKeycloak(realm); - Assert.assertEquals(3, syncResult.getUpdated()); - Assert.assertTrue(syncResult.getRemoved() == 2); + Assertions.assertEquals(3, syncResult.getUpdated()); + Assertions.assertTrue(syncResult.getRemoved() == 2); // Sync and assert groups updated - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/group11")); - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/group12")); - Assert.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/model1")); - Assert.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/model2")); - Assert.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/outside")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/group11")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/group12")); + Assertions.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/model1")); + Assertions.assertNull(KeycloakModelUtils.findGroupByPath(session, realm, LDAP_GROUPS_PATH + "/group1/model2")); + Assertions.assertNotNull(KeycloakModelUtils.findGroupByPath(session, realm, "/outside")); }); } @@ -235,7 +235,7 @@ public void test03_createConfigurationWithoutGroupPath() throws Exception { // Load the mapper and assert default group path set ComponentRepresentation newMapper = adminClient.realm("test").components().component(newMapperId).toRepresentation(); - Assert.assertEquals(GroupMapperConfig.DEFAULT_LDAP_GROUPS_PATH, newMapper.getConfig().getFirst(GroupMapperConfig.LDAP_GROUPS_PATH)); + Assertions.assertEquals(GroupMapperConfig.DEFAULT_LDAP_GROUPS_PATH, newMapper.getConfig().getFirst(GroupMapperConfig.LDAP_GROUPS_PATH)); } finally { // revert new mapper adminClient.realm("test").components().component(newMapperId).remove(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperTest.java index 70fd0f5e623c..98c0b53d4e05 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperTest.java @@ -47,10 +47,10 @@ import org.keycloak.testsuite.util.LDAPRule; import org.keycloak.testsuite.util.LDAPTestUtils; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import static org.keycloak.testsuite.util.LDAPTestUtils.getGroupDescriptionLDAPAttrName; @@ -128,9 +128,9 @@ protected void test01_ldapOnlyGroupMappings(boolean importEnabled) { john.joinGroup(groupChildWithSlashesInName); mary.joinGroup(groupChildWithSlashesInName); - Assert.assertEquals("Team SubChild 2020/2021", KeycloakModelUtils.findGroupByPath(session, appRealm, "defaultGroup1/Team Child 2018/2019/Team SubChild 2020/2021").getName()); - Assert.assertEquals("defaultGroup14", KeycloakModelUtils.findGroupByPath(session, appRealm, "defaultGroup13/Team SubChild 2022/2023/A/B/C/D/E/defaultGroup14").getName()); - Assert.assertEquals("Team SubChild 2026/2027", KeycloakModelUtils.findGroupByPath(session, appRealm, "Team Root 2024/2025/A/B/C/D/defaultGroup15/Team SubChild 2026/2027").getName()); + Assertions.assertEquals("Team SubChild 2020/2021", KeycloakModelUtils.findGroupByPath(session, appRealm, "defaultGroup1/Team Child 2018/2019/Team SubChild 2020/2021").getName()); + Assertions.assertEquals("defaultGroup14", KeycloakModelUtils.findGroupByPath(session, appRealm, "defaultGroup13/Team SubChild 2022/2023/A/B/C/D/E/defaultGroup14").getName()); + Assertions.assertEquals("Team SubChild 2026/2027", KeycloakModelUtils.findGroupByPath(session, appRealm, "Team Root 2024/2025/A/B/C/D/defaultGroup15/Team SubChild 2026/2027").getName()); }); @@ -141,14 +141,14 @@ protected void test01_ldapOnlyGroupMappings(boolean importEnabled) { RealmModel appRealm = ctx.getRealm(); UserModel johnDb = UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "johnkeycloak"); - Assert.assertEquals(2, johnDb.getGroupsStream().count()); - Assert.assertEquals(2, johnDb.getGroupsStream("Gr", 0, 10).count()); - Assert.assertEquals(1, johnDb.getGroupsStream("Gr", 1, 10).count()); - Assert.assertEquals(1, johnDb.getGroupsStream("Gr", 0, 1).count()); - Assert.assertEquals(1, johnDb.getGroupsStream("12", 0, 10).count()); + Assertions.assertEquals(2, johnDb.getGroupsStream().count()); + Assertions.assertEquals(2, johnDb.getGroupsStream("Gr", 0, 10).count()); + Assertions.assertEquals(1, johnDb.getGroupsStream("Gr", 1, 10).count()); + Assertions.assertEquals(1, johnDb.getGroupsStream("Gr", 0, 1).count()); + Assertions.assertEquals(1, johnDb.getGroupsStream("12", 0, 10).count()); long dbGroupCount = johnDb.getGroupsCount(); - Assert.assertEquals(2, dbGroupCount); + Assertions.assertEquals(2, dbGroupCount); }); } @@ -167,21 +167,21 @@ protected void test01_ldapOnlyGroupMappings(boolean importEnabled) { UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); Set johnGroups = john.getGroupsStream().collect(Collectors.toSet()); - Assert.assertEquals(4, johnGroups.size()); + Assertions.assertEquals(4, johnGroups.size()); long groupCount = john.getGroupsCount(); - Assert.assertEquals(4, groupCount); - Assert.assertTrue(johnGroups.contains(group1)); - Assert.assertFalse(johnGroups.contains(group11)); - Assert.assertTrue(johnGroups.contains(group12)); - Assert.assertTrue(johnGroups.contains(groupTeam20162017)); - Assert.assertTrue(johnGroups.contains(groupTeamChild20182019)); - - Assert.assertEquals(2, john.getGroupsStream("gr", 0, 10).count()); - Assert.assertEquals(1, john.getGroupsStream("gr", 1, 10).count()); - Assert.assertEquals(1, john.getGroupsStream("gr", 0, 1).count()); - Assert.assertEquals(1, john.getGroupsStream("12", 0, 10).count()); - Assert.assertEquals(1, john.getGroupsStream("2017", 0, 10).count()); - Assert.assertEquals(1, john.getGroupsStream("2018", 0, 10).count()); + Assertions.assertEquals(4, groupCount); + Assertions.assertTrue(johnGroups.contains(group1)); + Assertions.assertFalse(johnGroups.contains(group11)); + Assertions.assertTrue(johnGroups.contains(group12)); + Assertions.assertTrue(johnGroups.contains(groupTeam20162017)); + Assertions.assertTrue(johnGroups.contains(groupTeamChild20182019)); + + Assertions.assertEquals(2, john.getGroupsStream("gr", 0, 10).count()); + Assertions.assertEquals(1, john.getGroupsStream("gr", 1, 10).count()); + Assertions.assertEquals(1, john.getGroupsStream("gr", 0, 1).count()); + Assertions.assertEquals(1, john.getGroupsStream("12", 0, 10).count()); + Assertions.assertEquals(1, john.getGroupsStream("2017", 0, 10).count()); + Assertions.assertEquals(1, john.getGroupsStream("2018", 0, 10).count()); // 4 - Check through userProvider List group1Members = session.users().getGroupMembersStream(appRealm, group1, 0, 10) @@ -192,13 +192,13 @@ protected void test01_ldapOnlyGroupMappings(boolean importEnabled) { Stream groupTeam20162017Members = session.users().getGroupMembersStream(appRealm, groupTeam20162017, 0, 10); Stream groupTeam20182019Members = session.users().getGroupMembersStream(appRealm, groupTeamChild20182019, 0, 10); - Assert.assertEquals(1, group1Members.size()); - Assert.assertEquals("johnkeycloak", group1Members.get(0).getUsername()); - Assert.assertEquals(1, group11Members.size()); - Assert.assertEquals("marykeycloak", group11Members.get(0).getUsername()); - Assert.assertEquals(2, group12Members.count()); - Assert.assertEquals(2, groupTeam20162017Members.count()); - Assert.assertEquals(2, groupTeam20182019Members.count()); + Assertions.assertEquals(1, group1Members.size()); + Assertions.assertEquals("johnkeycloak", group1Members.get(0).getUsername()); + Assertions.assertEquals(1, group11Members.size()); + Assertions.assertEquals("marykeycloak", group11Members.get(0).getUsername()); + Assertions.assertEquals(2, group12Members.count()); + Assertions.assertEquals(2, groupTeam20162017Members.count()); + Assertions.assertEquals(2, groupTeam20182019Members.count()); // 4 - Delete some group mappings and check they are deleted @@ -213,10 +213,10 @@ protected void test01_ldapOnlyGroupMappings(boolean importEnabled) { mary.leaveGroup(groupTeam20162017); mary.leaveGroup(groupTeamChild20182019); - Assert.assertEquals(0, john.getGroupsStream().count()); + Assertions.assertEquals(0, john.getGroupsStream().count()); groupCount = john.getGroupsCount(); - Assert.assertEquals(0, groupCount); + Assertions.assertEquals(0, groupCount); }); } @@ -261,18 +261,18 @@ protected void test02_readOnlyGroupMappings(boolean importEnabled) { // Assert that mary has both LDAP and DB mapped groups Set maryGroups = mary.getGroupsStream().collect(Collectors.toSet()); - Assert.assertEquals(5, maryGroups.size()); - Assert.assertTrue(maryGroups.contains(group1)); - Assert.assertTrue(maryGroups.contains(group11)); - Assert.assertTrue(maryGroups.contains(group12)); + Assertions.assertEquals(5, maryGroups.size()); + Assertions.assertTrue(maryGroups.contains(group1)); + Assertions.assertTrue(maryGroups.contains(group11)); + Assertions.assertTrue(maryGroups.contains(group12)); long groupCount = mary.getGroupsCount(); - Assert.assertEquals(5, groupCount); + Assertions.assertEquals(5, groupCount); - Assert.assertEquals(5, mary.getGroupsStream("gr", 0, 10).count()); - Assert.assertEquals(4, mary.getGroupsStream("gr", 1, 10).count()); - Assert.assertEquals(1, mary.getGroupsStream("gr", 0, 1).count()); - Assert.assertEquals(2, mary.getGroupsStream("12", 0, 10).count()); + Assertions.assertEquals(5, mary.getGroupsStream("gr", 0, 10).count()); + Assertions.assertEquals(4, mary.getGroupsStream("gr", 1, 10).count()); + Assertions.assertEquals(1, mary.getGroupsStream("gr", 0, 1).count()); + Assertions.assertEquals(2, mary.getGroupsStream("12", 0, 10).count()); }); } else { testingClient.server().run(session -> { @@ -286,7 +286,7 @@ protected void test02_readOnlyGroupMappings(boolean importEnabled) { // as it is not allowed to update group mappings in LDAP nor in the DB try { mary.joinGroup(group12); - Assert.fail("Not expected to successfully add group12 in no-import mode and READ_ONLY mode of the group mapper"); + Assertions.fail("Not expected to successfully add group12 in no-import mode and READ_ONLY mode of the group mapper"); } catch (ReadOnlyException me) { // Ignore } @@ -303,18 +303,18 @@ protected void test02_readOnlyGroupMappings(boolean importEnabled) { // Assert that mary has both LDAP and DB mapped groups Set maryGroups = mary.getGroupsStream().collect(Collectors.toSet()); - Assert.assertEquals(4, maryGroups.size()); - Assert.assertTrue(maryGroups.contains(group1)); - Assert.assertTrue(maryGroups.contains(group11)); - Assert.assertFalse(maryGroups.contains(group12)); + Assertions.assertEquals(4, maryGroups.size()); + Assertions.assertTrue(maryGroups.contains(group1)); + Assertions.assertTrue(maryGroups.contains(group11)); + Assertions.assertFalse(maryGroups.contains(group12)); long groupCount = mary.getGroupsCount(); - Assert.assertEquals(4, groupCount); + Assertions.assertEquals(4, groupCount); - Assert.assertEquals(4, mary.getGroupsStream("gr", 0, 10).count()); - Assert.assertEquals(3, mary.getGroupsStream("gr", 1, 10).count()); - Assert.assertEquals(1, mary.getGroupsStream("gr", 0, 1).count()); - Assert.assertEquals(1, mary.getGroupsStream("12", 0, 10).count()); + Assertions.assertEquals(4, mary.getGroupsStream("gr", 0, 10).count()); + Assertions.assertEquals(3, mary.getGroupsStream("gr", 1, 10).count()); + Assertions.assertEquals(1, mary.getGroupsStream("gr", 0, 1).count()); + Assertions.assertEquals(1, mary.getGroupsStream("12", 0, 10).count()); }); } @@ -331,23 +331,23 @@ protected void test02_readOnlyGroupMappings(boolean importEnabled) { UserModel maryDB = UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "marykeycloak"); Set maryDBGroups = maryDB.getGroupsStream().collect(Collectors.toSet()); - Assert.assertFalse(maryDBGroups.contains(group1)); - Assert.assertFalse(maryDBGroups.contains(group11)); - Assert.assertTrue(maryDBGroups.contains(group12)); + Assertions.assertFalse(maryDBGroups.contains(group1)); + Assertions.assertFalse(maryDBGroups.contains(group11)); + Assertions.assertTrue(maryDBGroups.contains(group12)); - Assert.assertEquals(3, maryDB.getGroupsStream("Gr", 0, 10).count()); - Assert.assertEquals(2, maryDB.getGroupsStream("Gr", 1, 10).count()); - Assert.assertEquals(1, maryDB.getGroupsStream("Gr", 0, 1).count()); - Assert.assertEquals(2, maryDB.getGroupsStream("12", 0, 10).count()); + Assertions.assertEquals(3, maryDB.getGroupsStream("Gr", 0, 10).count()); + Assertions.assertEquals(2, maryDB.getGroupsStream("Gr", 1, 10).count()); + Assertions.assertEquals(1, maryDB.getGroupsStream("Gr", 0, 1).count()); + Assertions.assertEquals(2, maryDB.getGroupsStream("12", 0, 10).count()); long dbGroupCount = maryDB.getGroupsCount(); - Assert.assertEquals(3, dbGroupCount); + Assertions.assertEquals(3, dbGroupCount); // Test the group mapping available for group12 List group12Members = session.users().getGroupMembersStream(appRealm, group12, 0, 10) .collect(Collectors.toList()); - Assert.assertEquals(1, group12Members.size()); - Assert.assertEquals("marykeycloak", group12Members.get(0).getUsername()); + Assertions.assertEquals(1, group12Members.size()); + Assertions.assertEquals("marykeycloak", group12Members.get(0).getUsername()); UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); mary.leaveGroup(group12); @@ -361,7 +361,7 @@ protected void test02_readOnlyGroupMappings(boolean importEnabled) { // Test the group mapping NOT available for group12 Stream group12Members = session.users().getGroupMembersStream(appRealm, group12, 0, 10); - Assert.assertEquals(0, group12Members.count()); + Assertions.assertEquals(0, group12Members.count()); }); } @@ -385,14 +385,14 @@ protected void test02_readOnlyGroupMappings(boolean importEnabled) { .collect(Collectors.toList()); List group11Members = session.users().getGroupMembersStream(appRealm, group11, 0, 10) .collect(Collectors.toList()); - Assert.assertEquals(1, group1Members.size()); - Assert.assertEquals("marykeycloak", group1Members.get(0).getUsername()); - Assert.assertEquals(1, group11Members.size()); - Assert.assertEquals("marykeycloak", group11Members.get(0).getUsername()); + Assertions.assertEquals(1, group1Members.size()); + Assertions.assertEquals("marykeycloak", group1Members.get(0).getUsername()); + Assertions.assertEquals(1, group11Members.size()); + Assertions.assertEquals("marykeycloak", group11Members.get(0).getUsername()); try { mary.leaveGroup(group1); - Assert.fail("It wasn't expected to successfully delete LDAP group mappings in READ_ONLY mode"); + Assertions.fail("It wasn't expected to successfully delete LDAP group mappings in READ_ONLY mode"); } catch (ModelException expected) { } @@ -432,17 +432,17 @@ public void test03_importGroupMappings() { UserModel rob = session.users().getUserByUsername(appRealm, "robkeycloak"); Set robGroups = rob.getGroupsStream().collect(Collectors.toSet()); - Assert.assertFalse(robGroups.contains(group1)); - Assert.assertTrue(robGroups.contains(group11)); - Assert.assertTrue(robGroups.contains(group12)); + Assertions.assertFalse(robGroups.contains(group1)); + Assertions.assertTrue(robGroups.contains(group11)); + Assertions.assertTrue(robGroups.contains(group12)); - Assert.assertEquals(4, rob.getGroupsStream("Gr", 0, 10).count()); - Assert.assertEquals(3, rob.getGroupsStream("Gr", 1, 10).count()); - Assert.assertEquals(1, rob.getGroupsStream("Gr", 0, 1).count()); - Assert.assertEquals(2, rob.getGroupsStream("12", 0, 10).count()); + Assertions.assertEquals(4, rob.getGroupsStream("Gr", 0, 10).count()); + Assertions.assertEquals(3, rob.getGroupsStream("Gr", 1, 10).count()); + Assertions.assertEquals(1, rob.getGroupsStream("Gr", 0, 1).count()); + Assertions.assertEquals(2, rob.getGroupsStream("12", 0, 10).count()); long dbGroupCount = rob.getGroupsCount(); - Assert.assertEquals(4, dbGroupCount); + Assertions.assertEquals(4, dbGroupCount); // Check getGroupMembers Stream group1Members = session.users().getGroupMembersStream(appRealm, group1, 0, 10); @@ -451,11 +451,11 @@ public void test03_importGroupMappings() { List group12Members = session.users().getGroupMembersStream(appRealm, group12, 0, 10) .collect(Collectors.toList()); - Assert.assertEquals(0, group1Members.count()); - Assert.assertEquals(1, group11Members.size()); - Assert.assertEquals("robkeycloak", group11Members.get(0).getUsername()); - Assert.assertEquals(1, group12Members.size()); - Assert.assertEquals("robkeycloak", group12Members.get(0).getUsername()); + Assertions.assertEquals(0, group1Members.count()); + Assertions.assertEquals(1, group11Members.size()); + Assertions.assertEquals("robkeycloak", group11Members.get(0).getUsername()); + Assertions.assertEquals(1, group12Members.size()); + Assertions.assertEquals("robkeycloak", group12Members.get(0).getUsername()); // Delete some group mappings in LDAP and check that it doesn't have any effect and user still has groups LDAPObject ldapGroup = groupMapper.loadLDAPGroupByName("group11"); @@ -465,8 +465,8 @@ public void test03_importGroupMappings() { groupMapper.deleteGroupMappingInLDAP(robLdap, ldapGroup); robGroups = rob.getGroupsStream().collect(Collectors.toSet()); - Assert.assertTrue(robGroups.contains(group11)); - Assert.assertTrue(robGroups.contains(group12)); + Assertions.assertTrue(robGroups.contains(group11)); + Assertions.assertTrue(robGroups.contains(group12)); // Check getGroupMembers group1Members = session.users().getGroupMembersStream(appRealm, group1, 0, 10); @@ -475,16 +475,16 @@ public void test03_importGroupMappings() { group12Members = session.users().getGroupMembersStream(appRealm, group12, 0, 10) .collect(Collectors.toList()); - Assert.assertEquals(0, group1Members.count()); - Assert.assertEquals(1, group11Members.size()); - Assert.assertEquals("robkeycloak", group11Members.get(0).getUsername()); - Assert.assertEquals(1, group12Members.size()); - Assert.assertEquals("robkeycloak", group12Members.get(0).getUsername()); + Assertions.assertEquals(0, group1Members.count()); + Assertions.assertEquals(1, group11Members.size()); + Assertions.assertEquals("robkeycloak", group11Members.get(0).getUsername()); + Assertions.assertEquals(1, group12Members.size()); + Assertions.assertEquals("robkeycloak", group12Members.get(0).getUsername()); // Delete group mappings through model and verifies that user doesn't have them anymore rob.leaveGroup(group11); rob.leaveGroup(group12); - Assert.assertEquals(2, rob.getGroupsStream().count()); + Assertions.assertEquals(2, rob.getGroupsStream().count()); }); } @@ -535,9 +535,9 @@ public void test04_groupReferencingNonExistentMember() { GroupModel kcGroup2 = KeycloakModelUtils.findGroupByPath(session, appRealm, "/group2"); List groupUsers = session.users().getGroupMembersStream(appRealm, kcGroup2, 0, 5) .collect(Collectors.toList()); - Assert.assertEquals(1, groupUsers.size()); + Assertions.assertEquals(1, groupUsers.size()); UserModel rob = groupUsers.get(0); - Assert.assertEquals("jameskeycloak", rob.getUsername()); + Assertions.assertEquals("jameskeycloak", rob.getUsername()); }); } @@ -588,11 +588,11 @@ public void test05_getGroupsFromUserMemberOfStrategyTest() throws Exception { GroupModel group11 = KeycloakModelUtils.findGroupByPath(session, appRealm, "/group1/group11"); GroupModel group12 = KeycloakModelUtils.findGroupByPath(session, appRealm, "/group1/group12"); - Assert.assertTrue(carlosGroups.contains(group1)); - Assert.assertFalse(carlosGroups.contains(group11)); - Assert.assertFalse(carlosGroups.contains(group12)); + Assertions.assertTrue(carlosGroups.contains(group1)); + Assertions.assertFalse(carlosGroups.contains(group11)); + Assertions.assertFalse(carlosGroups.contains(group12)); - Assert.assertEquals(1, carlosGroups.size()); + Assertions.assertEquals(1, carlosGroups.size()); // check the user is listed as the sole member of group1 List group1Members = session.users().getGroupMembersStream(appRealm, group1, 0, 10).toList(); @@ -635,7 +635,7 @@ public void test05_DoNotResolveGroupsIfMemberOfNotChildOfGroupBaseDN() { UserModel user = session.users().getUserByUsername(appRealm, "alice"); Set groups = user.getGroupsStream().collect(Collectors.toSet()); - Assert.assertTrue(groups.isEmpty()); + Assertions.assertTrue(groups.isEmpty()); }); testRealm().components().component(streetMapperRep.getId()).remove(); @@ -676,7 +676,7 @@ public void test05_DoNotResolveGroupsIfMemberOfHasEmptyValue() { UserModel user = session.users().getUserByUsername(appRealm, "alice"); Set groups = user.getGroupsStream().collect(Collectors.toSet()); - Assert.assertTrue(groups.isEmpty()); + Assertions.assertTrue(groups.isEmpty()); }); testRealm().components().component(streetMapperRep.getId()).remove(); @@ -755,13 +755,13 @@ public void test06_addingUserToNewKeycloakGroup() throws Exception { assertThat(groups, containsInAnyOrder(group14, group31, group32, group4)); long groupsCount = john.getGroupsCount(); - Assert.assertEquals(4, groupsCount); + Assertions.assertEquals(4, groupsCount); - Assert.assertEquals(2, john.getGroupsStream("3", 0, 10).count()); - Assert.assertEquals(1, john.getGroupsStream("3", 1, 10).count()); - Assert.assertEquals(1, john.getGroupsStream("3", 1, 1).count()); - Assert.assertEquals(0, john.getGroupsStream("3", 1, 0).count()); - Assert.assertEquals(0, john.getGroupsStream("Keycloak", 0, 10).count()); + Assertions.assertEquals(2, john.getGroupsStream("3", 0, 10).count()); + Assertions.assertEquals(1, john.getGroupsStream("3", 1, 10).count()); + Assertions.assertEquals(1, john.getGroupsStream("3", 1, 1).count()); + Assertions.assertEquals(0, john.getGroupsStream("3", 1, 0).count()); + Assertions.assertEquals(0, john.getGroupsStream("Keycloak", 0, 10).count()); }); } @@ -792,24 +792,24 @@ public void test07_newUserDefaultGroupsImportModeTest() throws Exception { UserModel david = session.users().addUser(appRealm, "davidkeycloak"); GroupModel defaultGroup11 = KeycloakModelUtils.findGroupByPath(session, appRealm, "/defaultGroup1/defaultGroup11"); - Assert.assertNotNull(defaultGroup11); + Assertions.assertNotNull(defaultGroup11); GroupModel defaultGroup12 = KeycloakModelUtils.findGroupByPath(session, appRealm, "/defaultGroup1/defaultGroup12"); - Assert.assertNotNull(defaultGroup12); + Assertions.assertNotNull(defaultGroup12); GroupModel group31 = KeycloakModelUtils.findGroupByPath(session, appRealm, "/group3/group31"); - Assert.assertNotNull(group31); + Assertions.assertNotNull(group31); GroupModel group32 = KeycloakModelUtils.findGroupByPath(session, appRealm, "/group3/group32"); - Assert.assertNotNull(group32); + Assertions.assertNotNull(group32); GroupModel group4 = KeycloakModelUtils.findGroupByPath(session, appRealm, "/group4"); - Assert.assertNotNull(group4); + Assertions.assertNotNull(group4); Set groups = david.getGroupsStream().collect(Collectors.toSet()); - Assert.assertTrue(groups.contains(defaultGroup11)); - Assert.assertTrue(groups.contains(defaultGroup12)); - Assert.assertFalse(groups.contains(group31)); - Assert.assertFalse(groups.contains(group32)); - Assert.assertFalse(groups.contains(group4)); + Assertions.assertTrue(groups.contains(defaultGroup11)); + Assertions.assertTrue(groups.contains(defaultGroup12)); + Assertions.assertFalse(groups.contains(group31)); + Assertions.assertFalse(groups.contains(group32)); + Assertions.assertFalse(groups.contains(group4)); }); } @@ -863,10 +863,10 @@ public void test08_ldapOnlyGroupMappingsRanged() { // check if ranged intercetor is in place and working GroupMapperConfig config = new GroupMapperConfig(mapperModel); bigGroup = LDAPGroupMapperTest.searchObjectInBase(ctx.getLdapProvider(), bigGroup.getDn().toString(), config.getMembershipLdapAttribute()); - Assert.assertNotNull(bigGroup.getAttributes().get(config.getMembershipLdapAttribute())); - Assert.assertFalse(bigGroup.isRangeComplete(config.getMembershipLdapAttribute())); - Assert.assertTrue(membersToTest > bigGroup.getAttributeAsSet(config.getMembershipLdapAttribute()).size()); - Assert.assertEquals(bigGroup.getCurrentRange(config.getMembershipLdapAttribute()), bigGroup.getAttributeAsSet(config.getMembershipLdapAttribute()).size() - 1); + Assertions.assertNotNull(bigGroup.getAttributes().get(config.getMembershipLdapAttribute())); + Assertions.assertFalse(bigGroup.isRangeComplete(config.getMembershipLdapAttribute())); + Assertions.assertTrue(membersToTest > bigGroup.getAttributeAsSet(config.getMembershipLdapAttribute()).size()); + Assertions.assertEquals(bigGroup.getCurrentRange(config.getMembershipLdapAttribute()), bigGroup.getAttributeAsSet(config.getMembershipLdapAttribute()).size() - 1); // now check the population of ranged attributes is OK LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel()); @@ -877,15 +877,15 @@ public void test08_ldapOnlyGroupMappingsRanged() { // check all the users have the group assigned for (int i = 0; i < membersToTest; i++) { UserModel kcUser = session.users().getUserByUsername(appRealm, String.format("user%02d", i)); - Assert.assertTrue("User contains biggroup " + i, kcUser.getGroupsStream().collect(Collectors.toSet()).contains(kcBigGroup)); + Assertions.assertTrue(kcUser.getGroupsStream().collect(Collectors.toSet()).contains(kcBigGroup), "User contains biggroup " + i); } // check the group contains all the users as member List groupMembers = session.users().getGroupMembersStream(appRealm, kcBigGroup, 0, membersToTest) .collect(Collectors.toList()); - Assert.assertEquals(membersToTest, groupMembers.size()); + Assertions.assertEquals(membersToTest, groupMembers.size()); Set usernames = groupMembers.stream().map(u -> u.getUsername()).collect(Collectors.toSet()); for (int i = 0; i < membersToTest; i++) { - Assert.assertTrue("Group contains user " + i, usernames.contains(String.format("user%02d", i))); + Assertions.assertTrue(usernames.contains(String.format("user%02d", i)), "Group contains user " + i); } // check group members are paginated OK using page size 10 usernames.clear(); @@ -893,10 +893,10 @@ public void test08_ldapOnlyGroupMappingsRanged() { groupMembers = session.users().getGroupMembersStream(appRealm, kcBigGroup, i, 10) .collect(Collectors.toList()); usernames.addAll(groupMembers.stream().map(u -> u.getUsername()).collect(Collectors.toSet())); - Assert.assertEquals("Incorrect number of users after pagination " + i, membersToTest < i + 10 ? membersToTest : i + 10, usernames.size()); + Assertions.assertEquals(membersToTest < i + 10 ? membersToTest : i + 10, usernames.size(), "Incorrect number of users after pagination " + i); } for (int i = 0; i < membersToTest; i++) { - Assert.assertTrue("Group contains user after pagination " + i, usernames.contains(String.format("user%02d", i))); + Assertions.assertTrue(usernames.contains(String.format("user%02d", i)), "Group contains user after pagination " + i); } ctx.getLdapModel().getConfig().remove(LDAPConstants.MAX_CONDITIONS); }); @@ -924,9 +924,9 @@ public void test09_emptyMemberOnDeletionWorks() { empty.setDn(LDAPDn.fromString(LDAPConstants.EMPTY_MEMBER_ATTRIBUTE_VALUE)); LDAPUtils.deleteMember(ctx.getLdapProvider(), MembershipType.DN, LDAPConstants.MEMBER, descriptionAttrName, deleteGroup, empty); deleteGroup = LDAPGroupMapperTest.searchObjectInBase(ctx.getLdapProvider(), deleteGroup.getDn().toString(), LDAPConstants.MEMBER); - Assert.assertNotNull(deleteGroup); - Assert.assertEquals(1, deleteGroup.getAttributeAsSet(LDAPConstants.MEMBER).size()); - Assert.assertEquals(maryLdap.getDn(), LDAPDn.fromString(deleteGroup.getAttributeAsString(LDAPConstants.MEMBER))); + Assertions.assertNotNull(deleteGroup); + Assertions.assertEquals(1, deleteGroup.getAttributeAsSet(LDAPConstants.MEMBER).size()); + Assertions.assertEquals(maryLdap.getDn(), LDAPDn.fromString(deleteGroup.getAttributeAsString(LDAPConstants.MEMBER))); // import into keycloak LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel()); @@ -938,20 +938,20 @@ public void test09_emptyMemberOnDeletionWorks() { UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); List groupMembers = session.users().getGroupMembersStream(appRealm, kcDeleteGroup, 0, 5) .collect(Collectors.toList()); - Assert.assertEquals(1, groupMembers.size()); - Assert.assertEquals("marykeycloak", groupMembers.get(0).getUsername()); + Assertions.assertEquals(1, groupMembers.size()); + Assertions.assertEquals("marykeycloak", groupMembers.get(0).getUsername()); Set maryGroups = mary.getGroupsStream().collect(Collectors.toSet()); - Assert.assertEquals(1, maryGroups.size()); - Assert.assertEquals("deletegroup", maryGroups.iterator().next().getName()); + Assertions.assertEquals(1, maryGroups.size()); + Assertions.assertEquals("deletegroup", maryGroups.iterator().next().getName()); // delete the group from mary to force schema violation and assingment of the empty value mary.leaveGroup(kcDeleteGroup); // check now the group has the empty member instead of mary deleteGroup = LDAPGroupMapperTest.searchObjectInBase(ctx.getLdapProvider(), deleteGroup.getDn().toString(), LDAPConstants.MEMBER); - Assert.assertNotNull(deleteGroup); - Assert.assertEquals(1, deleteGroup.getAttributeAsSet(LDAPConstants.MEMBER).size()); - Assert.assertEquals(LDAPDn.fromString(LDAPConstants.EMPTY_MEMBER_ATTRIBUTE_VALUE), LDAPDn.fromString(deleteGroup.getAttributeAsString(LDAPConstants.MEMBER))); + Assertions.assertNotNull(deleteGroup); + Assertions.assertEquals(1, deleteGroup.getAttributeAsSet(LDAPConstants.MEMBER).size()); + Assertions.assertEquals(LDAPDn.fromString(LDAPConstants.EMPTY_MEMBER_ATTRIBUTE_VALUE), LDAPDn.fromString(deleteGroup.getAttributeAsString(LDAPConstants.MEMBER))); }); } @@ -1015,16 +1015,16 @@ public void test10_multipleGroupMappersInDifferentPaths() { // 5.1- Check that group mappings are in LDAP and hence available through federation Set johnGroups = john.getGroupsStream().collect(Collectors.toSet()); - Assert.assertEquals(4, johnGroups.size()); - Assert.assertTrue(johnGroups.contains(groupA)); - Assert.assertFalse(johnGroups.contains(groupB)); - Assert.assertTrue(johnGroups.contains(groupC)); + Assertions.assertEquals(4, johnGroups.size()); + Assertions.assertTrue(johnGroups.contains(groupA)); + Assertions.assertFalse(johnGroups.contains(groupB)); + Assertions.assertTrue(johnGroups.contains(groupC)); Set maryGroups = mary.getGroupsStream().collect(Collectors.toSet()); - Assert.assertEquals(4, maryGroups.size()); - Assert.assertFalse(maryGroups.contains(groupA)); - Assert.assertTrue(maryGroups.contains(groupB)); - Assert.assertTrue(maryGroups.contains(groupC)); + Assertions.assertEquals(4, maryGroups.size()); + Assertions.assertFalse(maryGroups.contains(groupA)); + Assertions.assertTrue(maryGroups.contains(groupB)); + Assertions.assertTrue(maryGroups.contains(groupC)); // 5.2- Check through userProvider List groupAMembers = session.users().getGroupMembersStream(realm, groupA, 0, 10) @@ -1034,13 +1034,13 @@ public void test10_multipleGroupMappersInDifferentPaths() { List groupCMembers = session.users().getGroupMembersStream(realm, groupC, 0, 10) .map(UserModel::getUsername).toList(); - Assert.assertEquals(1, groupAMembers.size()); - Assert.assertEquals("johnkeycloak", groupAMembers.get(0)); - Assert.assertEquals(1, groupBMembers.size()); - Assert.assertEquals("marykeycloak", groupBMembers.get(0)); - Assert.assertEquals(2, groupCMembers.size()); - Assert.assertTrue(groupCMembers.contains("johnkeycloak")); - Assert.assertTrue(groupCMembers.contains("marykeycloak")); + Assertions.assertEquals(1, groupAMembers.size()); + Assertions.assertEquals("johnkeycloak", groupAMembers.get(0)); + Assertions.assertEquals(1, groupBMembers.size()); + Assertions.assertEquals("marykeycloak", groupBMembers.get(0)); + Assertions.assertEquals(2, groupCMembers.size()); + Assertions.assertTrue(groupCMembers.contains("johnkeycloak")); + Assertions.assertTrue(groupCMembers.contains("marykeycloak")); }); testingClient.server(TEST_REALM_NAME).run(session -> { @@ -1054,8 +1054,8 @@ public void test10_multipleGroupMappersInDifferentPaths() { // 7- Check that the members of the local group are not mixed with members of the group with same name from LDAP List localGroupMembers = session.users().getGroupMembersStream(realm, localGroup, 0, 10) .map(UserModel::getUsername).toList(); - Assert.assertEquals(1, localGroupMembers.size()); - Assert.assertEquals("localuser", localGroupMembers.get(0)); + Assertions.assertEquals(1, localGroupMembers.size()); + Assertions.assertEquals("localuser", localGroupMembers.get(0)); }); } @@ -1116,7 +1116,7 @@ public void test11_fetchUsersGroupsWithPaginationAndInvalidBatchSize() { // verify that getting the user's groups still works UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); Set johnGroups = john.getGroupsStream().collect(Collectors.toSet()); - Assert.assertEquals(4, johnGroups.size()); + Assertions.assertEquals(4, johnGroups.size()); }); String configuredBatchSize = ldapRule.getConfig().get(LDAPConstants.BATCH_SIZE_FOR_SYNC); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPHardcodedAttributeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPHardcodedAttributeTest.java index 9f5a03e515da..f5bccc4aac21 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPHardcodedAttributeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPHardcodedAttributeTest.java @@ -29,11 +29,11 @@ import org.keycloak.testsuite.util.LDAPRule; import org.keycloak.testsuite.util.LDAPTestUtils; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.rules.ExpectedException; import org.junit.runners.MethodSorters; @@ -86,9 +86,9 @@ public void testHarcodedMapper(){ RealmModel appRealm = ctx.getRealm(); UserModel user = session.users().getUserByUsername(appRealm, "johnkeycloak"); - Assert.assertNotNull(user); - Assert.assertTrue(user.isEmailVerified()); - Assert.assertEquals("en", user.getFirstAttribute("locale")); + Assertions.assertNotNull(user); + Assertions.assertTrue(user.isEmailVerified()); + Assertions.assertEquals("en", user.getFirstAttribute("locale")); }); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPLegacyImportTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPLegacyImportTest.java index 0b91a7d31450..bc06429d8e6e 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPLegacyImportTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPLegacyImportTest.java @@ -32,10 +32,10 @@ import org.keycloak.testsuite.util.LDAPTestConfiguration; import org.keycloak.testsuite.util.LDAPTestUtils; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; @@ -101,8 +101,8 @@ public void loginClassic() { oauth.openLoginForm(); loginPage.login("marykeycloak", "password-app"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); } @@ -111,14 +111,14 @@ public void loginLdap() { oauth.openLoginForm(); loginPage.login("johnkeycloak", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation userRepresentation = AccountHelper.getUserRepresentation(testRealm(), "johnkeycloak"); - Assert.assertEquals("John", userRepresentation.getFirstName()); - Assert.assertEquals("Doe", userRepresentation.getLastName()); - Assert.assertEquals("john@email.org", userRepresentation.getEmail()); + Assertions.assertEquals("John", userRepresentation.getFirstName()); + Assertions.assertEquals("Doe", userRepresentation.getLastName()); + Assertions.assertEquals("john@email.org", userRepresentation.getEmail()); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMSADFullNameTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMSADFullNameTest.java index 59cc2f522469..f5ce082627d3 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMSADFullNameTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMSADFullNameTest.java @@ -35,10 +35,10 @@ import org.keycloak.testsuite.util.LDAPTestConfiguration; import org.keycloak.testsuite.util.LDAPTestUtils; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; /** @@ -87,7 +87,7 @@ protected void afterImportTestRealm() { // Remove the mapper for "username-cn" and create new mapper for fullName ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ldapModel, "username-cn"); - Assert.assertNotNull(mapperModel); + Assertions.assertNotNull(mapperModel); appRealm.removeComponent(mapperModel); mapperModel = KeycloakModelUtils.createComponentModel("fullNameWritable", ldapModel.getId(), FullNameLDAPStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(), @@ -122,7 +122,7 @@ public void test01_addUserWithoutFullName() { RealmModel appRealm = ctx.getRealm(); UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); - Assert.assertNotNull(john.getFederationLink()); + Assertions.assertNotNull(john.getFederationLink()); assertDnStartsWith(session, ctx, john, "cn=johnkeycloak"); session.users().removeUser(appRealm, john); @@ -138,7 +138,7 @@ public void test02_registerUserWithFullName() { registerPage.assertCurrent(); registerPage.register("Johny", "Anthony", "johnyanth@check.cz", "johnkeycloak", "Password1", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); @@ -208,7 +208,7 @@ public void test05_registerUserWithFullNameSpecialChars() { registerPage.assertCurrent(); registerPage.register("Jož,o", "Baříč", "johnyanth@check.cz", "johnkeycloak", "Password1", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); @@ -244,7 +244,7 @@ public void test06_conflicts() { registerPage.assertCurrent(); registerPage.register("John", "Existing", "johnyanth@check.cz", "existingkc", "Password1", "Password1"); - Assert.assertEquals("Username already exists.", registerPage.getInputAccountErrors().getUsernameError()); + Assertions.assertEquals("Username already exists.", registerPage.getInputAccountErrors().getUsernameError()); registerPage.register("John", "Existing", "johnyanth@check.cz", "existingkc2", "Password1", "Password1"); @@ -282,13 +282,13 @@ public void test06_conflicts() { private static void assertUser(KeycloakSession session, LDAPTestContext ctx, UserModel user, String expectedUsername, String expectedFirstName, String expectedLastName, boolean expectedEnabled, String expectedDn) { - Assert.assertNotNull(user); - Assert.assertNotNull(user.getFederationLink()); - Assert.assertEquals(user.getFederationLink(), ctx.getLdapModel().getId()); - Assert.assertEquals(expectedUsername, user.getUsername()); - Assert.assertEquals(expectedFirstName, user.getFirstName()); - Assert.assertEquals(expectedLastName, user.getLastName()); - Assert.assertEquals(expectedEnabled, user.isEnabled()); + Assertions.assertNotNull(user); + Assertions.assertNotNull(user.getFederationLink()); + Assertions.assertEquals(user.getFederationLink(), ctx.getLdapModel().getId()); + Assertions.assertEquals(expectedUsername, user.getUsername()); + Assertions.assertEquals(expectedFirstName, user.getFirstName()); + Assertions.assertEquals(expectedLastName, user.getLastName()); + Assertions.assertEquals(expectedEnabled, user.isEnabled()); assertDnStartsWith(session, ctx, user, expectedDn); } @@ -296,7 +296,7 @@ private static void assertUser(KeycloakSession session, LDAPTestContext ctx, Use private static void assertDnStartsWith(KeycloakSession session, LDAPTestContext ctx, UserModel user, String expectedRDn) { String usersDn = ctx.getLdapProvider().getLdapIdentityStore().getConfig().getUsersDn(); String userDN = user.getFirstAttribute(LDAPConstants.LDAP_ENTRY_DN); - Assert.assertTrue(userDN.equalsIgnoreCase(expectedRDn + "," + usersDn)); + Assertions.assertTrue(userDN.equalsIgnoreCase(expectedRDn + "," + usersDn)); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMSADMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMSADMapperTest.java index 9f5c590a234d..47285375b65b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMSADMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMSADMapperTest.java @@ -42,11 +42,11 @@ import org.hamcrest.Matchers; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import static org.hamcrest.MatcherAssert.assertThat; @@ -113,25 +113,25 @@ public void test01RegisterUserWithWeakPasswordFirst() { // Another weak password passwordUpdatePage.assertCurrent(); passwordUpdatePage.changePassword("pass", "pass"); - Assert.assertEquals("Invalid password: new password doesn't match password policies.", passwordUpdatePage.getError()); + Assertions.assertEquals("Invalid password: new password doesn't match password policies.", passwordUpdatePage.getError()); // Strong password. Successfully update password and being redirected to the app passwordUpdatePage.changePassword("Password1", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); UserModel user = session.users().getUserByUsername(appRealm, "registerUserSuccess2"); - Assert.assertNotNull(user); - Assert.assertNotNull(user.getFederationLink()); - Assert.assertEquals(user.getFederationLink(), ctx.getLdapModel().getId()); - Assert.assertEquals("registerusersuccess2", user.getUsername()); - Assert.assertEquals("firstName", user.getFirstName()); - Assert.assertEquals("lastName", user.getLastName()); - Assert.assertTrue(user.isEnabled()); - Assert.assertEquals(0, user.getRequiredActionsStream().count()); + Assertions.assertNotNull(user); + Assertions.assertNotNull(user.getFederationLink()); + Assertions.assertEquals(user.getFederationLink(), ctx.getLdapModel().getId()); + Assertions.assertEquals("registerusersuccess2", user.getUsername()); + Assertions.assertEquals("firstName", user.getFirstName()); + Assertions.assertEquals("lastName", user.getLastName()); + Assertions.assertTrue(user.isEnabled()); + Assertions.assertEquals(0, user.getRequiredActionsStream().count()); }); } @@ -145,7 +145,7 @@ public void test02UpdatePasswordTest() { john.update(johnRep); // Check in LDAP, that johnkeycloak has pwdLastSet set to 0 in LDAP - Assert.assertEquals(0, getPwdLastSetOfJohn()); + Assertions.assertEquals(0, getPwdLastSetOfJohn()); // Login as johnkeycloak and update password after login oauth.openLoginForm(); @@ -153,20 +153,20 @@ public void test02UpdatePasswordTest() { passwordUpdatePage.assertCurrent(); passwordUpdatePage.changePassword("Password1", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); // Check in LDAP, that johnkeycloak does not have pwdLastSet set to 0 assertThat(getPwdLastSetOfJohn(), Matchers.greaterThan(0L)); // Check in admin REST API, that johnkeycloak does not have required action on him johnRep = john.toRepresentation(); - Assert.assertTrue(johnRep.getRequiredActions().isEmpty()); + Assertions.assertTrue(johnRep.getRequiredActions().isEmpty()); // Logout and login again. There should not be a need to update required action anymore john.logout(); oauth.openLoginForm(); loginPage.login("johnkeycloak", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); } @@ -180,7 +180,7 @@ public void test03UpdatePasswordWithLDAPDirectly() { john.update(johnRep); // Check in LDAP, that johnkeycloak has pwdLastSet set to 0 in LDAP - Assert.assertEquals(0, getPwdLastSetOfJohn()); + Assertions.assertEquals(0, getPwdLastSetOfJohn()); // Update password directly in MSAD testingClient.server().run(session -> { @@ -196,13 +196,13 @@ public void test03UpdatePasswordWithLDAPDirectly() { // Check in admin REST API, that johnkeycloak does not have required action on him johnRep = john.toRepresentation(); - Assert.assertTrue(johnRep.getRequiredActions().isEmpty()); + Assertions.assertTrue(johnRep.getRequiredActions().isEmpty()); // Logout and login again. There should not be a need to update required action anymore john.logout(); oauth.openLoginForm(); loginPage.login("johnkeycloak", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); } @@ -221,12 +221,12 @@ public void test04UpdateLDAPDirectlyToSetUpdatePassword() { }); // Check in LDAP, that johnkeycloak has pwdLastSet set to 0 in LDAP - Assert.assertEquals(0, getPwdLastSetOfJohn()); + Assertions.assertEquals(0, getPwdLastSetOfJohn()); // Check Admin REST API contains UPDATE_PASSWORD required action UserResource john = AdminApiUtil.findUserByUsernameId(adminClient.realm("test"), "johnkeycloak"); UserRepresentation johnRep = john.toRepresentation(); - Assert.assertEquals(UserModel.RequiredAction.UPDATE_PASSWORD.name(), johnRep.getRequiredActions().get(0)); + Assertions.assertEquals(UserModel.RequiredAction.UPDATE_PASSWORD.name(), johnRep.getRequiredActions().get(0)); // Login as johnkeycloak and update password after login oauth.openLoginForm(); @@ -234,20 +234,20 @@ public void test04UpdateLDAPDirectlyToSetUpdatePassword() { passwordUpdatePage.assertCurrent(); passwordUpdatePage.changePassword("Password1", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); // Check in LDAP, that johnkeycloak does not have pwdLastSet set to 0 assertThat(getPwdLastSetOfJohn(), Matchers.greaterThan(0L)); // Check in admin REST API, that johnkeycloak does not have required action on him johnRep = john.toRepresentation(); - Assert.assertTrue(johnRep.getRequiredActions().isEmpty()); + Assertions.assertTrue(johnRep.getRequiredActions().isEmpty()); // Logout and login again. There should not be a need to update required action anymore john.logout(); oauth.openLoginForm(); loginPage.login("johnkeycloak", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); } @@ -278,20 +278,20 @@ public void test05UpdatePasswordUnsyncedMode() { passwordUpdatePage.assertCurrent(); passwordUpdatePage.changePassword("Password1", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); // Check in LDAP, that pwdLastSet attribute of MSAD user johnkeycloak did not change in MSAD - Assert.assertEquals(pwdLastSetFromLDAP, getPwdLastSetOfJohn()); + Assertions.assertEquals(pwdLastSetFromLDAP, getPwdLastSetOfJohn()); // Check in admin REST API, that johnkeycloak does not have required action on him johnRep = john.toRepresentation(); - Assert.assertTrue(johnRep.getRequiredActions().isEmpty()); + Assertions.assertTrue(johnRep.getRequiredActions().isEmpty()); // Logout and login again. There should not be a need to update required action anymore john.logout(); oauth.openLoginForm(); loginPage.login("johnkeycloak", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); // Switch edit mode back to WRITABLE testingClient.server().run(session -> { @@ -312,7 +312,7 @@ public void test06RegisterNewUser() { // Register user registerPage.register("firstName", "lastName", "email3@check.cz", "registeruser3", "Password1", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); // Check user enabled in MSAD testingClient.server().run(session -> { @@ -321,17 +321,17 @@ public void test06RegisterNewUser() { LDAPObject ldapJohn = ctx.getLdapProvider().loadLDAPUserByUsername(appRealm, "johnkeycloak"); String pwdLastSet = ldapJohn.getAttributeAsString(LDAPConstants.PWD_LAST_SET); - Assert.assertTrue(Long.parseLong(pwdLastSet) > 0); + Assertions.assertTrue(Long.parseLong(pwdLastSet) > 0); String userAccountControl = ldapJohn.getAttributeAsString(LDAPConstants.USER_ACCOUNT_CONTROL); - Assert.assertFalse(UserAccountControl.of(userAccountControl).has(UserAccountControl.ACCOUNTDISABLE)); + Assertions.assertFalse(UserAccountControl.of(userAccountControl).has(UserAccountControl.ACCOUNTDISABLE)); }); // Logout and login again. Success AdminApiUtil.findUserByUsernameId(adminClient.realm("test"), "registeruser3").logout(); oauth.openLoginForm(); loginPage.login("registeruser3", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); } @@ -355,27 +355,27 @@ public void test07DisabledUserInMSADSwitchedToEnabledInKeycloak() { // Check user disabled in both admin REST API and MSAD UserResource john = AdminApiUtil.findUserByUsernameId(adminClient.realm("test"), "johnkeycloak"); UserRepresentation johnRep = john.toRepresentation(); - Assert.assertFalse(johnRep.isEnabled()); + Assertions.assertFalse(johnRep.isEnabled()); - Assert.assertFalse(isJohnEnabledInMSAD()); + Assertions.assertFalse(isJohnEnabledInMSAD()); // Login as johnkeycloak, but user disabled oauth.openLoginForm(); loginPage.login("johnkeycloak", "Password1"); - Assert.assertEquals("Account is disabled, contact your administrator.", loginPage.getError()); + Assertions.assertEquals("Account is disabled, contact your administrator.", loginPage.getError()); // Enable user in admin REST API johnRep.setEnabled(true); john.update(johnRep); // Assert user enabled also in MSAD - Assert.assertTrue(isJohnEnabledInMSAD()); + Assertions.assertTrue(isJohnEnabledInMSAD()); // Logout and login again. There should not be a need to update required action anymore john.logout(); oauth.openLoginForm(); loginPage.login("johnkeycloak", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); } @@ -406,12 +406,12 @@ public void test08DisabledUserUnsyncedMode() { john.update(johnRep); // Check in LDAP, that johnkeycloak is still enabled in MSAD - Assert.assertTrue(isJohnEnabledInMSAD()); + Assertions.assertTrue(isJohnEnabledInMSAD()); // Login as johnkeycloak and see the user is disabled oauth.openLoginForm(); loginPage.login("johnkeycloak", "Password1"); - Assert.assertEquals("Account is disabled, contact your administrator.", loginPage.getError()); + Assertions.assertEquals("Account is disabled, contact your administrator.", loginPage.getError()); // Enable johnkeycloak in admin REST API johnRep = john.toRepresentation(); @@ -419,12 +419,12 @@ public void test08DisabledUserUnsyncedMode() { john.update(johnRep); // Check in LDAP, that johnkeycloak is still enabled in MSAD - Assert.assertTrue(isJohnEnabledInMSAD()); + Assertions.assertTrue(isJohnEnabledInMSAD()); // Login again. User should be enabled oauth.openLoginForm(); loginPage.login("johnkeycloak", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); // Switch edit mode back to WRITABLE testingClient.server().run(session -> { @@ -459,8 +459,8 @@ public void test09DisableUserImportDisabled() { // check user is enabled both locally and on MSAD. UserResource john = AdminApiUtil.findUserByUsernameId(adminClient.realm("test"), "johnkeycloak"); UserRepresentation johnRep = john.toRepresentation(); - Assert.assertTrue(johnRep.isEnabled()); - Assert.assertTrue(isJohnEnabledInMSAD()); + Assertions.assertTrue(johnRep.isEnabled()); + Assertions.assertTrue(isJohnEnabledInMSAD()); // disable user johnkeycloak - it should disable both locally and on MSAD. johnRep.setEnabled(false); @@ -469,12 +469,12 @@ public void test09DisableUserImportDisabled() { // Login as johnkeycloak and see the user is disabled. oauth.openLoginForm(); loginPage.login("johnkeycloak", "Password1"); - Assert.assertEquals("Account is disabled, contact your administrator.", loginPage.getError()); + Assertions.assertEquals("Account is disabled, contact your administrator.", loginPage.getError()); // check user is disabled in all places. johnRep = john.toRepresentation(); - Assert.assertFalse(johnRep.isEnabled()); - Assert.assertFalse(isJohnEnabledInMSAD()); + Assertions.assertFalse(johnRep.isEnabled()); + Assertions.assertFalse(isJohnEnabledInMSAD()); // restore john to enabled state. johnRep.setEnabled(true); @@ -483,7 +483,7 @@ public void test09DisableUserImportDisabled() { // Login again. User should be enabled. oauth.openLoginForm(); loginPage.login("johnkeycloak", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); testingClient.server().run(session -> { // restore import enabled mode in the storage provider. @@ -502,12 +502,12 @@ public void test10DisabledUserSwitchedToEnabledOnMSAD() { johnRep.setEnabled(false); john.update(johnRep); - Assert.assertFalse(isJohnEnabledInMSAD()); + Assertions.assertFalse(isJohnEnabledInMSAD()); // Login as johnkeycloak and see the user is disabled. oauth.openLoginForm(); loginPage.login("johnkeycloak", "Password1"); - Assert.assertEquals("Account is disabled, contact your administrator.", loginPage.getError()); + Assertions.assertEquals("Account is disabled, contact your administrator.", loginPage.getError()); // enable user johnkeycloak in MSAD only testingClient.server().run(session -> { @@ -522,12 +522,12 @@ public void test10DisabledUserSwitchedToEnabledOnMSAD() { ctx.getLdapProvider().getLdapIdentityStore().update(ldapJohn); }); - Assert.assertTrue(isJohnEnabledInMSAD()); + Assertions.assertTrue(isJohnEnabledInMSAD()); // Login again. User should be enabled. oauth.openLoginForm(); loginPage.login("johnkeycloak", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); } private long getPwdLastSetOfJohn() { @@ -541,7 +541,7 @@ private long getPwdLastSetOfJohn() { }); if (pwdLastSett == null) { - Assert.fail("LDAP user johnkeycloak does not have pwdLastSet on him"); + Assertions.fail("LDAP user johnkeycloak does not have pwdLastSet on him"); } // Need to remove double quotes TODO: Ideally fix fetchString method and all the tests, which uses it as it is dummy to need to remove quotes in each test individually... @@ -560,7 +560,7 @@ private boolean isJohnEnabledInMSAD() { }); if (userAccountControls == null) { - Assert.fail("LDAP user johnkeycloak does not have userAccountControl attribute on him"); + Assertions.fail("LDAP user johnkeycloak does not have userAccountControl attribute on him"); } // Need to remove double quotes TODO: Ideally fix fetchString method and all the tests, which uses it as it is dummy to need to remove quotes in each test individually... diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMultipleAttributesTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMultipleAttributesTest.java index 55e4baf3e250..290cffafa646 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMultipleAttributesTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMultipleAttributesTest.java @@ -40,10 +40,10 @@ import org.keycloak.testsuite.util.LDAPTestUtils; import org.keycloak.testsuite.util.oauth.AccessTokenResponse; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; /** @@ -113,7 +113,7 @@ public void testUserImport() { // Test user imported in local storage now UserModel user = session.users().getUserByUsername(appRealm, "jbrown"); - Assert.assertNotNull(UserStoragePrivateUtil.userLocalStorage(session).getUserById(appRealm, user.getId())); + Assertions.assertNotNull(UserStoragePrivateUtil.userLocalStorage(session).getUserById(appRealm, user.getId())); LDAPTestAsserts.assertUserImported(UserStoragePrivateUtil.userLocalStorage(session), appRealm, "jbrown", "James", "Brown", "jbrown@keycloak.org", "88441"); }); } @@ -127,11 +127,11 @@ public void testModel() { RealmModel appRealm = ctx.getRealm(); UserModel user = session.users().getUserByUsername(appRealm, "bwilson"); - Assert.assertEquals("bwilson@keycloak.org", user.getEmail()); - Assert.assertEquals("Bruce", user.getFirstName()); + Assertions.assertEquals("bwilson@keycloak.org", user.getEmail()); + Assertions.assertEquals("Bruce", user.getFirstName()); // There are 2 lastnames in ldif - Assert.assertTrue("Wilson".equals(user.getLastName()) || "Schneider".equals(user.getLastName())); + Assertions.assertTrue("Wilson".equals(user.getLastName()) || "Schneider".equals(user.getLastName())); // Actually there are 2 postalCodes List postalCodes = user.getAttributeStream("postal_code").collect(Collectors.toList()); @@ -173,10 +173,10 @@ private static void assertPostalCodes(List postalCodes, String... expect } - Assert.assertEquals(expectedPostalCodes.length, postalCodes.size()); + Assertions.assertEquals(expectedPostalCodes.length, postalCodes.size()); for (String expected : expectedPostalCodes) { if (!postalCodes.contains(expected)) { - Assert.fail("postalCode '" + expected + "' not in postalCodes: " + postalCodes); + Assertions.fail("postalCode '" + expected + "' not in postalCodes: " + postalCodes); } } } @@ -193,15 +193,15 @@ public void ldapPortalEndToEndTest() { String code = oauth.parseLoginResponse().getCode(); AccessTokenResponse response = oauth.doAccessTokenRequest(code); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); - Assert.assertEquals("Bruce Wilson", idToken.getName()); - Assert.assertEquals("Elm 5", idToken.getOtherClaims().get("street")); + Assertions.assertEquals("Bruce Wilson", idToken.getName()); + Assertions.assertEquals("Elm 5", idToken.getOtherClaims().get("street")); Collection postalCodes = (Collection) idToken.getOtherClaims().get("postal_code"); - Assert.assertEquals(2, postalCodes.size()); - Assert.assertTrue(postalCodes.contains("88441")); - Assert.assertTrue(postalCodes.contains("77332")); + Assertions.assertEquals(2, postalCodes.size()); + Assertions.assertTrue(postalCodes.contains("88441")); + Assertions.assertTrue(postalCodes.contains("77332")); oauth.doLogout(response.getRefreshToken()); @@ -212,15 +212,15 @@ public void ldapPortalEndToEndTest() { code = oauth.parseLoginResponse().getCode(); response = oauth.doAccessTokenRequest(code); - org.keycloak.testsuite.Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); idToken = oauth.verifyIDToken(response.getIdToken()); - Assert.assertEquals("James Brown", idToken.getName()); - Assert.assertNull(idToken.getOtherClaims().get("street")); + Assertions.assertEquals("James Brown", idToken.getName()); + Assertions.assertNull(idToken.getOtherClaims().get("street")); postalCodes = (Collection) idToken.getOtherClaims().get("postal_code"); - Assert.assertEquals(1, postalCodes.size()); - Assert.assertTrue(postalCodes.contains("88441")); - Assert.assertFalse(postalCodes.contains("77332")); + Assertions.assertEquals(1, postalCodes.size()); + Assertions.assertTrue(postalCodes.contains("88441")); + Assertions.assertFalse(postalCodes.contains("77332")); oauth.doLogout(response.getRefreshToken()); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPNoCacheTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPNoCacheTest.java index 8d5e757e003c..6cc56d852e02 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPNoCacheTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPNoCacheTest.java @@ -37,7 +37,6 @@ import org.keycloak.storage.ldap.idm.model.LDAPObject; import org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper; import org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapperFactory; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.client.KeycloakTestingClient; import org.keycloak.testsuite.pages.AppPage; import org.keycloak.testsuite.pages.LoginPage; @@ -53,6 +52,7 @@ import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import static org.hamcrest.CoreMatchers.is; @@ -60,8 +60,8 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; import static org.junit.Assume.assumeThat; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for the scenarios with disabled cache for LDAP provider. This involves scenarios when something is changed directly in LDAP server @@ -129,10 +129,10 @@ private static void checkEmailAddressMultipleVariants(KeycloakTestingClient test RealmModel realm = ctx.getRealm(); UserModel user = session.users().getUserByUsername(realm, username); - Assert.assertNotNull("User not found", user); - Assert.assertEquals(newEmail, user.getEmail()); - Assert.assertEquals(Collections.singletonList(newEmail), user.getAttributes().get(UserModel.EMAIL)); - Assert.assertEquals(Collections.singletonList(newEmail), user.getAttributeStream(UserModel.EMAIL).collect(Collectors.toList())); + Assertions.assertNotNull(user, "User not found"); + Assertions.assertEquals(newEmail, user.getEmail()); + Assertions.assertEquals(Collections.singletonList(newEmail), user.getAttributes().get(UserModel.EMAIL)); + Assertions.assertEquals(Collections.singletonList(newEmail), user.getAttributeStream(UserModel.EMAIL).collect(Collectors.toList())); }); } @@ -210,11 +210,11 @@ private void triggerForgetPasswordForUser(String usernameInput, int expectedCoun assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage()); MimeMessage[] messages = greenMail.getReceivedMessages(); - Assert.assertEquals(expectedCountOfMessages, messages.length); + Assertions.assertEquals(expectedCountOfMessages, messages.length); MimeMessage message = greenMail.getReceivedMessages()[expectedCountOfMessages - 1]; String emailAddress = MailUtils.getRecipient(message); - Assert.assertEquals(expectedEmail, emailAddress); + Assertions.assertEquals(expectedEmail, emailAddress); } private static void changeEmailAddressInLDAP(KeycloakTestingClient testingClient, String newEmail) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPNoMSADTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPNoMSADTest.java index d8f254760581..0d19ee14a5a1 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPNoMSADTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPNoMSADTest.java @@ -35,10 +35,10 @@ import org.keycloak.testsuite.util.LDAPTestConfiguration; import org.keycloak.testsuite.util.LDAPTestUtils; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import static org.hamcrest.MatcherAssert.assertThat; @@ -110,7 +110,7 @@ public void testUpdateWithUnmappedRdnAttribute() { ldapProvider.getLdapIdentityStore().update(john2); // Assert DN was changed - Assert.assertEquals("sn=Doe2", john2.getDn().getFirstRdn().toString()); + Assertions.assertEquals("sn=Doe2", john2.getDn().getFirstRdn().toString()); // Remove "sn" mapper snMapper = appRealm.getComponentsStream(ctx.getLdapModel().getId(), LDAPStorageMapper.class.getName()) @@ -118,7 +118,7 @@ public void testUpdateWithUnmappedRdnAttribute() { .findFirst() .orElse(null); - Assert.assertNotNull(snMapper); + Assertions.assertNotNull(snMapper); appRealm.removeComponent(snMapper); }); @@ -129,7 +129,7 @@ public void testUpdateWithUnmappedRdnAttribute() { RealmModel appRealm = ctx.getRealm(); UserModel johnkeycloak2 = session.users().getUserByUsername(appRealm, "johnkeycloak2"); - Assert.assertNotNull(johnkeycloak2); + Assertions.assertNotNull(johnkeycloak2); johnkeycloak2.setFirstName("foo2"); johnkeycloak2.setLastName("foo"); @@ -159,7 +159,7 @@ public void testMultivaluedRDN() { // Assert DN was changed String rdnAttrName = ldapProvider.getLdapIdentityStore().getConfig().getRdnLdapAttribute(); - Assert.assertEquals("sn=Doe3+" + rdnAttrName + "=johnkeycloak3", john2.getDn().getFirstRdn().toString()); + Assertions.assertEquals("sn=Doe3+" + rdnAttrName + "=johnkeycloak3", john2.getDn().getFirstRdn().toString()); }); // Update some user attributes not mapped to DN. DN won't be changed @@ -172,7 +172,7 @@ public void testMultivaluedRDN() { user.update(userRep); userRep = user.toRepresentation(); - Assert.assertEquals("newemail@email.cz", userRep.getEmail()); + Assertions.assertEquals("newemail@email.cz", userRep.getEmail()); assertFirstRDNEndsWith(userRep, "johnkeycloak3", "Doe3"); // Update some user attributes mapped to DN. DN will be changed @@ -195,10 +195,10 @@ private void assertFirstRDNEndsWith(UserRepresentation user, String expectedUser // Order is not guaranteed and can be dependent on LDAP server, so can't test simple string List rdnKeys = firstRDN.getAllKeys(); - Assert.assertEquals(2, rdnKeys.size()); - Assert.assertEquals(expectedLastNameInDN, firstRDN.getAttrValue("sn")); + Assertions.assertEquals(2, rdnKeys.size()); + Assertions.assertEquals(expectedLastNameInDN, firstRDN.getAttrValue("sn")); rdnKeys.remove("sn"); - Assert.assertEquals(expectedUsernameInDN, firstRDN.getAttrValue(rdnKeys.get(0))); + Assertions.assertEquals(expectedUsernameInDN, firstRDN.getAttrValue(rdnKeys.get(0))); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPPasswordModifyExtensionTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPPasswordModifyExtensionTest.java index 076abaf138b4..a4c75a1f2c57 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPPasswordModifyExtensionTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPPasswordModifyExtensionTest.java @@ -37,10 +37,10 @@ import org.keycloak.testsuite.util.LDAPTestConfiguration; import org.keycloak.testsuite.util.LDAPTestUtils; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; /** @@ -98,18 +98,18 @@ protected void afterImportTestRealm() { @Test public void ldapPasswordChangeWithAccountConsole() throws Exception { - Assert.assertTrue(AccountHelper.updatePassword(testRealm(), "johnkeycloak", "New-password1")); + Assertions.assertTrue(AccountHelper.updatePassword(testRealm(), "johnkeycloak", "New-password1")); oauth.openLoginForm(); loginPage.login("johnkeycloak", "Bad-password1"); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); oauth.openLoginForm(); loginPage.login("johnkeycloak", "New-password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); // Change password back to previous value - Assert.assertTrue(AccountHelper.updatePassword(testRealm(), "johnkeycloak", "Password1")); + Assertions.assertTrue(AccountHelper.updatePassword(testRealm(), "johnkeycloak", "Password1")); } @Test @@ -119,21 +119,21 @@ public void registerUserLdapSuccess() { registerPage.assertCurrent(); registerPage.register("firstName", "lastName", "email2@check.cz", "registerUserSuccess2", "Password1", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); UserRepresentation user = AdminApiUtil.findUserByUsername(testRealm(),"registerUserSuccess2"); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); assertFederatedUserLink(user); - Assert.assertEquals("registerusersuccess2", user.getUsername()); - Assert.assertEquals("firstName", user.getFirstName()); - Assert.assertEquals("lastName", user.getLastName()); - Assert.assertTrue(user.isEnabled()); + Assertions.assertEquals("registerusersuccess2", user.getUsername()); + Assertions.assertEquals("firstName", user.getFirstName()); + Assertions.assertEquals("lastName", user.getLastName()); + Assertions.assertTrue(user.isEnabled()); } protected void assertFederatedUserLink(UserRepresentation user) { - Assert.assertTrue(StorageId.isLocalStorage(user.getId())); - Assert.assertNotNull(user.getFederationLink()); - Assert.assertEquals(user.getFederationLink(), ldapModelId); + Assertions.assertTrue(StorageId.isLocalStorage(user.getId())); + Assertions.assertNotNull(user.getFederationLink()); + Assertions.assertEquals(user.getFederationLink(), ldapModelId); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersFullNameMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersFullNameMapperTest.java index 3b209ea443aa..01402430395f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersFullNameMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersFullNameMapperTest.java @@ -38,9 +38,9 @@ import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; @@ -74,7 +74,7 @@ protected void afterImportTestRealm() { appRealm.getClientByClientId("test-app").setDirectAccessGrantsEnabled(true); // assert that user "fullnameUser" is not in local DB - Assert.assertNull(session.users().getUserByUsername(appRealm, "fullname")); + Assertions.assertNull(session.users().getUserByUsername(appRealm, "fullname")); // Add the user with some fullName into LDAP directly. Ensure that fullName is saved into "cn" attribute in LDAP (currently mapped to model firstName) ComponentModel ldapModel = LDAPTestUtils.getLdapProviderModel(appRealm); @@ -208,7 +208,7 @@ public void testMultiValuedAttributes() { RealmModel appRealm = ctx.getRealm(); UserModel fullnameUser = session.users().getUserByUsername(appRealm, "fullname"); - Assert.assertEquals(Arrays.asList("role1", "role2"), fullnameUser.getAttributeStream("roles").collect(Collectors.toList())); + Assertions.assertEquals(Arrays.asList("role1", "role2"), fullnameUser.getAttributeStream("roles").collect(Collectors.toList())); // Remove "fullnameUser" to prevent conflicts with other tests session.users().removeUser(appRealm, fullnameUser); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersIntegrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersIntegrationTest.java index 4e0e9a9e50bb..d6b73df217a8 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersIntegrationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersIntegrationTest.java @@ -82,13 +82,13 @@ import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Marek Posolda @@ -151,8 +151,8 @@ public void testSyncRegistrationOff() { resp.close(); testRealm().users().get(userId).toRepresentation(); - Assert.assertTrue(StorageId.isLocalStorage(userId)); - Assert.assertNull(newUser1.getFederationLink()); + Assertions.assertTrue(StorageId.isLocalStorage(userId)); + Assertions.assertNull(newUser1.getFederationLink()); // Revert testingClient.server().run(session -> { @@ -194,7 +194,7 @@ public void testSyncRegistrationWithCreateDNRelativeToBaseDN() { // remove the created user try (Response resp = testRealm().users().delete(userId)) { - Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), resp.getStatus()); + Assertions.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), resp.getStatus()); } // revert changes to the LDAP storage provider @@ -217,7 +217,7 @@ public void testSyncRegistrationForceDefault() { } newUser1 = testRealm().users().get(userId).toRepresentation(); assertFederatedUserLink(newUser1); - Assert.assertNotNull(newUser1.getAttributes().get(LDAPConstants.LDAP_ID)); + Assertions.assertNotNull(newUser1.getAttributes().get(LDAPConstants.LDAP_ID)); MatcherAssert.assertThat(newUser1.firstAttribute(LDAPConstants.LDAP_ENTRY_DN), Matchers.containsString("=newuser1,")); String cnValue = testingClient.server().fetch(session -> { @@ -227,13 +227,13 @@ public void testSyncRegistrationForceDefault() { LDAPObject userLdap = ctx.getLdapProvider().loadLDAPUserByUsername(ctx.getRealm(), "newuser1"); return userLdap.getAttributeAsString(cnMapper.get(UserAttributeLDAPStorageMapper.LDAP_ATTRIBUTE)); }, String.class); - Assert.assertEquals("Attribute CN was not set with the forced default value", "", cnValue); + Assertions.assertEquals("", cnValue, "Attribute CN was not set with the forced default value"); // remove the created user try (Response resp = testRealm().users().delete(userId)) { - Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), resp.getStatus()); + Assertions.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), resp.getStatus()); } - Assert.assertTrue(testRealm().users().search("newuser1").isEmpty()); + Assertions.assertTrue(testRealm().users().search("newuser1").isEmpty()); } private static LDAPObject searchObjectInBase(LDAPStorageProvider ldapProvider, String dn, String... attrs) { @@ -268,11 +268,11 @@ public void testSyncRegistrationEmailRDNNoDefault() { // test the user cannot be created without email UserRepresentation newUser1 = AbstractAuthTest.createUserRepresentation("newuser1", null, "newuser1", "newuser1", true); try (Response resp = testRealm().users().create(newUser1)) { - Assert.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), resp.getStatus()); + Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), resp.getStatus()); OAuth2ErrorRepresentation error = resp.readEntity(OAuth2ErrorRepresentation.class); - Assert.assertEquals("unknown_error", error.getError()); + Assertions.assertEquals("unknown_error", error.getError()); } - Assert.assertTrue(testRealm().users().search("newuser1").isEmpty()); + Assertions.assertTrue(testRealm().users().search("newuser1").isEmpty()); // test the user is correctly created with email newUser1 = AbstractAuthTest.createUserRepresentation("newuser1", "newuser1@keycloak.org", "newuser1", "newuser1", true); @@ -282,10 +282,10 @@ public void testSyncRegistrationEmailRDNNoDefault() { } newUser1 = testRealm().users().get(userId).toRepresentation(); assertFederatedUserLink(newUser1); - Assert.assertNotNull(newUser1.getAttributes().get(LDAPConstants.LDAP_ID)); + Assertions.assertNotNull(newUser1.getAttributes().get(LDAPConstants.LDAP_ID)); final String userDN = newUser1.firstAttribute(LDAPConstants.LDAP_ENTRY_DN); MatcherAssert.assertThat(userDN, Matchers.containsString("=newuser1,")); - Assert.assertEquals("newuser1@keycloak.org", newUser1.getEmail()); + Assertions.assertEquals("newuser1@keycloak.org", newUser1.getEmail()); String emailValueInLdap = testingClient.server().fetch(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); ComponentModel ldapModel = LDAPTestUtils.getLdapProviderModel(ctx.getRealm()); @@ -293,7 +293,7 @@ public void testSyncRegistrationEmailRDNNoDefault() { LDAPObject userLdap = ctx.getLdapProvider().loadLDAPUserByUsername(ctx.getRealm(), "newuser1"); return userLdap.getAttributeAsString(emailMapper.get(UserAttributeLDAPStorageMapper.LDAP_ATTRIBUTE)); }, String.class); - Assert.assertEquals("newuser1@keycloak.org", emailValueInLdap); + Assertions.assertEquals("newuser1@keycloak.org", emailValueInLdap); // check description is in ldap assigned String description = testingClient.server().fetch(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); @@ -304,9 +304,9 @@ public void testSyncRegistrationEmailRDNNoDefault() { // remove the created user try (Response resp = testRealm().users().delete(userId)) { - Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), resp.getStatus()); + Assertions.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), resp.getStatus()); } - Assert.assertTrue(testRealm().users().search("newuser1").isEmpty()); + Assertions.assertTrue(testRealm().users().search("newuser1").isEmpty()); } finally { testingClient.server().run(session -> { // revert @@ -342,7 +342,7 @@ public void testSyncRegistrationEmailRDNDefaultValue() { } newUser1 = testRealm().users().get(userId).toRepresentation(); assertFederatedUserLink(newUser1); - Assert.assertNotNull(newUser1.getAttributes().get(LDAPConstants.LDAP_ID)); + Assertions.assertNotNull(newUser1.getAttributes().get(LDAPConstants.LDAP_ID)); MatcherAssert.assertThat(newUser1.firstAttribute(LDAPConstants.LDAP_ENTRY_DN), Matchers.containsString("=newuser1,")); String emailValueInLdap = testingClient.server().fetch(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); @@ -351,13 +351,13 @@ public void testSyncRegistrationEmailRDNDefaultValue() { LDAPObject userLdap = ctx.getLdapProvider().loadLDAPUserByUsername(ctx.getRealm(), "newuser1"); return userLdap.getAttributeAsString(emailMapper.get(UserAttributeLDAPStorageMapper.LDAP_ATTRIBUTE)); }, String.class); - Assert.assertEquals("empty@keycloak.org", emailValueInLdap); + Assertions.assertEquals("empty@keycloak.org", emailValueInLdap); // remove the created user try (Response resp = testRealm().users().delete(userId)) { - Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), resp.getStatus()); + Assertions.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), resp.getStatus()); } - Assert.assertTrue(testRealm().users().search("newuser1").isEmpty()); + Assertions.assertTrue(testRealm().users().search("newuser1").isEmpty()); } finally { testingClient.server().run(session -> { // revert @@ -376,7 +376,7 @@ public void testRemoveImportedUsers() { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); UserModel user = session.users().getUserByUsername(ctx.getRealm(), "johnkeycloak"); - Assert.assertEquals(ctx.getLdapModel().getId(), user.getFederationLink()); + Assertions.assertEquals(ctx.getLdapModel().getId(), user.getFederationLink()); }); adminClient.realm("test").userStorage().removeImportedUsers(ldapModelId); @@ -385,7 +385,7 @@ public void testRemoveImportedUsers() { RealmManager manager = new RealmManager(session); RealmModel appRealm = manager.getRealmByName("test"); UserModel user = UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "johnkeycloak"); - Assert.assertNull(user); + Assertions.assertNull(user); }); } @@ -395,7 +395,7 @@ public void zzTestUnlinkUsers() { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); UserModel user = session.users().getUserByUsername(ctx.getRealm(), "johnkeycloak"); - Assert.assertEquals(ctx.getLdapModel().getId(), user.getFederationLink()); + Assertions.assertEquals(ctx.getLdapModel().getId(), user.getFederationLink()); }); adminClient.realm("test").userStorage().unlink(ldapModelId); @@ -403,8 +403,8 @@ public void zzTestUnlinkUsers() { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); UserModel user = session.users().getUserByUsername(ctx.getRealm(), "johnkeycloak"); - Assert.assertNotNull(user); - Assert.assertNull(user.getFederationLink()); + Assertions.assertNotNull(user); + Assertions.assertNull(user.getFederationLink()); }); } @@ -433,7 +433,7 @@ private void loginSuccessAndLogout(String username, String password) { events.clear(); oauth.openLoginForm(); loginPage.login(username, password); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); AccessTokenResponse tokenResponse = sendTokenRequestAndGetResponse(events.poll()); oauth.logoutForm().idTokenHint(tokenResponse.getIdToken()).withRedirect().open(); @@ -454,15 +454,15 @@ public void caseInsensitiveSearch() { // search by username List users = testRealm().users().search("JBROwn4", 0, 10); UserRepresentation user4 = users.get(0); - Assert.assertEquals("jbrown4", user4.getUsername()); - Assert.assertEquals("jbrown4@email.org", user4.getEmail()); + Assertions.assertEquals("jbrown4", user4.getUsername()); + Assertions.assertEquals("jbrown4@email.org", user4.getEmail()); // search by email users = testRealm().users().search("JBROwn5@eMAil.org", 0, 10); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); UserRepresentation user5 = users.get(0); - Assert.assertEquals("jbrown5", user5.getUsername()); - Assert.assertEquals("jbrown5@email.org", user5.getEmail()); + Assertions.assertEquals("jbrown5", user5.getUsername()); + Assertions.assertEquals("jbrown5@email.org", user5.getEmail()); } @Test @@ -475,7 +475,7 @@ public void testUsernameAndEmailCaseSensitiveIfImportDisabled() { LDAPObject ldapObject = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "JBrown8", "John", "Brown8", "JBrown8@Email.org", null, "1234"); LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), ldapObject, "Password1"); UserModel model = session.users().searchForUserStream(ctx.getRealm(), Map.of(UserModel.USERNAME, "JBrown8")).findAny().orElse(null); - Assert.assertNotNull(model); + Assertions.assertNotNull(model); assertEquals("JBrown8", model.getUsername()); assertEquals("JBrown8@Email.org", model.getEmail()); ldapModel.setImportEnabled(true); @@ -493,7 +493,7 @@ public void testUsernameAndEmailCaseInSensitiveIfImportEnabled() { LDAPObject ldapObject = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "JBrown9", "John", "Brown9", "JBrown9@Email.org", null, "1234"); LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), ldapObject, "Password1"); UserModel model = session.users().searchForUserStream(ctx.getRealm(), Map.of(UserModel.USERNAME, "JBrown9")).findAny().orElse(null); - Assert.assertNotNull(model); + Assertions.assertNotNull(model); assertEquals("jbrown9", model.getUsername()); assertEquals("jbrown9@email.org", model.getEmail()); }); @@ -509,8 +509,8 @@ public void deleteFederationLink() throws Exception { grantPage.assertCurrent(); grantPage.accept(); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); ComponentRepresentation ldapRep = testRealm().components().component(ldapModelId).toRepresentation(); testRealm().components().component(ldapModelId).remove(); @@ -520,7 +520,7 @@ public void deleteFederationLink() throws Exception { loginPage.login("johnkeycloak", "Password1"); loginPage.assertCurrent(); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); // Re-add LDAP provider Map cfg = getLDAPRule().getConfig(); @@ -543,8 +543,8 @@ public void loginClassic() { oauth.openLoginForm(); loginPage.login("marykeycloak", "password-app"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); } @@ -553,24 +553,24 @@ public void loginLdap() { oauth.openLoginForm(); loginPage.login("johnkeycloak", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation userRepresentation = AccountHelper.getUserRepresentation(adminClient.realm(TEST_REALM_NAME), "johnkeycloak"); - Assert.assertEquals("John", userRepresentation.getFirstName()); - Assert.assertEquals("Doe", userRepresentation.getLastName()); - Assert.assertEquals("john@email.org", userRepresentation.getEmail()); + Assertions.assertEquals("John", userRepresentation.getFirstName()); + Assertions.assertEquals("Doe", userRepresentation.getLastName()); + Assertions.assertEquals("john@email.org", userRepresentation.getEmail()); } @Test public void loginLdapWithDirectGrant() throws Exception { AccessTokenResponse response = oauth.doPasswordGrantRequest("johnkeycloak", "Password1"); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); response = oauth.doPasswordGrantRequest("johnkeycloak", ""); - Assert.assertEquals(400, response.getStatusCode()); + Assertions.assertEquals(400, response.getStatusCode()); } @Test @@ -578,31 +578,31 @@ public void loginLdapWithEmail() { oauth.openLoginForm(); loginPage.login("john@email.org", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); } @Test public void loginLdapWithoutPassword() { oauth.openLoginForm(); loginPage.login("john@email.org", ""); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); } @Test public void ldapPasswordChangeWithAccountConsole() throws Exception { - Assert.assertTrue(AccountHelper.updatePassword(testRealm(), "johnkeycloak", "New-password1")); + Assertions.assertTrue(AccountHelper.updatePassword(testRealm(), "johnkeycloak", "New-password1")); oauth.openLoginForm(); loginPage.login("johnkeycloak", "Bad-password1"); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); oauth.openLoginForm(); loginPage.login("johnkeycloak", "New-password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); // Change password back to previous value - Assert.assertTrue(AccountHelper.updatePassword(testRealm(), "johnkeycloak", "Password1")); + Assertions.assertTrue(AccountHelper.updatePassword(testRealm(), "johnkeycloak", "Password1")); } @@ -620,7 +620,7 @@ public void ldapPasswordChangeWithAdminEndpointAndRequiredAction() throws Except username, "Password1", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); UserResource user = AdminApiUtil.findUserByUsernameId(testRealm(), username); String userId = user.toRepresentation().getId(); @@ -680,13 +680,13 @@ private void assertPasswordConfiguredThroughLDAPOnly(UserResource user) { List storedCredentials = user.credentials(); assertEquals(1, storedCredentials.size()); for (CredentialRepresentation credential : storedCredentials) { - Assert.assertTrue(PasswordCredentialModel.TYPE.equals(credential.getType())); - Assert.assertNotNull(credential.getFederationLink()); + Assertions.assertTrue(PasswordCredentialModel.TYPE.equals(credential.getType())); + Assertions.assertNotNull(credential.getFederationLink()); } // Assert password is stored in the LDAP List userStorageCredentials = user.getConfiguredUserStorageCredentialTypes(); - Assert.assertTrue(userStorageCredentials.contains(PasswordCredentialModel.TYPE)); + Assertions.assertTrue(userStorageCredentials.contains(PasswordCredentialModel.TYPE)); } @Test @@ -698,12 +698,12 @@ public void registerExistingLdapUser() { // check existing username registerPage.register("firstName", "lastName", "email@mail.cz", "existing", "Password1", "Password1"); registerPage.assertCurrent(); - Assert.assertEquals("Username already exists.", registerPage.getInputAccountErrors().getUsernameError()); + Assertions.assertEquals("Username already exists.", registerPage.getInputAccountErrors().getUsernameError()); // Check existing email registerPage.register("firstName", "lastName", "existing@email.org", "nonExisting", "Password1", "Password1"); registerPage.assertCurrent(); - Assert.assertEquals("Email already exists.", registerPage.getInputAccountErrors().getEmailError()); + Assertions.assertEquals("Email already exists.", registerPage.getInputAccountErrors().getEmailError()); } @@ -735,7 +735,7 @@ public void testLDAPUserDeletionImport() { LDAPTestUtils.removeLDAPUserByUsername(ctx.getLdapProvider(), ctx.getRealm(), config, "maryjane"); // Make sure the deletion took place. - Assert.assertEquals(0, session.users().searchForUserStream(ctx.getRealm(), Map.of(UserModel.SEARCH, "mary yram")).count()); + Assertions.assertEquals(0, session.users().searchForUserStream(ctx.getRealm(), Map.of(UserModel.SEARCH, "mary yram")).count()); }); } @@ -747,22 +747,22 @@ public void registerUserLdapSuccess() { registerPage.assertCurrent(); registerPage.register("firstName", "lastName", "email2@check.cz", "register-user-success2", "Password1", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); UserRepresentation user = AdminApiUtil.findUserByUsername(testRealm(),"register-user-success2"); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); assertFederatedUserLink(user); - Assert.assertEquals("register-user-success2", user.getUsername()); - Assert.assertEquals("firstName", user.getFirstName()); - Assert.assertEquals("lastName", user.getLastName()); - Assert.assertTrue(user.isEnabled()); + Assertions.assertEquals("register-user-success2", user.getUsername()); + Assertions.assertEquals("firstName", user.getFirstName()); + Assertions.assertEquals("lastName", user.getLastName()); + Assertions.assertTrue(user.isEnabled()); } protected void assertFederatedUserLink(UserRepresentation user) { - Assert.assertTrue(StorageId.isLocalStorage(user.getId())); - Assert.assertNotNull(user.getFederationLink()); - Assert.assertEquals(user.getFederationLink(), ldapModelId); + Assertions.assertTrue(StorageId.isLocalStorage(user.getId())); + Assertions.assertNotNull(user.getFederationLink()); + Assertions.assertEquals(user.getFederationLink(), ldapModelId); } @@ -784,20 +784,20 @@ public void testCaseSensitiveAttributeName() { // Fetch user from LDAP and check that postalCode is filled UserModel user = session.users().getUserByUsername(appRealm, "johnzip"); String postalCode = user.getFirstAttribute("postal_code"); - Assert.assertEquals("12398", postalCode); + Assertions.assertEquals("12398", postalCode); }); // modify postal_code in the user RealmResource realm = testRealm(); List users = realm.users().search("johnzip", true); - Assert.assertEquals("User not found", 1, users.size()); + Assertions.assertEquals(1, users.size(), "User not found"); UserRepresentation user = users.iterator().next(); - Assert.assertEquals("Incorrect postal code", Collections.singletonList("12398"), user.getAttributes().get("postal_code")); + Assertions.assertEquals(Collections.singletonList("12398"), user.getAttributes().get("postal_code"), "Incorrect postal code"); UserResource userRes = realm.users().get(user.getId()); user.getAttributes().put("postal_code", Collections.singletonList("9876")); userRes.update(user); user = userRes.toRepresentation(); - Assert.assertEquals("Incorrect postal code", Collections.singletonList("9876"), user.getAttributes().get("postal_code")); + Assertions.assertEquals(Collections.singletonList("9876"), user.getAttributes().get("postal_code"), "Incorrect postal code"); // ensure the ldap contains the correct value testingClient.server().run(session -> { @@ -806,7 +806,7 @@ public void testCaseSensitiveAttributeName() { LDAPStorageProvider ldapProvider = ctx.getLdapProvider(); LDAPObject ldapUser = ldapProvider.loadLDAPUserByUsername(appRealm, "johnzip"); - Assert.assertEquals("Incorrect postal code", "9876", ldapUser.getAttributeAsString("POstalCode")); + Assertions.assertEquals("9876", ldapUser.getAttributeAsString("POstalCode"), "Incorrect postal code"); }); } @@ -861,7 +861,7 @@ public void testHardcodedAttributeMapperTest() throws Exception { registerPage.assertCurrent(); registerPage.register("firstName", "lastName", "email34@check.cz", "register123", "Password1", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); @@ -869,8 +869,8 @@ public void testHardcodedAttributeMapperTest() throws Exception { // See that user don't yet have any description UserModel user = LDAPTestAsserts.assertUserImported(session.users(), appRealm, "register123", "firstName", "lastName", "email34@check.cz", null); - Assert.assertNull(user.getFirstAttribute("desc")); - Assert.assertNull(user.getFirstAttribute("description")); + Assertions.assertNull(user.getFirstAttribute("desc")); + Assertions.assertNull(user.getFirstAttribute("description")); // Remove hardcoded mapper for "description" and create regular userAttribute mapper for description ComponentModel hardcodedMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "hardcodedAttr-description"); @@ -890,11 +890,11 @@ public void testHardcodedAttributeMapperTest() throws Exception { // See that user don't yet have any description UserModel user = session.users().getUserByUsername(appRealm, "register123"); - Assert.assertNull(user.getFirstAttribute("description")); - Assert.assertNotNull(user.getFirstAttribute("desc")); + Assertions.assertNull(user.getFirstAttribute("description")); + Assertions.assertNotNull(user.getFirstAttribute("desc")); String desc = user.getFirstAttribute("desc"); - Assert.assertTrue(desc.startsWith("some-")); - Assert.assertEquals(35, desc.length()); + Assertions.assertTrue(desc.startsWith("some-")); + Assertions.assertEquals(35, desc.length()); // Remove mapper for "description" ComponentModel userAttrMapper = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "desc-attribute-mapper"); @@ -912,7 +912,7 @@ public void testHardcodedRoleMapper() { // assert that user "johnkeycloak" doesn't have hardcoded role UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); - Assert.assertFalse(john.hasRole(hardcodedRole)); + Assertions.assertFalse(john.hasRole(hardcodedRole)); ComponentModel hardcodedMapperModel = KeycloakModelUtils.createComponentModel("hardcoded role", ctx.getLdapModel().getId(), HardcodedLDAPRoleStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(), @@ -928,12 +928,12 @@ public void testHardcodedRoleMapper() { // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); - Assert.assertTrue(john.hasRole(hardcodedRole)); + Assertions.assertTrue(john.hasRole(hardcodedRole)); // Can't remove user from hardcoded role try { john.deleteRoleMapping(hardcodedRole); - Assert.fail("Didn't expected to remove role mapping"); + Assertions.fail("Didn't expected to remove role mapping"); } catch (ModelException expected) { } @@ -954,7 +954,7 @@ public void testHardcodedGroupMapper() { // assert that user "johnkeycloak" doesn't have hardcoded group UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); - Assert.assertFalse(john.isMemberOf(hardcodedGroup)); + Assertions.assertFalse(john.isMemberOf(hardcodedGroup)); ComponentModel hardcodedMapperModel = KeycloakModelUtils.createComponentModel("hardcoded group", ctx.getLdapModel().getId(), HardcodedLDAPGroupStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(), @@ -970,12 +970,12 @@ public void testHardcodedGroupMapper() { // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); - Assert.assertTrue(john.isMemberOf(hardcodedGroup)); + Assertions.assertTrue(john.isMemberOf(hardcodedGroup)); // Can't remove user from hardcoded role try { john.leaveGroup(hardcodedGroup); - Assert.fail("Didn't expected to leave group"); + Assertions.fail("Didn't expected to leave group"); } catch (ModelException expected) { } @@ -1002,10 +1002,10 @@ public void testImportExistingUserFromLDAP() throws Exception { // Try to import the duplicated LDAP user into Keycloak oauth.openLoginForm(); loginPage.login("mary-duplicatemail", "password"); - Assert.assertEquals("Email already exists.", loginPage.getError()); + Assertions.assertEquals("Email already exists.", loginPage.getError()); loginPage.login("mary1@email.org", "password"); - Assert.assertEquals("Username already exists.", loginPage.getError()); + Assertions.assertEquals("Username already exists.", loginPage.getError()); loginSuccessAndLogout("marynoemail", "Password1"); } @@ -1028,34 +1028,34 @@ public void testReadonly() { RealmModel appRealm = ctx.getRealm(); UserModel user = session.users().getUserByUsername(appRealm, "johnkeycloak"); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); try { user.setEmail("error@error.com"); - Assert.fail("should fail"); + Assertions.fail("should fail"); } catch (ReadOnlyException e) { } try { user.setLastName("Berk"); - Assert.fail("should fail"); + Assertions.fail("should fail"); } catch (ReadOnlyException e) { } try { user.setFirstName("Bilbo"); - Assert.fail("should fail"); + Assertions.fail("should fail"); } catch (ReadOnlyException e) { } try { UserCredentialModel cred = UserCredentialModel.password("PoopyPoop1", true); user.credentialManager().updateCredential(cred); - Assert.fail("should fail"); + Assertions.fail("should fail"); } catch (ReadOnlyException e) { } - Assert.assertTrue(session.users().removeUser(appRealm, user)); + Assertions.assertTrue(session.users().removeUser(appRealm, user)); }); // Revert @@ -1066,7 +1066,7 @@ public void testReadonly() { ctx.getLdapModel().put(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.WRITABLE.toString()); appRealm.updateComponent(ctx.getLdapModel()); - Assert.assertEquals(UserStorageProvider.EditMode.WRITABLE.toString(), + Assertions.assertEquals(UserStorageProvider.EditMode.WRITABLE.toString(), appRealm.getComponent(ctx.getLdapModel().getId()).getConfig().getFirst(LDAPConstants.EDIT_MODE)); }); } @@ -1084,7 +1084,7 @@ public void testRemoveFederatedUser() { assertFederatedUserLink(user); testRealm().users().get(user.getId()).remove(); user = AdminApiUtil.findUserByUsername(testRealm(), "register-user-success2"); - Assert.assertNull(user); + Assertions.assertNull(user); } @Test @@ -1100,33 +1100,33 @@ public void testSearch() { LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username11", "John11", "Doel11", "user11@email.org", null, "124"); // Users are not at local store at this moment - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username1")); - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username2")); - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username3")); - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username4")); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username1")); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username2")); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username3")); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username4")); // search by username (we use a terminal operation on the stream to ensure it is consumed) - Assert.assertEquals(1, session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "\"username1\"")).count()); + Assertions.assertEquals(1, session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "\"username1\"")).count()); LDAPTestAsserts.assertUserImported(UserStoragePrivateUtil.userLocalStorage(session), appRealm, "username1", "John1", "Doel1", "user1@email.org", "121"); // search by email (we use a terminal operation on the stream to ensure it is consumed) - Assert.assertEquals(1, session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "user2@email.org")).count()); + Assertions.assertEquals(1, session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "user2@email.org")).count()); LDAPTestAsserts.assertUserImported(UserStoragePrivateUtil.userLocalStorage(session), appRealm, "username2", "John2", "Doel2", "user2@email.org", "122"); // search by lastName (we use a terminal operation on the stream to ensure it is consumed) - Assert.assertEquals(1, session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "Doel3")).count()); + Assertions.assertEquals(1, session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "Doel3")).count()); LDAPTestAsserts.assertUserImported(UserStoragePrivateUtil.userLocalStorage(session), appRealm, "username3", "John3", "Doel3", "user3@email.org", "123"); // search by firstName + lastName (we use a terminal operation on the stream to ensure it is consumed) - Assert.assertEquals(1, session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "John4 Doel4")).count()); + Assertions.assertEquals(1, session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "John4 Doel4")).count()); LDAPTestAsserts.assertUserImported(UserStoragePrivateUtil.userLocalStorage(session), appRealm, "username4", "John4", "Doel4", "user4@email.org", "124"); // search by a string that matches multiple fields. Should still return the one entity it matches. - Assert.assertEquals(1, session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "*11*")).count()); + Assertions.assertEquals(1, session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "*11*")).count()); LDAPTestAsserts.assertUserImported(UserStoragePrivateUtil.userLocalStorage(session), appRealm, "username11", "John11", "Doel11", "user11@email.org", "124"); // search by a string that has special characters. Should succeed with an empty set, but no exceptions. - Assert.assertEquals(0, session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH,"John)")).count()); + Assertions.assertEquals(0, session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH,"John)")).count()); }); } @@ -1160,7 +1160,7 @@ public void testSearchWithCustomLDAPFilter() { session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "user7@email.org")).count(); session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "John7 Doel7")).count(); - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username7")); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username7")); // Remove custom filter ctx.getLdapModel().getConfig().remove(LDAPConstants.CUSTOM_USER_SEARCH_FILTER); @@ -1202,11 +1202,11 @@ public void testSearchWithCustomLDAPFilter() { // search by id using custom filter. Must return the user UserModel testUser5 = session.users().getUserById(appRealm, user5Id); - Assert.assertNotNull(testUser5); + Assertions.assertNotNull(testUser5); // search by id using custom filter. Must not return the user UserModel testUser7 = session.users().getUserById(appRealm, user7Id); - Assert.assertNull(testUser7); + Assertions.assertNull(testUser7); // Remove custom filter ctx.getLdapModel().getConfig().remove(LDAPConstants.CUSTOM_USER_SEARCH_FILTER); @@ -1232,17 +1232,17 @@ public void testUnsynced() throws Exception { session.getContext().setRealm(appRealm); UserModel user = session.users().getUserByUsername(appRealm, "johnkeycloak"); - Assert.assertNotNull(user); - Assert.assertNotNull(user.getFederationLink()); - Assert.assertEquals(user.getFederationLink(), ctx.getLdapModel().getId()); + Assertions.assertNotNull(user); + Assertions.assertNotNull(user.getFederationLink()); + Assertions.assertEquals(user.getFederationLink(), ctx.getLdapModel().getId()); UserCredentialModel cred = UserCredentialModel.password("Candycand1", true); user.credentialManager().updateCredential(cred); CredentialModel userCredentialValueModel = user.credentialManager().getStoredCredentialsByTypeStream(PasswordCredentialModel.TYPE) .findFirst().orElse(null); - Assert.assertNotNull(userCredentialValueModel); - Assert.assertEquals(PasswordCredentialModel.TYPE, userCredentialValueModel.getType()); - Assert.assertTrue(user.credentialManager().isValid(cred)); + Assertions.assertNotNull(userCredentialValueModel); + Assertions.assertEquals(PasswordCredentialModel.TYPE, userCredentialValueModel.getType()); + Assertions.assertTrue(user.credentialManager().isValid(cred)); // LDAP password is still unchanged try { @@ -1260,11 +1260,11 @@ public void testUnsynced() throws Exception { List storedCredentials = userResource.credentials().stream() .map(CredentialRepresentation::getType) .collect(Collectors.toList()); - Assert.assertTrue(storedCredentials.contains(PasswordCredentialModel.TYPE)); + Assertions.assertTrue(storedCredentials.contains(PasswordCredentialModel.TYPE)); // Assert password is supported in the LDAP too. List userStorageCredentials = userResource.getConfiguredUserStorageCredentialTypes(); - Assert.assertTrue(userStorageCredentials.contains(PasswordCredentialModel.TYPE)); + Assertions.assertTrue(userStorageCredentials.contains(PasswordCredentialModel.TYPE)); testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); @@ -1272,11 +1272,11 @@ public void testUnsynced() throws Exception { UserModel user = session.users().getUserByUsername(appRealm, "johnkeycloak"); // User is deleted just locally - Assert.assertTrue(session.users().removeUser(appRealm, user)); + Assertions.assertTrue(session.users().removeUser(appRealm, user)); // Assert user not available locally, but will be reimported from LDAP once searched - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "johnkeycloak")); - Assert.assertNotNull(session.users().getUserByUsername(appRealm, "johnkeycloak")); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "johnkeycloak")); + Assertions.assertNotNull(session.users().getUserByUsername(appRealm, "johnkeycloak")); }); // change username @@ -1292,11 +1292,11 @@ public void testUnsynced() throws Exception { // check user is found just once List users = testRealm().users().search("johnkeycloak", 0, 2); - Assert.assertEquals("More than one user is found", 1, users.size()); + Assertions.assertEquals(1, users.size(), "More than one user is found"); List components = testRealm().components().query( testRealm().toRepresentation().getId(), UserStorageProvider.class.getName(), "test-ldap"); - Assert.assertEquals("LDAP component not found", 1, users.size()); - Assert.assertEquals(components.iterator().next().getId(), users.iterator().next().getFederationLink()); + Assertions.assertEquals(1, users.size(), "LDAP component not found"); + Assertions.assertEquals(components.iterator().next().getId(), users.iterator().next().getFederationLink()); // Revert testingClient.server().run(session -> { @@ -1308,7 +1308,7 @@ public void testUnsynced() throws Exception { appRealm.updateComponent(ctx.getLdapModel()); - Assert.assertEquals(UserStorageProvider.EditMode.WRITABLE.toString(), appRealm.getComponent(ctx.getLdapModel().getId()).getConfig().getFirst(LDAPConstants.EDIT_MODE)); + Assertions.assertEquals(UserStorageProvider.EditMode.WRITABLE.toString(), appRealm.getComponent(ctx.getLdapModel().getId()).getConfig().getFirst(LDAPConstants.EDIT_MODE)); }); } @@ -1328,9 +1328,9 @@ public void testSearchByAttributes() { LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username10", "John10", "Doel10", "user10@email.org", null, "1210"); // Users are not at local store at this moment - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username8")); - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username9")); - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username10")); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username8")); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username9")); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username10")); // search for user by attribute List users = ctx.getLdapProvider().searchForUserByUserAttributeStream(appRealm, ATTRIBUTE, ATTRIBUTE_VALUE) @@ -1348,7 +1348,7 @@ public void testSearchByAttributes() { LDAPTestAsserts.assertUserImported(UserStoragePrivateUtil.userLocalStorage(session), appRealm, "username8", "John8", "Doel8", "user8@email.org", ATTRIBUTE_VALUE); LDAPTestAsserts.assertUserImported(UserStoragePrivateUtil.userLocalStorage(session), appRealm, "username9", "John9", "Doel9", "user9@email.org", ATTRIBUTE_VALUE); // but the one not looked up is not - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username10")); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "username10")); }); } @@ -1367,7 +1367,7 @@ public void testSearchWithPartiallyCachedUser() { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); UserModel user = session.users().getUserByUsername(appRealm, "johnkeycloak"); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); user.getAttributes(); }); @@ -1377,7 +1377,7 @@ public void testSearchWithPartiallyCachedUser() { adminClient.realm("test").users().search(null, 0, 10, false); List users = adminClient.realm("test").users().search("johnkeycloak", 0, 10, false); - Assert.assertTrue(users.stream().anyMatch(userRepresentation -> "johnkeycloak".equals(userRepresentation.getUsername()))); + Assertions.assertTrue(users.stream().anyMatch(userRepresentation -> "johnkeycloak".equals(userRepresentation.getUsername()))); } @@ -1400,7 +1400,7 @@ public void testLDAPUserRefreshCache() { // Fetch user from LDAP and check that postalCode is filled UserModel user = session.users().getUserByUsername(appRealm, "johndirect"); String postalCode = user.getFirstAttribute("postal_code"); - Assert.assertEquals("1234", postalCode); + Assertions.assertEquals("1234", postalCode); LDAPTestUtils.removeLDAPUserByUsername(ldapProvider, appRealm, ldapProvider.getLdapIdentityStore().getConfig(), "johndirect"); }); @@ -1413,8 +1413,8 @@ public void testLDAPUserRefreshCache() { CachedUserModel user = (CachedUserModel) session.users().getUserByUsername(appRealm, "johndirect"); String postalCode = user.getFirstAttribute("postal_code"); String email = user.getEmail(); - Assert.assertEquals("1234", postalCode); - Assert.assertEquals("johndirect@email.org", email); + Assertions.assertEquals("1234", postalCode); + Assertions.assertEquals("johndirect@email.org", email); }); setTimeOffset(60 * 20); // 20 minutes into future, cache will be invalidated @@ -1423,7 +1423,7 @@ public void testLDAPUserRefreshCache() { RealmModel appRealm = new RealmManager(session).getRealmByName("test"); session.getContext().setRealm(appRealm); UserModel user = session.users().getUserByUsername(appRealm, "johndirect"); - Assert.assertNull(user); + Assertions.assertNull(user); }); } finally { resetTimeOffset(); @@ -1444,8 +1444,8 @@ public void testCacheUser() { UserModel testedUser = session.users().getUserByUsername(ctx.getRealm(), "testCacheUser"); String usserId = testedUser.getId(); - Assert.assertNotNull(usserId); - Assert.assertFalse(usserId.isEmpty()); + Assertions.assertNotNull(usserId); + Assertions.assertFalse(usserId.isEmpty()); return usserId; }, String.class); @@ -1454,7 +1454,7 @@ public void testCacheUser() { RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME); UserModel testedUser = session.users().getUserById(appRealm, userId); - Assert.assertFalse(testedUser instanceof CachedUserModel); + Assertions.assertFalse(testedUser instanceof CachedUserModel); }); // restore default cache policy @@ -1470,21 +1470,21 @@ public void testCacheUser() { testingClient.server().run(session -> { RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME); UserModel testedUser = session.users().getUserById(appRealm, userId); - Assert.assertTrue(testedUser instanceof CachedUserModel); + Assertions.assertTrue(testedUser instanceof CachedUserModel); }); setTimeOffset(60 * 5); // 5 minutes in future, should be cached still testingClient.server().run(session -> { RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME); UserModel testedUser = session.users().getUserById(appRealm, userId); - Assert.assertTrue(testedUser instanceof CachedUserModel); + Assertions.assertTrue(testedUser instanceof CachedUserModel); }); setTimeOffset(60 * 10); // 10 minutes into future, cache will be invalidated testingClient.server().run(session -> { RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME); UserModel testedUser = session.users().getUserByUsername(appRealm, "thor"); - Assert.assertFalse(testedUser instanceof CachedUserModel); + Assertions.assertFalse(testedUser instanceof CachedUserModel); }); setTimeOffset(0); @@ -1496,11 +1496,11 @@ public void testAlwaysReadValueFromLdapCached() throws Exception { testingClient.testing().setTestingInfinispanTimeService(); // import user from the ldap johnkeycloak and cache it reading it by id List users = testRealm().users().search("johnkeycloak", true); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); UserRepresentation john = users.iterator().next(); - Assert.assertEquals("Doe", john.getLastName()); + Assertions.assertEquals("Doe", john.getLastName()); john = testRealm().users().get(john.getId()).toRepresentation(); - Assert.assertEquals("Doe", john.getLastName()); + Assertions.assertEquals("Doe", john.getLastName()); // modify the sn of the user directly in ldap testingClient.server().run(session -> { @@ -1512,22 +1512,22 @@ public void testAlwaysReadValueFromLdapCached() throws Exception { // it's cached so it should be still the initial one users = testRealm().users().search("johnkeycloak", true); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); john = users.iterator().next(); - Assert.assertEquals("Doe", john.getLastName()); + Assertions.assertEquals("Doe", john.getLastName()); john = testRealm().users().get(john.getId()).toRepresentation(); - Assert.assertEquals("Doe", john.getLastName()); + Assertions.assertEquals("Doe", john.getLastName()); // expire the cache which is 10 minutes setTimeOffset(610); // new sn should be present users = testRealm().users().search("johnkeycloak", true); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); john = users.iterator().next(); - Assert.assertEquals("sn-modified", john.getLastName()); + Assertions.assertEquals("sn-modified", john.getLastName()); john = testRealm().users().get(john.getId()).toRepresentation(); - Assert.assertEquals("sn-modified", john.getLastName()); + Assertions.assertEquals("sn-modified", john.getLastName()); } finally { // revert testingClient.server().run(session -> { @@ -1554,11 +1554,11 @@ public void testAlwaysReadValueFromLdapNoCache() throws Exception { try { // import user from the ldap johnkeycloak List users = testRealm().users().search("johnkeycloak", true); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); UserRepresentation john = users.iterator().next(); - Assert.assertEquals("Doe", john.getLastName()); + Assertions.assertEquals("Doe", john.getLastName()); john = testRealm().users().get(john.getId()).toRepresentation(); - Assert.assertEquals("Doe", john.getLastName()); + Assertions.assertEquals("Doe", john.getLastName()); // modify the sn of the user directly in ldap testingClient.server().run(session -> { @@ -1571,11 +1571,11 @@ public void testAlwaysReadValueFromLdapNoCache() throws Exception { // no cache, so it should be validated and new data received users = testRealm().users().search("johnkeycloak", true); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); john = users.iterator().next(); - Assert.assertEquals("sn-modified", john.getLastName()); + Assertions.assertEquals("sn-modified", john.getLastName()); john = testRealm().users().get(john.getId()).toRepresentation(); - Assert.assertEquals("sn-modified", john.getLastName()); + Assertions.assertEquals("sn-modified", john.getLastName()); } finally { // revert cache to default max-liespan setting testingClient.server().run(session -> { @@ -1606,7 +1606,7 @@ public void testEmailVerifiedFromImport(){ testingClient.server().run(session -> { RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME); Optional userVerified = session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "john@test.com")).findFirst(); - Assert.assertTrue(userVerified.get().isEmailVerified()); + Assertions.assertTrue(userVerified.get().isEmailVerified()); }); //Test untrusted email option @@ -1623,7 +1623,7 @@ public void testEmailVerifiedFromImport(){ testingClient.server().run(session -> { RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME); Optional userNotVerified = session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "john2@test.com")).findFirst(); - Assert.assertFalse(userNotVerified.get().isEmailVerified()); + Assertions.assertFalse(userNotVerified.get().isEmailVerified()); }); } @@ -1666,7 +1666,7 @@ public void updateLDAPUsernameTest() { RealmModel testRealm = ctx.getRealm(); UserModel importedUser = UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(testRealm, "beckybecks"); - Assert.assertNotNull(importedUser); + Assertions.assertNotNull(importedUser); // Update user 'beckybecks' in LDAP LDAPObject becky = ctx.getLdapProvider().loadLDAPUserByUsername(testRealm, importedUser.getUsername()); @@ -1683,7 +1683,7 @@ public void updateLDAPUsernameTest() { oauth.openLoginForm(); loginPage.login("beckybecks", "Password1"); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); @@ -1691,14 +1691,14 @@ public void updateLDAPUsernameTest() { // The original username is not possible to use as username was changed in LDAP. // However the call to LDAPStorageProvider.loadAndValidateUser shouldn't delete the user just because his username changed in LDAP UserModel user = session.users().getUserByUsername(ctx.getRealm(), "beckybecks"); - Assert.assertNull(user); + Assertions.assertNull(user); // Assert user can be found with new username from LDAP. And it is same user as before user = session.users().getUserByUsername(ctx.getRealm(), "beckyupdated"); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); String newKeycloakUserId = user.getId(); // Need to remove double quotes from server response - Assert.assertEquals(origKeycloakUserId.replace("\"",""), newKeycloakUserId); + Assertions.assertEquals(origKeycloakUserId.replace("\"",""), newKeycloakUserId); }); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPReadOnlyTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPReadOnlyTest.java index 23189e666483..6be7fea1637f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPReadOnlyTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPReadOnlyTest.java @@ -53,18 +53,18 @@ import org.hamcrest.MatcherAssert; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import org.openqa.selenium.By; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test for more advanced scenarios related to LDAP read-only mode @@ -140,8 +140,8 @@ public void testReadOnlyWithTOTPEnabled() { totpPage.configure(totp.generateTOTP(totpPage.getTotpSecret())); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); // Revert TOTP setTotpRequirementExecutionForRealm(AuthenticationExecutionModel.Requirement.CONDITIONAL, AuthenticationExecutionModel.Requirement.ALTERNATIVE); @@ -163,8 +163,8 @@ public void testReadOnlyUserDoesNotThrowIfUnchanged() { // assert user = AdminApiUtil.findUserByUsernameId(testRealm(), "johnkeycloak"); userRepresentation = user.toRepresentation(); - Assert.assertEquals(userRepresentation.getRequiredActions().size(), 1); - Assert.assertEquals(userRepresentation.getRequiredActions().get(0), UserModel.RequiredAction.CONFIGURE_TOTP.toString()); + Assertions.assertEquals(userRepresentation.getRequiredActions().size(), 1); + Assertions.assertEquals(userRepresentation.getRequiredActions().get(0), UserModel.RequiredAction.CONFIGURE_TOTP.toString()); // reset userRepresentation.setRequiredActions(Collections.emptyList()); @@ -214,7 +214,7 @@ public void testReadOnlyUserGetsPermanentlyLocked(){ UserRepresentation user = adminClient.realm("test").users().search("johnkeycloak", 0, 1).get(0); Map bruteForceStatus = testRealm().attackDetection().bruteForceUserStatus(user.getId()); - assertFalse("User should not be disabled by brute force.", (boolean) bruteForceStatus.get("disabled")); + assertFalse((boolean) bruteForceStatus.get("disabled"), "User should not be disabled by brute force."); assertTrue(user.isEnabled()); // Lock user (permanently) and make sure the number of failures matches failure factor @@ -226,7 +226,7 @@ public void testReadOnlyUserGetsPermanentlyLocked(){ // Make sure user is now disabled bruteForceStatus = testRealm().attackDetection().bruteForceUserStatus(user.getId()); - assertTrue("User should be disabled by brute force.", (boolean) bruteForceStatus.get("disabled")); + assertTrue((boolean) bruteForceStatus.get("disabled"), "User should be disabled by brute force."); user = adminClient.realm("test").users().search("johnkeycloak", 0, 1).get(0); assertFalse(user.isEnabled()); @@ -248,7 +248,7 @@ public void loginInvalidPassword(String username) { loginPage.assertCurrent(); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); events.clear(); } @@ -275,8 +275,8 @@ private void setTotpRequirementExecutionForRealm(AuthenticationExecutionModel.Re } protected void assertFederatedUserLink(UserRepresentation user) { - Assert.assertTrue(StorageId.isLocalStorage(user.getId())); - Assert.assertNotNull(user.getFederationLink()); - Assert.assertEquals(user.getFederationLink(), ldapModelId); + Assertions.assertTrue(StorageId.isLocalStorage(user.getId())); + Assertions.assertNotNull(user.getFederationLink()); + Assertions.assertEquals(user.getFederationLink(), ldapModelId); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPRoleMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPRoleMapperTest.java index 2ab3d9e6e926..61648c170b8d 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPRoleMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPRoleMapperTest.java @@ -29,10 +29,10 @@ import org.keycloak.testsuite.util.LDAPTestUtils; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import static org.hamcrest.MatcherAssert.assertThat; @@ -66,29 +66,29 @@ public void test01RoleMapperRealmRoles() { // check users UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); - Assert.assertNotNull(john); + Assertions.assertNotNull(john); assertThat(john.getRealmRoleMappingsStream().map(RoleModel::getName).collect(Collectors.toSet()), Matchers.containsInAnyOrder("group1", "group2")); UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); - Assert.assertNotNull(mary); + Assertions.assertNotNull(mary); assertThat(mary.getRealmRoleMappingsStream().map(RoleModel::getName).collect(Collectors.toSet()), Matchers.containsInAnyOrder("group1", "group2")); UserModel rob = session.users().getUserByUsername(appRealm, "robkeycloak"); - Assert.assertNotNull(rob); + Assertions.assertNotNull(rob); assertThat(rob.getRealmRoleMappingsStream().map(RoleModel::getName).collect(Collectors.toSet()), Matchers.containsInAnyOrder("group1")); UserModel james = session.users().getUserByUsername(appRealm, "jameskeycloak"); - Assert.assertNotNull(james); + Assertions.assertNotNull(james); assertThat(james.getRealmRoleMappingsStream().collect(Collectors.toSet()), Matchers.empty()); // check groups RoleModel group1 = appRealm.getRole("group1"); - Assert.assertNotNull(group1); + Assertions.assertNotNull(group1); assertThat(session.users().getRoleMembersStream(appRealm, group1).map(UserModel::getUsername).collect(Collectors.toSet()), Matchers.containsInAnyOrder("johnkeycloak", "marykeycloak", "robkeycloak")); RoleModel group2 = appRealm.getRole("group2"); - Assert.assertNotNull(group2); + Assertions.assertNotNull(group2); assertThat(session.users().getRoleMembersStream(appRealm, group2).map(UserModel::getUsername).collect(Collectors.toSet()), Matchers.containsInAnyOrder("johnkeycloak", "marykeycloak")); RoleModel group3 = appRealm.getRole("group3"); - Assert.assertNotNull(group3); + Assertions.assertNotNull(group3); assertThat(session.users().getRoleMembersStream(appRealm, group3).collect(Collectors.toSet()), Matchers.empty()); }); } @@ -114,29 +114,29 @@ public void test02RoleMapperClientRoles() { // check users UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); - Assert.assertNotNull(john); + Assertions.assertNotNull(john); assertThat(john.getClientRoleMappingsStream(rolesClient).map(RoleModel::getName).collect(Collectors.toSet()), Matchers.containsInAnyOrder("group1", "group2")); UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); - Assert.assertNotNull(mary); + Assertions.assertNotNull(mary); assertThat(mary.getClientRoleMappingsStream(rolesClient).map(RoleModel::getName).collect(Collectors.toSet()), Matchers.containsInAnyOrder("group1", "group2")); UserModel rob = session.users().getUserByUsername(appRealm, "robkeycloak"); - Assert.assertNotNull(rob); + Assertions.assertNotNull(rob); assertThat(rob.getClientRoleMappingsStream(rolesClient).map(RoleModel::getName).collect(Collectors.toSet()), Matchers.containsInAnyOrder("group1")); UserModel james = session.users().getUserByUsername(appRealm, "jameskeycloak"); - Assert.assertNotNull(james); + Assertions.assertNotNull(james); assertThat(james.getClientRoleMappingsStream(rolesClient).map(RoleModel::getName).collect(Collectors.toSet()), Matchers.empty()); // check groups RoleModel group1 = rolesClient.getRole("group1"); - Assert.assertNotNull(group1); + Assertions.assertNotNull(group1); assertThat(session.users().getRoleMembersStream(appRealm, group1).map(UserModel::getUsername).collect(Collectors.toSet()), Matchers.containsInAnyOrder("johnkeycloak", "marykeycloak", "robkeycloak")); RoleModel group2 = rolesClient.getRole("group2"); - Assert.assertNotNull(group2); + Assertions.assertNotNull(group2); assertThat(session.users().getRoleMembersStream(appRealm, group2).map(UserModel::getUsername).collect(Collectors.toSet()), Matchers.containsInAnyOrder("johnkeycloak", "marykeycloak")); RoleModel group3 = rolesClient.getRole("group3"); - Assert.assertNotNull(group3); + Assertions.assertNotNull(group3); assertThat(session.users().getRoleMembersStream(appRealm, group3).collect(Collectors.toSet()), Matchers.empty()); } finally { @@ -170,16 +170,16 @@ public void test03RoleMapperClientRoles() { // check users UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); - Assert.assertNotNull(john); + Assertions.assertNotNull(john); assertThat(john.getClientRoleMappingsStream(rolesClient).map(RoleModel::getName).collect(Collectors.toSet()), Matchers.empty()); UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); - Assert.assertNotNull(mary); + Assertions.assertNotNull(mary); assertThat(mary.getClientRoleMappingsStream(rolesClient).map(RoleModel::getName).collect(Collectors.toSet()), Matchers.empty()); UserModel rob = session.users().getUserByUsername(appRealm, "robkeycloak"); - Assert.assertNotNull(rob); + Assertions.assertNotNull(rob); assertThat(rob.getClientRoleMappingsStream(rolesClient).map(RoleModel::getName).collect(Collectors.toSet()), Matchers.empty()); UserModel james = session.users().getUserByUsername(appRealm, "jameskeycloak"); - Assert.assertNotNull(james); + Assertions.assertNotNull(james); assertThat(james.getClientRoleMappingsStream(rolesClient).map(RoleModel::getName).collect(Collectors.toSet()), Matchers.empty()); // check groups diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPRoleMappingsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPRoleMappingsTest.java index c9b97b7029b4..1892c0f9db16 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPRoleMappingsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPRoleMappingsTest.java @@ -40,10 +40,10 @@ import org.keycloak.testsuite.util.LDAPRule; import org.keycloak.testsuite.util.LDAPTestUtils; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; /** @@ -158,27 +158,27 @@ public void test01_ldapOnlyRoleMappings() { UserModel johnDb = UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "johnkeycloak"); Set johnDbRoles = johnDb.getRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertFalse(johnDbRoles.contains(realmRole1)); - Assert.assertFalse(johnDbRoles.contains(realmRole2)); - Assert.assertFalse(johnDbRoles.contains(realmRole3)); - Assert.assertFalse(johnDbRoles.contains(financeRole1)); + Assertions.assertFalse(johnDbRoles.contains(realmRole1)); + Assertions.assertFalse(johnDbRoles.contains(realmRole2)); + Assertions.assertFalse(johnDbRoles.contains(realmRole3)); + Assertions.assertFalse(johnDbRoles.contains(financeRole1)); // 3 - Check that role mappings are in LDAP and hence available through federation Set johnRoles = john.getRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertTrue(johnRoles.contains(realmRole1)); - Assert.assertFalse(johnRoles.contains(realmRole2)); - Assert.assertTrue(johnRoles.contains(realmRole3)); - Assert.assertTrue(johnRoles.contains(financeRole1)); + Assertions.assertTrue(johnRoles.contains(realmRole1)); + Assertions.assertFalse(johnRoles.contains(realmRole2)); + Assertions.assertTrue(johnRoles.contains(realmRole3)); + Assertions.assertTrue(johnRoles.contains(financeRole1)); Set johnRealmRoles = john.getRealmRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertEquals(2, johnRealmRoles.size()); - Assert.assertTrue(johnRealmRoles.contains(realmRole1)); - Assert.assertTrue(johnRealmRoles.contains(realmRole3)); + Assertions.assertEquals(2, johnRealmRoles.size()); + Assertions.assertTrue(johnRealmRoles.contains(realmRole1)); + Assertions.assertTrue(johnRealmRoles.contains(realmRole3)); Set johnFinanceRoles = john.getClientRoleMappingsStream(financeApp).collect(Collectors.toSet()); - Assert.assertEquals(1, johnFinanceRoles.size()); - Assert.assertTrue(johnFinanceRoles.contains(financeRole1)); + Assertions.assertEquals(1, johnFinanceRoles.size()); + Assertions.assertTrue(johnFinanceRoles.contains(financeRole1)); // 4 - Delete some role mappings and check they are deleted @@ -187,10 +187,10 @@ public void test01_ldapOnlyRoleMappings() { john.deleteRoleMapping(financeRole1); johnRoles = john.getRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertFalse(johnRoles.contains(realmRole1)); - Assert.assertFalse(johnRoles.contains(realmRole2)); - Assert.assertFalse(johnRoles.contains(realmRole3)); - Assert.assertFalse(johnRoles.contains(financeRole1)); + Assertions.assertFalse(johnRoles.contains(realmRole1)); + Assertions.assertFalse(johnRoles.contains(realmRole2)); + Assertions.assertFalse(johnRoles.contains(realmRole3)); + Assertions.assertFalse(johnRoles.contains(financeRole1)); // Cleanup mary.deleteRoleMapping(realmRole2); @@ -230,21 +230,21 @@ public void test02_readOnlyRoleMappings() { // Assert that mary has both LDAP and DB mapped roles Set maryRoles = mary.getRealmRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertTrue(maryRoles.contains(realmRole1)); - Assert.assertTrue(maryRoles.contains(realmRole2)); - Assert.assertTrue(maryRoles.contains(realmRole3)); + Assertions.assertTrue(maryRoles.contains(realmRole1)); + Assertions.assertTrue(maryRoles.contains(realmRole2)); + Assertions.assertTrue(maryRoles.contains(realmRole3)); // Assert that access through DB will have just DB mapped role UserModel maryDB = UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "marykeycloak"); Set maryDBRoles = maryDB.getRealmRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertFalse(maryDBRoles.contains(realmRole1)); - Assert.assertFalse(maryDBRoles.contains(realmRole2)); - Assert.assertTrue(maryDBRoles.contains(realmRole3)); + Assertions.assertFalse(maryDBRoles.contains(realmRole1)); + Assertions.assertFalse(maryDBRoles.contains(realmRole2)); + Assertions.assertTrue(maryDBRoles.contains(realmRole3)); mary.deleteRoleMapping(realmRole3); try { mary.deleteRoleMapping(realmRole1); - Assert.fail("It wasn't expected to successfully delete LDAP role mappings in READ_ONLY mode"); + Assertions.fail("It wasn't expected to successfully delete LDAP role mappings in READ_ONLY mode"); } catch (ModelException expected) { } @@ -261,9 +261,9 @@ public void test02_readOnlyRoleMappings() { // Assert role mappings is not available Set maryRoles = mary.getRealmRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertFalse(maryRoles.contains(appRealm.getRole("realmRole1"))); - Assert.assertFalse(maryRoles.contains(appRealm.getRole("realmRole2"))); - Assert.assertFalse(maryRoles.contains(appRealm.getRole("realmRole3"))); + Assertions.assertFalse(maryRoles.contains(appRealm.getRole("realmRole1"))); + Assertions.assertFalse(maryRoles.contains(appRealm.getRole("realmRole2"))); + Assertions.assertFalse(maryRoles.contains(appRealm.getRole("realmRole3"))); }); } @@ -294,30 +294,30 @@ public void test03_importRoleMappings() { realmRole3 = appRealm.addRole("realmRole3"); } Set robRoles = rob.getRealmRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertTrue(robRoles.contains(realmRole1)); - Assert.assertTrue(robRoles.contains(realmRole2)); - Assert.assertFalse(robRoles.contains(realmRole3)); + Assertions.assertTrue(robRoles.contains(realmRole1)); + Assertions.assertTrue(robRoles.contains(realmRole2)); + Assertions.assertFalse(robRoles.contains(realmRole3)); // Add some role mappings in model and check that user has it rob.grantRole(realmRole3); robRoles = rob.getRealmRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertTrue(robRoles.contains(realmRole3)); + Assertions.assertTrue(robRoles.contains(realmRole3)); // Delete some role mappings in LDAP and check that it doesn't have any effect and user still has role deleteRoleMappingsInLDAP(roleMapper, robLdap, "realmRole1"); deleteRoleMappingsInLDAP(roleMapper, robLdap, "realmRole2"); robRoles = rob.getRealmRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertTrue(robRoles.contains(realmRole1)); - Assert.assertTrue(robRoles.contains(realmRole2)); + Assertions.assertTrue(robRoles.contains(realmRole1)); + Assertions.assertTrue(robRoles.contains(realmRole2)); // Delete role mappings through model and verifies that user doesn't have them anymore rob.deleteRoleMapping(realmRole1); rob.deleteRoleMapping(realmRole2); rob.deleteRoleMapping(realmRole3); robRoles = rob.getRealmRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertFalse(robRoles.contains(realmRole1)); - Assert.assertFalse(robRoles.contains(realmRole2)); - Assert.assertFalse(robRoles.contains(realmRole3)); + Assertions.assertFalse(robRoles.contains(realmRole1)); + Assertions.assertFalse(robRoles.contains(realmRole2)); + Assertions.assertFalse(robRoles.contains(realmRole3)); }); } @@ -351,8 +351,8 @@ public void test04_syncRoleMappings() { // make sure user is cached. UserModel johnRoleMapper = session.users().getUserByUsername(appRealm, "johnrolemapper"); - Assert.assertNotNull(johnRoleMapper); - Assert.assertEquals(0, johnRoleMapper.getRealmRoleMappingsStream().count()); + Assertions.assertNotNull(johnRoleMapper); + Assertions.assertEquals(0, johnRoleMapper.getRealmRoleMappingsStream().count()); }); @@ -375,8 +375,8 @@ public void test04_syncRoleMappings() { RoleModel realmRole2 = appRealm.getRole("realmRole2"); Set johnRoles = johnRoleMapper.getRealmRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertFalse(johnRoles.contains(realmRole1)); - Assert.assertFalse(johnRoles.contains(realmRole2)); + Assertions.assertFalse(johnRoles.contains(realmRole1)); + Assertions.assertFalse(johnRoles.contains(realmRole2)); }); testingClient.server().run(session -> { @@ -408,8 +408,8 @@ public void test04_syncRoleMappings() { RoleModel realmRole2 = appRealm.getRole("realmRole2"); Set johnRoles = johnRoleMapper.getRealmRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertTrue(johnRoles.contains(realmRole1)); - Assert.assertTrue(johnRoles.contains(realmRole2)); + Assertions.assertTrue(johnRoles.contains(realmRole1)); + Assertions.assertTrue(johnRoles.contains(realmRole2)); }); } @@ -459,8 +459,8 @@ public void test05_getRolesFromUserMemberOfStrategyTest() throws Exception { RoleModel realmRole1 = appRealm.getRole("realmRole1"); RoleModel realmRole2 = appRealm.getRole("realmRole2"); - Assert.assertTrue(carlosRoles.contains(realmRole1)); - Assert.assertFalse(carlosRoles.contains(realmRole2)); + Assertions.assertTrue(carlosRoles.contains(realmRole1)); + Assertions.assertFalse(carlosRoles.contains(realmRole2)); }); // Revert mappers @@ -481,8 +481,8 @@ public void test06_newUserDefaultRolesImportModeTest() throws Exception { RoleModel defaultRole = appRealm.getRole("realmRole1"); RoleModel realmRole2 = appRealm.getRole("realmRole2"); - Assert.assertNotNull(defaultRole); - Assert.assertNotNull(realmRole2); + Assertions.assertNotNull(defaultRole); + Assertions.assertNotNull(realmRole2); // Set a default role on the realm appRealm.addToDefaultRoles(defaultRole); @@ -490,12 +490,12 @@ public void test06_newUserDefaultRolesImportModeTest() throws Exception { Set davidRoles = david.getRealmRoleMappingsStream().collect(Collectors.toSet()); // default role is not assigned directly - Assert.assertFalse(davidRoles.contains(defaultRole)); - Assert.assertFalse(davidRoles.contains(realmRole2)); + Assertions.assertFalse(davidRoles.contains(defaultRole)); + Assertions.assertFalse(davidRoles.contains(realmRole2)); // but david should have the role as effective - Assert.assertTrue(david.hasRole(defaultRole)); - Assert.assertFalse(david.hasRole(realmRole2)); + Assertions.assertTrue(david.hasRole(defaultRole)); + Assertions.assertFalse(david.hasRole(realmRole2)); }); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSamlIdPInitiatedVaryingLetterCaseTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSamlIdPInitiatedVaryingLetterCaseTest.java index 48536f72cb33..73d55b6cc5ed 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSamlIdPInitiatedVaryingLetterCaseTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSamlIdPInitiatedVaryingLetterCaseTest.java @@ -49,7 +49,6 @@ import org.keycloak.storage.ldap.idm.model.LDAPObject; import org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper; import org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapperFactory; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.broker.KcSamlBrokerConfiguration; import org.keycloak.testsuite.pages.AppPage; import org.keycloak.testsuite.updaters.Creator; @@ -65,6 +64,7 @@ import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_SAML_ALIAS; @@ -214,8 +214,8 @@ public void loginLDAPTest() { oauth.openLoginForm(); loginPage.login(USER_NAME_LDAP, USER_PASSWORD); appPage.assertCurrent(); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); String code = oauth.parseLoginResponse().getCode(); String idTokenHint = oauth.doAccessTokenRequest(code).getIdToken(); appPage.logout(idTokenHint); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSearchForUsersPaginationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSearchForUsersPaginationTest.java index 4fe6e94f6d82..4f0d942a91f6 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSearchForUsersPaginationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSearchForUsersPaginationTest.java @@ -39,10 +39,10 @@ import org.keycloak.testsuite.util.LDAPTestUtils; import org.keycloak.testsuite.util.UserBuilder; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import static org.hamcrest.MatcherAssert.assertThat; @@ -149,12 +149,12 @@ public void testSearchLDAPStreet() { Set usernames = testRealm().users().searchByAttributes("street:\"Acacia Avenue\"") .stream().map(UserRepresentation::getUsername) .collect(Collectors.toSet()); - Assert.assertEquals(Set.of("john", "john00", "john01"), usernames); + Assertions.assertEquals(Set.of("john", "john00", "john01"), usernames); usernames = testRealm().users().searchByAttributes(0, 5, true, true, "street:\"Acacia Avenue\"") .stream().map(UserRepresentation::getUsername) .collect(Collectors.toSet()); - Assert.assertEquals(Set.of("john", "john00", "john01"), usernames); + Assertions.assertEquals(Set.of("john", "john00", "john01"), usernames); } @Test @@ -163,37 +163,37 @@ public void testSearchNonExact() { .stream() .map(UserRepresentation::getUsername) .collect(Collectors.toSet()); - Assert.assertEquals(Set.of("john01", "john11"), usernames); + Assertions.assertEquals(Set.of("john01", "john11"), usernames); usernames = testRealm().users().searchByEmail("1@email.org", false) .stream() .map(UserRepresentation::getUsername) .collect(Collectors.toSet()); - Assert.assertEquals(Set.of("john01", "john11"), usernames); + Assertions.assertEquals(Set.of("john01", "john11"), usernames); } @Test public void testSearchLDAPLdapId() { UserRepresentation john = testRealm().users().search("john", true).stream().findAny().orElse(null); - Assert.assertNotNull(john); - Assert.assertNotNull(john.firstAttribute(LDAPConstants.LDAP_ID)); + Assertions.assertNotNull(john); + Assertions.assertNotNull(john.firstAttribute(LDAPConstants.LDAP_ID)); Set usernames = testRealm().users() .searchByAttributes(LDAPConstants.LDAP_ID + ":" + john.firstAttribute(LDAPConstants.LDAP_ID)) .stream().map(UserRepresentation::getUsername) .collect(Collectors.toSet()); - Assert.assertEquals(Set.of("john"), usernames); + Assertions.assertEquals(Set.of("john"), usernames); } @Test public void testSearchLDAPLdapEntryDn() { UserRepresentation john = testRealm().users().search("john", true).stream().findAny().orElse(null); - Assert.assertNotNull(john); - Assert.assertNotNull(john.firstAttribute(LDAPConstants.LDAP_ENTRY_DN)); + Assertions.assertNotNull(john); + Assertions.assertNotNull(john.firstAttribute(LDAPConstants.LDAP_ENTRY_DN)); Set usernames = testRealm().users() .searchByAttributes(LDAPConstants.LDAP_ENTRY_DN + ":" + john.firstAttribute(LDAPConstants.LDAP_ENTRY_DN)) .stream().map(UserRepresentation::getUsername) .collect(Collectors.toSet()); - Assert.assertEquals(Set.of("john"), usernames); + Assertions.assertEquals(Set.of("john"), usernames); } public void testDuplicateEmailInDatabase() { @@ -204,7 +204,7 @@ public void testDuplicateEmailInDatabase() { .username("jdoe").firstName("John").lastName("Doe") .email("john14@email.org") .build())); - Assert.assertNotNull("User not created", userId); + Assertions.assertNotNull(userId, "User not created"); getCleanup().addUserId(userId); } finally { setLDAPEnabled(true); @@ -213,9 +213,9 @@ public void testDuplicateEmailInDatabase() { List search = adminClient.realm(TEST_REALM_NAME).users() .search("john14@email.org", null, null) .stream().collect(Collectors.toList()); - Assert.assertEquals("Incorrect users found", 1, search.size()); - Assert.assertEquals("Incorrect User", "jdoe", search.get(0).getUsername()); - Assert.assertTrue("Duplicated user created", adminClient.realm(TEST_REALM_NAME).users().search("john", true).isEmpty()); + Assertions.assertEquals(1, search.size(), "Incorrect users found"); + Assertions.assertEquals("jdoe", search.get(0).getUsername(), "Incorrect User"); + Assertions.assertTrue(adminClient.realm(TEST_REALM_NAME).users().search("john", true).isEmpty(), "Duplicated user created"); } @Test @@ -232,31 +232,31 @@ public void testSearchByUserAttributeDoesNotTriggerUserReimport() { // check the user doesn't yet exist in Keycloak UserProvider localProvider = ((DefaultDatastoreProvider) session.getProvider(DatastoreProvider.class)).userLocalStorage(); UserModel user = localProvider.getUserByUsername(session.getContext().getRealm(), "bwayne"); - Assert.assertNull(user); + Assertions.assertNull(user); // import the user by searching for its username, and check it has the timestamp set by one of the LDAP mappers. user = session.users().getUserByUsername(session.getContext().getRealm(), "bwayne"); - Assert.assertNotNull(user); - Assert.assertNotNull(user.getAttributes().get("createTimestamp")); + Assertions.assertNotNull(user); + Assertions.assertNotNull(user.getAttributes().get("createTimestamp")); // remove the create timestamp from the user. user.removeAttribute("createTimestamp"); user = localProvider.getUserByUsername(session.getContext().getRealm(), "bwayne"); - Assert.assertNull(user.getAttributes().get("createTimestamp")); + Assertions.assertNull(user.getAttributes().get("createTimestamp")); }); testingClient.server(TEST_REALM_NAME).run(session -> { // search users by user attribute - the existing user SHOULD NOT be re-imported (GHI #32870) List users = session.users().searchForUserByUserAttributeStream(session.getContext().getRealm(), "street", "Gotham Avenue").toList(); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); UserModel user = users.get(0); // create timestamp won't be null because it is provided directly from the LDAP mapper, so it should still be visible. - Assert.assertNotNull(user.getAttributes().get("createTimestamp")); + Assertions.assertNotNull(user.getAttributes().get("createTimestamp")); // however, the local stored attribute should not have been updated (i.e. user should not have been fully re-imported). UserProvider localProvider = ((DefaultDatastoreProvider) session.getProvider(DatastoreProvider.class)).userLocalStorage(); user = localProvider.getUserByUsername(session.getContext().getRealm(), "bwayne"); - Assert.assertNull(user.getAttributes().get("createTimestamp")); + Assertions.assertNull(user.getAttributes().get("createTimestamp")); }); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSpecialCharsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSpecialCharsTest.java index c61fbffba6f4..bd66a1d8f0bb 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSpecialCharsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSpecialCharsTest.java @@ -38,10 +38,10 @@ import org.keycloak.testsuite.util.LDAPTestConfiguration; import org.keycloak.testsuite.util.LDAPTestUtils; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import static org.keycloak.testsuite.util.LDAPTestUtils.getGroupDescriptionLDAPAttrName; @@ -112,7 +112,7 @@ private void assertContainsUsername(List users, String usern }).findFirst().isPresent(); if (!found) { - Assert.fail("Username " + username + " not found in the list"); + Assertions.fail("Username " + username + " not found in the list"); } } @@ -122,16 +122,16 @@ public void test02_loginWithSpecialCharacter() { // Fail login with wildcard oauth.openLoginForm(); loginPage.login("john*", "Password1"); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); // Fail login with wildcard loginPage.login("j*", "Password1"); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); // Success login as username exactly match loginPage.login("jamees,key*cložak)ppp", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); } @@ -146,46 +146,46 @@ public void test03_specialCharUserJoiningSpecialCharGroup() { appRealm.updateComponent(mapperModel); UserModel specialUser = session.users().getUserByUsername(appRealm, "jamees,key*cložak)ppp"); - Assert.assertNotNull(specialUser); + Assertions.assertNotNull(specialUser); // 1 - Grant some groups in LDAP // This group should already exists as it was imported from LDAP GroupModel specialGroup = KeycloakModelUtils.findGroupByPath(session, appRealm, "/group-spec,ia*l_characžter)s"); - Assert.assertNotNull(specialGroup); + Assertions.assertNotNull(specialGroup); specialUser.joinGroup(specialGroup); GroupModel groupWithSlashes = KeycloakModelUtils.findGroupByPath(session, appRealm, "/group/with/three/slashes"); - Assert.assertNotNull(groupWithSlashes); + Assertions.assertNotNull(groupWithSlashes); specialUser.joinGroup(groupWithSlashes); // 2 - Check that group mappings are in LDAP and hence available through federation Set userGroups = specialUser.getGroupsStream().collect(Collectors.toSet()); - Assert.assertEquals(2, userGroups.size()); - Assert.assertTrue(userGroups.contains(specialGroup)); + Assertions.assertEquals(2, userGroups.size()); + Assertions.assertTrue(userGroups.contains(specialGroup)); // 3 - Check through userProvider List groupMembers = session.users().getGroupMembersStream(appRealm, specialGroup, 0, 10) .collect(Collectors.toList()); - Assert.assertEquals(1, groupMembers.size()); - Assert.assertEquals("jamees,key*cložak)ppp", groupMembers.get(0).getUsername()); + Assertions.assertEquals(1, groupMembers.size()); + Assertions.assertEquals("jamees,key*cložak)ppp", groupMembers.get(0).getUsername()); groupMembers = session.users().getGroupMembersStream(appRealm, groupWithSlashes, 0, 10) .collect(Collectors.toList()); - Assert.assertEquals(1, groupMembers.size()); - Assert.assertEquals("jamees,key*cložak)ppp", groupMembers.get(0).getUsername()); + Assertions.assertEquals(1, groupMembers.size()); + Assertions.assertEquals("jamees,key*cložak)ppp", groupMembers.get(0).getUsername()); // 4 - Delete some group mappings and check they are deleted specialUser.leaveGroup(specialGroup); specialUser.leaveGroup(groupWithSlashes); - Assert.assertEquals(0, specialUser.getGroupsStream().count()); + Assertions.assertEquals(0, specialUser.getGroupsStream().count()); }); } @@ -210,20 +210,20 @@ public void test04_loginWithSpecialCharacterUsingSameUUIDThanUsernameAttribute() try { // assert the user is found and UUID is the name List users = adminClient.realm(TEST_REALM_NAME).users().search("jamees,key*cložak)ppp", true); - Assert.assertEquals("User not found", 1, users.size()); + Assertions.assertEquals(1, users.size(), "User not found"); UserRepresentation jamees = users.iterator().next(); - Assert.assertEquals("Incorrect user", "jamees,key*cložak)ppp", jamees.getUsername()); - Assert.assertEquals("Incorrect UUID attribute", "jamees,key*cložak)ppp", jamees.firstAttribute(LDAPConstants.LDAP_ID)); + Assertions.assertEquals("jamees,key*cložak)ppp", jamees.getUsername(), "Incorrect user"); + Assertions.assertEquals("jamees,key*cložak)ppp", jamees.firstAttribute(LDAPConstants.LDAP_ID), "Incorrect UUID attribute"); // Fail login with wildcard oauth.openLoginForm(); loginPage.login("jamees*", "Password1"); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); // Success login as username exactly match loginPage.login("jamees,key*cložak)ppp", "Password1"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); } finally { // Revert config changes to be back to previous UUID attribute ComponentRepresentation ldapRep = testRealm().components().component(ldapModelId).toRepresentation(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSyncTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSyncTest.java index 88b341b5a18f..c722def5c99f 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSyncTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSyncTest.java @@ -59,10 +59,10 @@ import org.keycloak.testsuite.util.WaitUtils; import org.awaitility.Awaitility; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import static org.hamcrest.MatcherAssert.assertThat; @@ -147,13 +147,13 @@ public void test01LDAPSync() { LDAPTestAsserts.assertUserImported(userProvider, testRealm, "user5", "User5FN", "User5LN", "user5@email.org", "125"); // Assert lastSync time updated - Assert.assertTrue(ctx.getLdapModel().getLastSync() > 0); + Assertions.assertTrue(ctx.getLdapModel().getLastSync() > 0); ((StorageProviderRealmModel) testRealm).getUserStorageProvidersStream().forEachOrdered(persistentFedModel -> { if (LDAPStorageProviderFactory.PROVIDER_NAME.equals(persistentFedModel.getProviderId())) { - Assert.assertTrue(persistentFedModel.getLastSync() > 0); + Assertions.assertTrue(persistentFedModel.getLastSync() > 0); } else { // Dummy provider has still 0 - Assert.assertEquals(0, persistentFedModel.getLastSync()); + Assertions.assertEquals(0, persistentFedModel.getLastSync()); } }); }); @@ -176,7 +176,7 @@ public void test01LDAPSync() { // Assert still old users in local provider LDAPTestAsserts.assertUserImported(userProvider, testRealm, "user5", "User5FN", "User5LN", "user5@email.org", "125"); - Assert.assertNull(userProvider.getUserByUsername(testRealm, "user6")); + Assertions.assertNull(userProvider.getUserByUsername(testRealm, "user6")); // Trigger partial sync, one added and updates because a partial sync did not happen yet, only a full sync KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory(); @@ -264,7 +264,7 @@ public void test02duplicateUsernameAndEmailSync() { // Assert syncing from LDAP fails due to duplicated username SynchronizationResult result = UserStoragePrivateUtil.runFullSync(session.getKeycloakSessionFactory(), ctx.getLdapModel()); - Assert.assertEquals(1, result.getFailed()); + Assertions.assertEquals(1, result.getFailed()); // Remove "user7" from LDAP LDAPObject duplicatedLdapUser = ctx.getLdapProvider().loadLDAPUserByUsername(ctx.getRealm(), "user7"); @@ -279,8 +279,8 @@ public void test02duplicateUsernameAndEmailSync() { // Assert syncing from LDAP fails due to duplicated email SynchronizationResult result = UserStoragePrivateUtil.runFullSync(session.getKeycloakSessionFactory(), ctx.getLdapModel()); - Assert.assertEquals(1, result.getFailed()); - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(ctx.getRealm(), "user7-something")); + Assertions.assertEquals(1, result.getFailed()); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(ctx.getRealm(), "user7-something")); // Update LDAP user to avoid duplicated email LDAPObject duplicatedLdapUser = ctx.getLdapProvider().loadLDAPUserByUsername(ctx.getRealm(), "user7-something"); @@ -289,7 +289,7 @@ public void test02duplicateUsernameAndEmailSync() { // Assert user successfully synced now result = UserStoragePrivateUtil.runFullSync(session.getKeycloakSessionFactory(), ctx.getLdapModel()); - Assert.assertEquals(0, result.getFailed()); + Assertions.assertEquals(0, result.getFailed()); }); // Assert user was imported. Use another transaction for that @@ -336,7 +336,7 @@ public void testSyncAfterDeletingUserInLDAPWithSameEmail() { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); SynchronizationResult result = UserStoragePrivateUtil.runFullSync(session.getKeycloakSessionFactory(), ctx.getLdapModel()); - Assert.assertEquals(0, result.getFailed()); + Assertions.assertEquals(0, result.getFailed()); }); } @@ -350,7 +350,7 @@ public void test03LDAPSyncWhenUsernameChanged() { // Add user to LDAP LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "beckybecks", "Becky", "Becks", "becky-becks@email.org", null, "123"); SynchronizationResult syncResult = UserStoragePrivateUtil.runFullSync(sessionFactory, ctx.getLdapModel()); - Assert.assertEquals(0, syncResult.getFailed()); + Assertions.assertEquals(0, syncResult.getFailed()); }); testingClient.server().run(session -> { @@ -371,7 +371,7 @@ public void test03LDAPSyncWhenUsernameChanged() { // Trigger partial sync KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory(); SynchronizationResult syncResult = UserStoragePrivateUtil.runPeriodicSync(sessionFactory, ctx.getLdapModel()); - Assert.assertEquals(0, syncResult.getFailed()); + Assertions.assertEquals(0, syncResult.getFailed()); }); testingClient.server().run(session -> { @@ -383,9 +383,9 @@ public void test03LDAPSyncWhenUsernameChanged() { UserModel updatedLocalUser = userProvider.getUserByUsername(testRealm, "beckyupdated"); LDAPObject ldapUser = ctx.getLdapProvider().loadLDAPUserByUsername(testRealm, "beckyupdated"); // Assert old user 'beckybecks' does not exists locally - Assert.assertNull(userProvider.getUserByUsername(testRealm, "beckybecks")); + Assertions.assertNull(userProvider.getUserByUsername(testRealm, "beckybecks")); // Assert UUID didn't change - Assert.assertEquals(updatedLocalUser.getAttributeStream(LDAPConstants.LDAP_ID).findFirst().get(),ldapUser.getUuid()); + Assertions.assertEquals(updatedLocalUser.getAttributeStream(LDAPConstants.LDAP_ID).findFirst().get(),ldapUser.getUuid()); }); } @@ -420,7 +420,7 @@ public void test04SameUUIDAndUsernameSync() { KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory(); SynchronizationResult syncResult = UserStoragePrivateUtil.runFullSync(sessionFactory, ctx.getLdapModel()); - Assert.assertEquals(0, syncResult.getFailed()); + Assertions.assertEquals(0, syncResult.getFailed()); }); @@ -431,7 +431,7 @@ public void test04SameUUIDAndUsernameSync() { LDAPTestAsserts.assertUserImported(session.users(), ctx.getRealm(), "user1", "User1FN", "User1LN", "user1@email.org", "121"); LDAPTestAsserts.assertUserImported(session.users(), ctx.getRealm(), "user2", "User2FN", "User2LN", "user2@email.org", "122"); UserModel user1 = session.users().getUserByUsername(ctx.getRealm(), "user1"); - Assert.assertEquals("user1", user1.getFirstAttribute(LDAPConstants.LDAP_ID)); + Assertions.assertEquals("user1", user1.getFirstAttribute(LDAPConstants.LDAP_ID)); }); // Remove all users from model - required step before the next test execution especially when running against external AD @@ -491,8 +491,8 @@ public void test05MissingLDAPUsernameSync() { KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory(); SynchronizationResult syncResult = UserStoragePrivateUtil.runFullSync(sessionFactory, ctx.getLdapModel()); - Assert.assertEquals(1, syncResult.getAdded()); - Assert.assertTrue(syncResult.getFailed() > 0); + Assertions.assertEquals(1, syncResult.getAdded()); + Assertions.assertTrue(syncResult.getFailed() > 0); UserModel invalidUser = session.users().getUserByUsername(ctx.getRealm(), "user8street"); session.users().removeUser(ctx.getRealm(), invalidUser); }); @@ -522,9 +522,9 @@ public void test06SyncRestAPIMissingAction() { try { SynchronizationResultRepresentation syncResultRep = adminClient.realm(TEST_REALM_NAME).userStorage().syncUsers( ldapModelId, null); - Assert.fail("Should throw 400"); + Assertions.fail("Should throw 400"); } catch (Exception e) { - Assert.assertTrue(e instanceof BadRequestException); + Assertions.assertTrue(e instanceof BadRequestException); } } @@ -535,9 +535,9 @@ public void test07SyncRestAPIWrongAction() { try { SynchronizationResultRepresentation syncResultRep = adminClient.realm(TEST_REALM_NAME).userStorage().syncUsers( ldapModelId, "wrong action"); - Assert.fail("Should throw 400"); + Assertions.fail("Should throw 400"); } catch (Exception e) { - Assert.assertTrue(e instanceof BadRequestException); + Assertions.assertTrue(e instanceof BadRequestException); } } @@ -569,7 +569,7 @@ public void test08LDAPGroupSyncAfterGroupRename() { GroupModel kcGroup1 = KeycloakModelUtils.findGroupByPath(session, appRealm, "/group1"); String descriptionAttrName = LDAPTestUtils.getGroupDescriptionLDAPAttrName(ctx.getLdapProvider()); - Assert.assertEquals("group1 - description", kcGroup1.getFirstAttribute(descriptionAttrName)); + Assertions.assertEquals("group1 - description", kcGroup1.getFirstAttribute(descriptionAttrName)); }); testingClient.server().run(session -> { @@ -602,7 +602,7 @@ public void test08LDAPGroupSyncAfterGroupRename() { GroupModel kcGroup5 = KeycloakModelUtils.findGroupByPath(session, appRealm, "/group5"); String descriptionAttrName = LDAPTestUtils.getGroupDescriptionLDAPAttrName(ctx.getLdapProvider()); - Assert.assertEquals("group5 - description", kcGroup5.getFirstAttribute(descriptionAttrName)); + Assertions.assertEquals("group5 - description", kcGroup5.getFirstAttribute(descriptionAttrName)); }); } @@ -680,7 +680,7 @@ public void test09MembershipUsingDifferentAttributes() throws Exception { KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory(); SynchronizationResult syncResult = UserStoragePrivateUtil.runFullSync(sessionFactory, ctx.getLdapModel()); - Assert.assertEquals(2, syncResult.getAdded()); + Assertions.assertEquals(2, syncResult.getAdded()); }); testingClient.server().run(session -> { @@ -688,15 +688,15 @@ public void test09MembershipUsingDifferentAttributes() throws Exception { RealmModel appRealm = ctx.getRealm(); GroupModel user8Group = KeycloakModelUtils.findGroupByPath(session, appRealm, "/user8group"); - Assert.assertNotNull(user8Group); + Assertions.assertNotNull(user8Group); UserModel user8 = session.users().getUserByUsername(appRealm, "user8"); - Assert.assertNotNull(user8); + Assertions.assertNotNull(user8); UserModel user8Bis = session.users().getUserByUsername(appRealm, "user8bis"); - Assert.assertNotNull(user8Bis); - Assert.assertTrue("User user8 contains the group", user8.getGroupsStream().collect(Collectors.toSet()).contains(user8Group)); - Assert.assertFalse("User user8bis does not contain the group", user8Bis.getGroupsStream().collect(Collectors.toSet()).contains(user8Group)); + Assertions.assertNotNull(user8Bis); + Assertions.assertTrue(user8.getGroupsStream().collect(Collectors.toSet()).contains(user8Group), "User user8 contains the group"); + Assertions.assertFalse(user8Bis.getGroupsStream().collect(Collectors.toSet()).contains(user8Group), "User user8bis does not contain the group"); List members = session.users().getGroupMembersStream(appRealm, user8Group).map(u -> u.getUsername()).collect(Collectors.toList()); - Assert.assertEquals("Group contains only user8", members, Collections.singletonList("user8")); + Assertions.assertEquals(members, Collections.singletonList("user8"), "Group contains only user8"); }); // revert changes diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPTestAsserts.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPTestAsserts.java index d89a3f8fad1b..802995f5631b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPTestAsserts.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPTestAsserts.java @@ -26,7 +26,7 @@ import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; /** * Common LDAP asserts @@ -55,11 +55,11 @@ public static void assertLoaded(UserModel user, String username, String expected public static void assertLoaded(UserModel user, String username, String expectedFirstName, String expectedLastName, String expectedEmail, String expectedPostalCode, MultivaluedHashMap otherAttrs) { - Assert.assertNotNull(user); - Assert.assertEquals(expectedFirstName, user.getFirstName()); - Assert.assertEquals(expectedLastName, user.getLastName()); - Assert.assertEquals(expectedEmail, user.getEmail()); - Assert.assertEquals(expectedPostalCode, user.getFirstAttribute("postal_code")); + Assertions.assertNotNull(user); + Assertions.assertEquals(expectedFirstName, user.getFirstName()); + Assertions.assertEquals(expectedLastName, user.getLastName()); + Assertions.assertEquals(expectedEmail, user.getEmail()); + Assertions.assertEquals(expectedPostalCode, user.getFirstAttribute("postal_code")); for (String name : otherAttrs.keySet()) { MatcherAssert.assertThat(otherAttrs.getList(name), Matchers.containsInAnyOrder(user.getAttributeStream(name).toArray(String[]::new))); } @@ -67,17 +67,17 @@ public static void assertLoaded(UserModel user, String username, String expected public static void assertSyncEquals(SynchronizationResult syncResult, int expectedAdded, int expectedUpdated, int expectedRemoved, int expectedFailed) { - Assert.assertEquals(expectedAdded, syncResult.getAdded()); - Assert.assertEquals(expectedUpdated, syncResult.getUpdated()); - Assert.assertEquals(expectedRemoved, syncResult.getRemoved()); - Assert.assertEquals(expectedFailed, syncResult.getFailed()); + Assertions.assertEquals(expectedAdded, syncResult.getAdded()); + Assertions.assertEquals(expectedUpdated, syncResult.getUpdated()); + Assertions.assertEquals(expectedRemoved, syncResult.getRemoved()); + Assertions.assertEquals(expectedFailed, syncResult.getFailed()); } public static void assertSyncEquals(SynchronizationResultRepresentation syncResult, int expectedAdded, int expectedUpdated, int expectedRemoved, int expectedFailed) { - Assert.assertEquals(expectedAdded, syncResult.getAdded()); - Assert.assertEquals(expectedUpdated, syncResult.getUpdated()); - Assert.assertEquals(expectedRemoved, syncResult.getRemoved()); - Assert.assertEquals(expectedFailed, syncResult.getFailed()); + Assertions.assertEquals(expectedAdded, syncResult.getAdded()); + Assertions.assertEquals(expectedUpdated, syncResult.getUpdated()); + Assertions.assertEquals(expectedRemoved, syncResult.getRemoved()); + Assertions.assertEquals(expectedFailed, syncResult.getFailed()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPUserLoginTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPUserLoginTest.java index 4d4a1b82a98b..51a60862bd0e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPUserLoginTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPUserLoginTest.java @@ -31,7 +31,6 @@ import org.keycloak.representations.idm.EventRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.storage.ldap.idm.model.LDAPObject; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.arquillian.annotation.EnableVault; import org.keycloak.testsuite.pages.AppPage; @@ -48,6 +47,7 @@ import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.rules.ExternalResource; import org.junit.runners.MethodSorters; @@ -152,8 +152,8 @@ private void verifyLoginSucceededAndLogout(String username, String password) { oauth.openLoginForm(); loginPage.login(username, password); appPage.assertCurrent(); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); EventRepresentation loginEvent = events.expectLogin().user(userId).assertEvent(); AccessTokenResponse tokenResponse = sendTokenRequestAndGetResponse(loginEvent); appPage.logout(tokenResponse.getIdToken()); @@ -166,7 +166,7 @@ private void verifyLoginFailed(String username, String password) { // Run the test actions oauth.openLoginForm(); loginPage.login(username, password); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); if (username.equals(DEFAULT_TEST_USERS.get("INVALID_USER_EMAIL")) || username.equals(DEFAULT_TEST_USERS.get("INVALID_USER_NAME"))) { @@ -175,7 +175,7 @@ private void verifyLoginFailed(String username, String password) { } else if (username.equals(DEFAULT_TEST_USERS.get("VALID_USER_EMAIL")) || username.equals(DEFAULT_TEST_USERS.get("VALID_USER_NAME"))) { List knownUsers = getAdminClient().realm(TEST_REALM_NAME).users().search(DEFAULT_TEST_USERS.get("VALID_USER_NAME")); - Assert.assertTrue(!knownUsers.isEmpty()); + Assertions.assertTrue(!knownUsers.isEmpty()); final String userId = knownUsers.get(0).getId(); events.expect(EventType.LOGIN_ERROR).user(userId).error(Errors.INVALID_USER_CREDENTIALS).assertEvent(); @@ -211,7 +211,7 @@ private void runLDAPLoginTest() { private void verifyConnectionUrlProtocolPrefix(String ldapProtocolPrefix) { final String ldapConnectionUrl = ldapRule.getConfig().get(LDAPConstants.CONNECTION_URL); - Assert.assertTrue(!ldapConnectionUrl.isEmpty() && ldapConnectionUrl.startsWith(ldapProtocolPrefix)); + Assertions.assertTrue(!ldapConnectionUrl.isEmpty() && ldapConnectionUrl.startsWith(ldapProtocolPrefix)); } // Tests themselves diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPUserMultipleCredentialTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPUserMultipleCredentialTest.java index 8d7a0ef6ff57..f33056e14724 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPUserMultipleCredentialTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPUserMultipleCredentialTest.java @@ -26,10 +26,10 @@ import org.keycloak.testsuite.util.LDAPTestUtils; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; /** @@ -121,7 +121,7 @@ public void testUserCredentialsAvailable() { loginTotpPage.clickTryAnotherWayLink(); selectAuthenticatorPage.assertCurrent(); // make sure password method exists as well - Assert.assertEquals(Arrays.asList(SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION, SelectAuthenticatorPage.PASSWORD), selectAuthenticatorPage.getAvailableLoginMethods()); + Assertions.assertEquals(Arrays.asList(SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION, SelectAuthenticatorPage.PASSWORD), selectAuthenticatorPage.getAvailableLoginMethods()); } finally { // Revert flow binding diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPUserProfileTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPUserProfileTest.java index d45d537c0967..3a5e4b319e6c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPUserProfileTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPUserProfileTest.java @@ -49,11 +49,11 @@ import org.keycloak.userprofile.config.UPConfigUtils; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Assume; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import static org.keycloak.storage.UserStorageProviderModel.IMPORT_ENABLED; @@ -116,11 +116,11 @@ public void testUserProfile() { oauth.openLoginForm(); loginPage.login("johnkeycloak", "Password1"); updateProfilePage.assertCurrent(); - Assert.assertEquals("John", updateProfilePage.getFirstName()); - Assert.assertEquals("Doe", updateProfilePage.getLastName()); - Assert.assertTrue(updateProfilePage.getElementById("firstName").isEnabled()); - Assert.assertTrue(updateProfilePage.getElementById("lastName").isEnabled()); - Assert.assertNull(updateProfilePage.getElementById("postal_code")); + Assertions.assertEquals("John", updateProfilePage.getFirstName()); + Assertions.assertEquals("Doe", updateProfilePage.getLastName()); + Assertions.assertTrue(updateProfilePage.getElementById("firstName").isEnabled()); + Assertions.assertTrue(updateProfilePage.getElementById("lastName").isEnabled()); + Assertions.assertNull(updateProfilePage.getElementById("postal_code")); updateProfilePage.prepareUpdate().submit(); } @@ -144,7 +144,7 @@ public void testUserProfileWithDefinedAttribute() throws IOException { // Defined postal_code in user profile config should have preference UserResource johnResource = AdminApiUtil.findUserByUsernameId(testRealm(), "johnkeycloak"); UserRepresentation john = johnResource.toRepresentation(true); - Assert.assertEquals("Postal Code", john.getUserProfileMetadata().getAttributeMetadata("postal_code").getDisplayName()); + Assertions.assertEquals("Postal Code", john.getUserProfileMetadata().getAttributeMetadata("postal_code").getDisplayName()); // update profile now. john.getRequiredActions().add(UserModel.RequiredAction.UPDATE_PROFILE.toString()); @@ -154,12 +154,12 @@ public void testUserProfileWithDefinedAttribute() throws IOException { loginPage.login("johnkeycloak", "Password1"); updateProfilePage.assertCurrent(); - Assert.assertEquals("John", updateProfilePage.getFirstName()); - Assert.assertEquals("Doe", updateProfilePage.getLastName()); - Assert.assertEquals("1234", updateProfilePage.getElementById("postal_code").getAttribute("value")); - Assert.assertTrue(updateProfilePage.getElementById("firstName").isEnabled()); - Assert.assertTrue(updateProfilePage.getElementById("lastName").isEnabled()); - Assert.assertTrue(updateProfilePage.getElementById("postal_code").isEnabled()); + Assertions.assertEquals("John", updateProfilePage.getFirstName()); + Assertions.assertEquals("Doe", updateProfilePage.getLastName()); + Assertions.assertEquals("1234", updateProfilePage.getElementById("postal_code").getAttribute("value")); + Assertions.assertTrue(updateProfilePage.getElementById("firstName").isEnabled()); + Assertions.assertTrue(updateProfilePage.getElementById("lastName").isEnabled()); + Assertions.assertTrue(updateProfilePage.getElementById("postal_code").isEnabled()); updateProfilePage.prepareUpdate().submit(); } finally { testRealm().users().userProfile().update(origConfig); @@ -185,17 +185,17 @@ public void testUserProfileWithMetadataAttributeDefinedInUserProfileConfig() { UserResource johnResource = AdminApiUtil.findUserByUsernameId(testRealm(), "johnkeycloak"); UserRepresentation john = johnResource.toRepresentation(true); - Assert.assertNotNull(john.getAttributes().get(LDAPConstants.LDAP_ENTRY_DN)); - Assert.assertNotNull(john.getAttributes().get(LDAPConstants.LDAP_ID)); - Assert.assertNotNull(john.getUserProfileMetadata()); + Assertions.assertNotNull(john.getAttributes().get(LDAPConstants.LDAP_ENTRY_DN)); + Assertions.assertNotNull(john.getAttributes().get(LDAPConstants.LDAP_ID)); + Assertions.assertNotNull(john.getUserProfileMetadata()); UserProfileAttributeMetadata ldapIdMeta = john.getUserProfileMetadata().getAttributeMetadata(LDAPConstants.LDAP_ID); - Assert.assertNotNull(ldapIdMeta); - Assert.assertNull(ldapIdMeta.getGroup()); + Assertions.assertNotNull(ldapIdMeta); + Assertions.assertNull(ldapIdMeta.getGroup()); UserProfileAttributeMetadata ldapEntryDnMeta = john.getUserProfileMetadata().getAttributeMetadata(LDAPConstants.LDAP_ENTRY_DN); - Assert.assertNotNull(ldapEntryDnMeta); - Assert.assertNull(ldapEntryDnMeta.getGroup()); + Assertions.assertNotNull(ldapEntryDnMeta); + Assertions.assertNull(ldapEntryDnMeta.getGroup()); } finally { testRealm().users().userProfile().update(origConfig); } @@ -219,11 +219,11 @@ public void testUserProfileWithReadOnlyLdap() { oauth.openLoginForm(); loginPage.login("johnkeycloak", "Password1"); updateProfilePage.assertCurrent(); - Assert.assertEquals("John", updateProfilePage.getFirstName()); - Assert.assertEquals("Doe", updateProfilePage.getLastName()); - Assert.assertFalse(updateProfilePage.getElementById("firstName").isEnabled()); - Assert.assertFalse(updateProfilePage.getElementById("lastName").isEnabled()); - Assert.assertNull(updateProfilePage.getElementById("postal_code")); + Assertions.assertEquals("John", updateProfilePage.getFirstName()); + Assertions.assertEquals("Doe", updateProfilePage.getLastName()); + Assertions.assertFalse(updateProfilePage.getElementById("firstName").isEnabled()); + Assertions.assertFalse(updateProfilePage.getElementById("lastName").isEnabled()); + Assertions.assertNull(updateProfilePage.getElementById("postal_code")); updateProfilePage.prepareUpdate().submit(); } finally { setLDAPWritable(); @@ -250,11 +250,11 @@ public void testUserProfileWithReadOnlyLdapLocalUser() { oauth.openLoginForm(); loginPage.login("marykeycloak", "Password1"); updateProfilePage.assertCurrent(); - Assert.assertEquals("Mary", updateProfilePage.getFirstName()); - Assert.assertEquals("Kelly", updateProfilePage.getLastName()); - Assert.assertTrue(updateProfilePage.getElementById("firstName").isEnabled()); - Assert.assertTrue(updateProfilePage.getElementById("lastName").isEnabled()); - Assert.assertNull(updateProfilePage.getElementById("postal_code")); + Assertions.assertEquals("Mary", updateProfilePage.getFirstName()); + Assertions.assertEquals("Kelly", updateProfilePage.getLastName()); + Assertions.assertTrue(updateProfilePage.getElementById("firstName").isEnabled()); + Assertions.assertTrue(updateProfilePage.getElementById("lastName").isEnabled()); + Assertions.assertNull(updateProfilePage.getElementById("postal_code")); updateProfilePage.prepareUpdate().submit(); } finally { setLDAPWritable(); @@ -322,12 +322,12 @@ public void testMultipleLDAPProviders() { // the provider for this user does not have postal_code mapper UserResource userResource = AdminApiUtil.findUserByUsernameId(testRealm(), "anotherjohn"); UserRepresentation userRep = userResource.toRepresentation(true); - Assert.assertNull(userRep.getAttributes().get("postal_code")); + Assertions.assertNull(userRep.getAttributes().get("postal_code")); // the provider for this user does have postal_code mapper userResource = AdminApiUtil.findUserByUsernameId(testRealm(), "johnkeycloak"); userRep = userResource.toRepresentation(true); - Assert.assertNotNull(userRep.getAttributes().get("postal_code")); + Assertions.assertNotNull(userRep.getAttributes().get("postal_code")); setLDAPReadOnly(); try { @@ -385,11 +385,11 @@ public void testUsernameRespectFormatFromExternalStore() { UserResource johnResource = AdminApiUtil.findUserByUsernameId(testRealm(), upperCaseUsername); UserRepresentation john = johnResource.toRepresentation(true); - Assert.assertEquals(upperCaseUsername, john.getUsername()); + Assertions.assertEquals(upperCaseUsername, john.getUsername()); johnResource = AdminApiUtil.findUserByUsernameId(testRealm(), upperCaseUsername.toLowerCase()); john = johnResource.toRepresentation(true); - Assert.assertEquals(upperCaseUsername, john.getUsername()); + Assertions.assertEquals(upperCaseUsername, john.getUsername()); oauth.openLoginForm(); loginPage.login(upperCaseUsername, "Password1"); @@ -422,11 +422,11 @@ public void testUsernameRespectFormatFromExternalStoreAD() { UserResource johnResource = AdminApiUtil.findUserByUsernameId(testRealm(), upperCaseUsername); UserRepresentation john = johnResource.toRepresentation(true); - Assert.assertEquals(upperCaseUsername, john.getUsername()); + Assertions.assertEquals(upperCaseUsername, john.getUsername()); johnResource = AdminApiUtil.findUserByUsernameId(testRealm(), upperCaseUsername.toLowerCase()); john = johnResource.toRepresentation(true); - Assert.assertEquals(upperCaseUsername, john.getUsername()); + Assertions.assertEquals(upperCaseUsername, john.getUsername()); oauth.openLoginForm(); loginPage.login(upperCaseUsername, "Password1"); @@ -491,14 +491,14 @@ public void testUpdateEmailVerifiedWithReadOnlyLdapAndUpperCaseEmail() { // Fetch the user via admin API - email should be returned as lowercase UserResource userResource = AdminApiUtil.findUserByUsernameId(testRealm(), "uppercaseemailuser"); UserRepresentation userRep = userResource.toRepresentation(); - Assert.assertEquals("uppercase@email.org", userRep.getEmail()); + Assertions.assertEquals("uppercase@email.org", userRep.getEmail()); // Update only emailVerified - this should succeed even though the email in LDAP is uppercase userRep.setEmailVerified(true); userResource.update(userRep); userRep = userResource.toRepresentation(); - Assert.assertTrue(userRep.isEmailVerified()); + Assertions.assertTrue(userRep.isEmailVerified()); } finally { setEmailMapperAlwaysReadFromLDAP(false); setLDAPWritable(); @@ -557,31 +557,31 @@ private void setLDAPImportEnabled() { } private void assertUser(UserRepresentation user, String expectedUsername, String expectedEmail, String expectedFirstName, String expectedLastname, String expectedPostalCode) { - Assert.assertNotNull(user); - Assert.assertEquals(expectedUsername, user.getUsername()); - Assert.assertEquals(expectedFirstName, user.getFirstName()); - Assert.assertEquals(expectedLastname, user.getLastName()); - Assert.assertEquals(expectedEmail, user.getEmail()); - Assert.assertEquals(expectedPostalCode, user.getAttributes().get("postal_code").get(0)); - - Assert.assertNotNull(user.getAttributes().get(LDAPConstants.LDAP_ID)); - Assert.assertNotNull(user.getAttributes().get(LDAPConstants.LDAP_ENTRY_DN)); + Assertions.assertNotNull(user); + Assertions.assertEquals(expectedUsername, user.getUsername()); + Assertions.assertEquals(expectedFirstName, user.getFirstName()); + Assertions.assertEquals(expectedLastname, user.getLastName()); + Assertions.assertEquals(expectedEmail, user.getEmail()); + Assertions.assertEquals(expectedPostalCode, user.getAttributes().get("postal_code").get(0)); + + Assertions.assertNotNull(user.getAttributes().get(LDAPConstants.LDAP_ID)); + Assertions.assertNotNull(user.getAttributes().get(LDAPConstants.LDAP_ENTRY_DN)); } private void assertProfileAttributes(UserRepresentation user, String expectedGroup, boolean expectReadOnly, String... attributes) { for (String attrName : attributes) { UserProfileAttributeMetadata attrMetadata = user.getUserProfileMetadata().getAttributeMetadata(attrName); - Assert.assertNotNull("Attribute " + attrName + " was not present for user " + user.getUsername(), attrMetadata); - Assert.assertEquals("Attribute " + attrName + " for user " + user.getUsername() + ". Expected read-only: " + expectReadOnly + " but was not", expectReadOnly, attrMetadata.isReadOnly()); - Assert.assertEquals("Attribute " + attrName + " for user " + user.getUsername() + ". Expected group: " + expectedGroup + " but was " + attrMetadata.getGroup(), expectedGroup, attrMetadata.getGroup()); + Assertions.assertNotNull(attrMetadata, "Attribute " + attrName + " was not present for user " + user.getUsername()); + Assertions.assertEquals(expectReadOnly, attrMetadata.isReadOnly(), "Attribute " + attrName + " for user " + user.getUsername() + ". Expected read-only: " + expectReadOnly + " but was not"); + Assertions.assertEquals(expectedGroup, attrMetadata.getGroup(), "Attribute " + attrName + " for user " + user.getUsername() + ". Expected group: " + expectedGroup + " but was " + attrMetadata.getGroup()); } } private void assertProfileAttributesNotPresent(UserRepresentation user, String... attributes) { for (String attrName : attributes) { UserProfileAttributeMetadata attrMetadata = user.getUserProfileMetadata().getAttributeMetadata(attrName); - Assert.assertNull("Attribute " + attrName + " was present for user " + user.getUsername(), attrMetadata); + Assertions.assertNull(attrMetadata, "Attribute " + attrName + " was present for user " + user.getUsername()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPUserPropertiesMappingTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPUserPropertiesMappingTest.java index 053c10bf55b9..3f62071414db 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPUserPropertiesMappingTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPUserPropertiesMappingTest.java @@ -25,13 +25,13 @@ import org.keycloak.storage.UserStorageProviderModel; import org.keycloak.storage.ldap.LDAPStorageProvider; import org.keycloak.storage.ldap.idm.model.LDAPObject; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.LDAPRule; import org.keycloak.testsuite.util.LDAPTestConfiguration; import org.keycloak.testsuite.util.LDAPTestUtils; import org.junit.ClassRule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; public class LDAPUserPropertiesMappingTest extends AbstractLDAPTest { @@ -90,23 +90,23 @@ public void createAndReadUser() { RealmModel realm = context.getRealm(); UserModel test10 = session.users().getUserByUsername(realm, DIETMAR); - Assert.assertTrue(test10.isEnabled()); - Assert.assertTrue(test10.isEmailVerified()); + Assertions.assertTrue(test10.isEnabled()); + Assertions.assertTrue(test10.isEmailVerified()); UserModel test11 = session.users().getUserByUsername(realm, STEFAN); - Assert.assertFalse(test11.isEnabled()); - Assert.assertFalse(test11.isEmailVerified()); + Assertions.assertFalse(test11.isEnabled()); + Assertions.assertFalse(test11.isEmailVerified()); ComponentModel ldapProviderModel = LDAPTestUtils.getLdapProviderModel(realm); LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ldapProviderModel); LDAPObject user10FromLdap = ldapProvider.loadLDAPUserByUsername(realm, DIETMAR); - Assert.assertTrue(Boolean.parseBoolean(user10FromLdap.getAttributeAsString(USER_EMAIL_VERIFIED_LDAP_ATTRIBUTE))); - Assert.assertTrue(Boolean.parseBoolean(user10FromLdap.getAttributeAsString(USER_ENABLED_LDAP_ATTRIBUTE))); + Assertions.assertTrue(Boolean.parseBoolean(user10FromLdap.getAttributeAsString(USER_EMAIL_VERIFIED_LDAP_ATTRIBUTE))); + Assertions.assertTrue(Boolean.parseBoolean(user10FromLdap.getAttributeAsString(USER_ENABLED_LDAP_ATTRIBUTE))); LDAPObject user11FromLdap = ldapProvider.loadLDAPUserByUsername(realm, STEFAN); - Assert.assertFalse(Boolean.parseBoolean(user11FromLdap.getAttributeAsString(USER_EMAIL_VERIFIED_LDAP_ATTRIBUTE))); - Assert.assertFalse(Boolean.parseBoolean(user11FromLdap.getAttributeAsString(USER_ENABLED_LDAP_ATTRIBUTE))); + Assertions.assertFalse(Boolean.parseBoolean(user11FromLdap.getAttributeAsString(USER_EMAIL_VERIFIED_LDAP_ATTRIBUTE))); + Assertions.assertFalse(Boolean.parseBoolean(user11FromLdap.getAttributeAsString(USER_ENABLED_LDAP_ATTRIBUTE))); }); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LdapUsernameAttributeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LdapUsernameAttributeTest.java index aa0ea7a24249..53e51e6654a5 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LdapUsernameAttributeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LdapUsernameAttributeTest.java @@ -25,10 +25,10 @@ import org.keycloak.testsuite.runonserver.RunOnServerException; import org.keycloak.testsuite.util.LDAPRule; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; /** @@ -71,16 +71,16 @@ public void testUsernameChange() { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); UserModel john = session.users().getUserByUsername(appRealm, "johndow"); - Assert.assertNotNull(john); - Assert.assertNotNull(john.getFederationLink()); - Assert.assertEquals("johndow", john.getUsername()); - Assert.assertEquals("johndow@email.cz", john.getEmail()); - Assert.assertEquals("johndow", john.getFirstName()); - Assert.assertEquals("johndow", john.getLastName()); + Assertions.assertNotNull(john); + Assertions.assertNotNull(john.getFederationLink()); + Assertions.assertEquals("johndow", john.getUsername()); + Assertions.assertEquals("johndow@email.cz", john.getEmail()); + Assertions.assertEquals("johndow", john.getFirstName()); + Assertions.assertEquals("johndow", john.getLastName()); LDAPObject johnLdap = ctx.getLdapProvider().loadLDAPUserByUsername(appRealm, "johndow"); - Assert.assertNotNull(johnLdap); + Assertions.assertNotNull(johnLdap); LDAPDn.RDN firstRdnEntry = johnLdap.getDn().getFirstRdn(); - Assert.assertEquals("johndow", firstRdnEntry.getAttrValue(firstRdnEntry.getAllKeys().get(0))); + Assertions.assertEquals("johndow", firstRdnEntry.getAttrValue(firstRdnEntry.getAllKeys().get(0))); }); // rename to johndow2 testingClient.server().run(session -> { @@ -96,21 +96,21 @@ public void testUsernameChange() { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); - Assert.assertNull(session.users().getUserByUsername(appRealm, "johndow")); + Assertions.assertNull(session.users().getUserByUsername(appRealm, "johndow")); UserModel john2 = session.users().getUserByUsername(appRealm, "johndow2"); - Assert.assertNotNull(john2); - Assert.assertNotNull(john2.getFederationLink()); - Assert.assertEquals("johndow2", john2.getUsername()); - Assert.assertEquals("johndow2@email.cz", john2.getEmail()); - Assert.assertEquals("johndow2", john2.getFirstName()); - Assert.assertEquals("johndow2", john2.getLastName()); + Assertions.assertNotNull(john2); + Assertions.assertNotNull(john2.getFederationLink()); + Assertions.assertEquals("johndow2", john2.getUsername()); + Assertions.assertEquals("johndow2@email.cz", john2.getEmail()); + Assertions.assertEquals("johndow2", john2.getFirstName()); + Assertions.assertEquals("johndow2", john2.getLastName()); LDAPObject johnLdap2 = ctx.getLdapProvider().loadLDAPUserByUsername(appRealm, "johndow2"); - Assert.assertNotNull(johnLdap2); + Assertions.assertNotNull(johnLdap2); LDAPDn.RDN firstRdnEntry = johnLdap2.getDn().getFirstRdn(); - Assert.assertEquals("johndow2", firstRdnEntry.getAttrValue(firstRdnEntry.getAllKeys().get(0))); + Assertions.assertEquals("johndow2", firstRdnEntry.getAttrValue(firstRdnEntry.getAllKeys().get(0))); session.users().removeUser(appRealm, john2); - Assert.assertNull(session.users().getUserByUsername(appRealm, "johndow2")); + Assertions.assertNull(session.users().getUserByUsername(appRealm, "johndow2")); }); } @@ -134,11 +134,11 @@ public void testUsernameChangeAlreadyExists() { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); UserModel john = session.users().getUserByUsername(appRealm, "johndow"); - Assert.assertNotNull(john); - Assert.assertNotNull(john.getFederationLink()); + Assertions.assertNotNull(john); + Assertions.assertNotNull(john.getFederationLink()); UserModel john2 = session.users().getUserByUsername(appRealm, "johndow2"); - Assert.assertNotNull(john2); - Assert.assertNotNull(john2.getFederationLink()); + Assertions.assertNotNull(john2); + Assertions.assertNotNull(john2.getFederationLink()); }); // rename johndow to johndow2 => it should fail try { @@ -148,23 +148,23 @@ public void testUsernameChangeAlreadyExists() { UserModel john = session.users().getUserByUsername(appRealm, "johndow"); john.setUsername("johndow2"); }); - Assert.assertFalse("Model exception is expected here, so it should not reach this point", true); + Assertions.assertFalse(true, "Model exception is expected here, so it should not reach this point"); } catch (RunOnServerException e) { - Assert.assertTrue("Model exception is expected here but another error found", e.getCause() instanceof ModelDuplicateException); - Assert.assertEquals(UserModel.USERNAME, ((ModelDuplicateException)e.getCause()).getDuplicateFieldName()); + Assertions.assertTrue(e.getCause() instanceof ModelDuplicateException, "Model exception is expected here but another error found"); + Assertions.assertEquals(UserModel.USERNAME, ((ModelDuplicateException)e.getCause()).getDuplicateFieldName()); } // remove both users testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel appRealm = ctx.getRealm(); UserModel john = session.users().getUserByUsername(appRealm, "johndow"); - Assert.assertNotNull(john); + Assertions.assertNotNull(john); UserModel john2 = session.users().getUserByUsername(appRealm, "johndow2"); - Assert.assertNotNull(john2); + Assertions.assertNotNull(john2); session.users().removeUser(appRealm, john); session.users().removeUser(appRealm, john2); - Assert.assertNull(session.users().getUserByUsername(appRealm, "johndow")); - Assert.assertNull(session.users().getUserByUsername(appRealm, "johndow2")); + Assertions.assertNull(session.users().getUserByUsername(appRealm, "johndow")); + Assertions.assertNull(session.users().getUserByUsername(appRealm, "johndow2")); }); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/UserFederationLdapConnectionTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/UserFederationLdapConnectionTest.java index c24c6025f26a..333c2a3ee583 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/UserFederationLdapConnectionTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/UserFederationLdapConnectionTest.java @@ -30,13 +30,13 @@ import org.keycloak.services.managers.LDAPServerCapabilitiesManager; import org.keycloak.storage.ldap.idm.store.ldap.extended.PasswordModifyRequest; import org.keycloak.testsuite.AbstractAdminTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.arquillian.annotation.EnableVault; import org.keycloak.testsuite.util.LDAPRule; import org.hamcrest.Matchers; import org.junit.ClassRule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.hamcrest.MatcherAssert.assertThat; @@ -238,14 +238,14 @@ public void testLdapCapabilities() { "false", null, "false", LDAPConstants.AUTH_TYPE_SIMPLE); realm.ldapServerCapabilities(config); - Assert.fail("It wasn't expected to successfully sent the request for query capabilities"); + Assertions.fail("It wasn't expected to successfully sent the request for query capabilities"); } catch (BadRequestException bre) { // Expected } } private void assertStatus(Response response, int status) { - Assert.assertEquals(status, response.getStatus()); + Assertions.assertEquals(status, response.getStatus()); response.close(); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/UserStorageGracefulDegradationLdapTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/UserStorageGracefulDegradationLdapTest.java index 0d728fad9343..c55fe0612903 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/UserStorageGracefulDegradationLdapTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/UserStorageGracefulDegradationLdapTest.java @@ -38,9 +38,9 @@ import org.keycloak.testsuite.util.LDAPTestUtils; import org.keycloak.testsuite.util.UserBuilder; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * Test graceful degradation with real embedded LDAP server that gets unreachable. @@ -86,7 +86,7 @@ public void testGracefulDegradationWhenLdapGoesDown(KeycloakSession session) { List usernames = users.map(UserModel::getUsername).toList(); // Should find LDAP user "john" when LDAP is up - Assert.assertTrue("Should find john from LDAP when server is up", usernames.contains("john")); + Assertions.assertTrue(usernames.contains("john"), "Should find john from LDAP when server is up"); // Simulate LDAP going down by changing connection URL to invalid server ldapModel.getConfig().putSingle("connectionUrl", "ldap://invalid-server:999"); @@ -100,10 +100,10 @@ public void testGracefulDegradationWhenLdapGoesDown(KeycloakSession session) { usernames = users.map(UserModel::getUsername).toList(); // Should gracefully return local users despite LDAP being down - Assert.assertTrue("Should find local user despite LDAP down", - usernames.contains("local-user")); - Assert.assertTrue("Should find local admin despite LDAP down", - usernames.contains("local-admin")); + Assertions.assertTrue(usernames.contains("local-user"), + "Should find local user despite LDAP down"); + Assertions.assertTrue(usernames.contains("local-admin"), + "Should find local admin despite LDAP down"); } finally { // Clean up - remove users (LDAP provider will be cleaned up by AbstractLDAPTest) @@ -154,15 +154,15 @@ public void testLoginWithEmbeddedLDAPFailure() { loginPage.login("testldapuser", "TestPassword123!"); // Should stay on login page with error since LDAP user can't be authenticated - Assert.assertTrue("Should stay on login page when LDAP user login fails", - loginPage.isCurrent()); + Assertions.assertTrue(loginPage.isCurrent(), + "Should stay on login page when LDAP user login fails"); // Now try to login with the local user - this should work despite LDAP being down loginPage.login("user@domain.com", "password"); // Should succeed despite LDAP failure appPage.assertCurrent(); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); } finally { // Cleanup diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPMultipleAttributesNoImportTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPMultipleAttributesNoImportTest.java index a6b28b786949..31bf01893593 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPMultipleAttributesNoImportTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPMultipleAttributesNoImportTest.java @@ -25,9 +25,9 @@ import org.keycloak.testsuite.federation.ldap.LDAPTestAsserts; import org.keycloak.testsuite.federation.ldap.LDAPTestContext; -import org.junit.Assert; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; /** @@ -52,8 +52,8 @@ public void testUserImport() { // Test user NOT imported in local storage now. He is available just through "session.users()" UserModel user = session.users().getUserByUsername(appRealm, "jbrown"); - Assert.assertNotNull(user); - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserById(appRealm, user.getId())); + Assertions.assertNotNull(user); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserById(appRealm, user.getId())); LDAPTestAsserts.assertUserImported(session.users(), appRealm, "jbrown", "James", "Brown", "jbrown@keycloak.org", "88441"); }); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPProvidersIntegrationNoImportTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPProvidersIntegrationNoImportTest.java index 6e7b59abf53d..dcbd56af4733 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPProvidersIntegrationNoImportTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPProvidersIntegrationNoImportTest.java @@ -52,14 +52,14 @@ import org.keycloak.testsuite.util.LDAPTestUtils; import org.keycloak.testsuite.util.userprofile.UserProfileUtil; -import org.junit.Assert; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** @@ -84,12 +84,12 @@ public void enableUserProfileUnmanagedAttributes() { @Override protected void assertFederatedUserLink(UserRepresentation user) { StorageId storageId = new StorageId(user.getId()); - Assert.assertFalse(storageId.isLocal()); - Assert.assertEquals(ldapModelId, storageId.getProviderId()); + Assertions.assertFalse(storageId.isLocal()); + Assertions.assertEquals(ldapModelId, storageId.getProviderId()); // TODO: It should be possibly LDAP_ID (LDAP UUID) used as an externalId inside storageId... - Assert.assertEquals(storageId.getExternalId(), user.getUsername()); - Assert.assertNotNull(user.getFederationLink()); + Assertions.assertEquals(storageId.getExternalId(), user.getUsername()); + Assertions.assertNotNull(user.getFederationLink()); } @@ -116,31 +116,31 @@ public void testSearch() { // search by username List users = session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "username1")).collect(Collectors.toList()); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); UserModel user = users.get(0); LDAPTestAsserts.assertLoaded(user, "username1", "John1", "Doel1", "user1@email.org", "121"); // search by email users = session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "user2@email.org")).collect(Collectors.toList()); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); user = users.get(0); LDAPTestAsserts.assertLoaded(user, "username2", "John2", "Doel2", "user2@email.org", "122"); // search by lastName users = session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "Doel3")).collect(Collectors.toList()); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); user = users.get(0); LDAPTestAsserts.assertLoaded(user, "username3", "John3", "Doel3", "user3@email.org", "123"); // search by firstName + lastName users = session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "John4 Doel4")).collect(Collectors.toList()); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); user = users.get(0); LDAPTestAsserts.assertLoaded(user, "username4", "John4", "Doel4", "user4@email.org", "124"); // search by a string that matches multiple fields. Should still return the one entity it matches users = session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "*8*")).collect(Collectors.toList()); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); user = users.get(0); LDAPTestAsserts.assertLoaded(user, "username8", "John8", "Doel8", "user8@email.org", "124"); }); @@ -182,8 +182,8 @@ public void testSearchWithCustomLDAPFilter() { user = session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "John6 Doel6")).findFirst().get(); LDAPTestAsserts.assertLoaded(user, "username6", "John6", "Doel6", "user6@email.org", "126"); - Assert.assertEquals(0, session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "user7@email.org")).count()); - Assert.assertEquals(0, session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "John7 Doel7")).count()); + Assertions.assertEquals(0, session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "user7@email.org")).count()); + Assertions.assertEquals(0, session.users().searchForUserStream(appRealm, Map.of(UserModel.SEARCH, "John7 Doel7")).count()); // Remove custom filter ctx.getLdapModel().getConfig().remove(LDAPConstants.CUSTOM_USER_SEARCH_FILTER); @@ -199,13 +199,13 @@ public void testUnsynced() throws Exception { ComponentResource ldapProviderResource = testRealm().components().component(ldapModelId); ComponentRepresentation ldapProviderRep = ldapProviderResource.toRepresentation(); String currentEditMode = ldapProviderRep.getConfig().getFirst(LDAPConstants.EDIT_MODE); - Assert.assertEquals(UserStorageProvider.EditMode.WRITABLE.toString(), currentEditMode); + Assertions.assertEquals(UserStorageProvider.EditMode.WRITABLE.toString(), currentEditMode); // Try update editMode to UNSYNCED. It should not work as UNSYNCED with no-import is not allowed ldapProviderRep.getConfig().putSingle(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.UNSYNCED.toString()); try { ldapProviderResource.update(ldapProviderRep); - Assert.fail("Not expected to successfully update provider"); + Assertions.fail("Not expected to successfully update provider"); } catch (BadRequestException bre) { // Expected } @@ -230,7 +230,7 @@ public void testFullNameMapperWriteOnly() { RealmModel appRealm = ctx.getRealm(); // assert that user "fullnameUser" is not in local DB - Assert.assertNull(session.users().getUserByUsername(appRealm, "fullname")); + Assertions.assertNull(session.users().getUserByUsername(appRealm, "fullname")); // Add the user with some fullName into LDAP directly. Ensure that fullName is saved into "cn" attribute in LDAP (currently mapped to model firstName) ComponentModel ldapModel = LDAPTestUtils.getLdapProviderModel(appRealm); @@ -294,7 +294,7 @@ public void testFullNameMapperWriteOnly() { firstNameMapperRep.setId(null); Response response = testRealm().components().add(firstNameMapperRep); - Assert.assertEquals(201, response.getStatus()); + Assertions.assertEquals(201, response.getStatus()); response.close(); } @@ -317,7 +317,7 @@ public void testImpossibleToChangeNonLDAPMappedAttributes() { johnRep.setEnabled(false); john.update(johnRep); - Assert.fail("Not supposed to successfully update 'enabled' state of the user"); + Assertions.fail("Not supposed to successfully update 'enabled' state of the user"); } catch (BadRequestException bre) { // Expected } @@ -327,7 +327,7 @@ public void testImpossibleToChangeNonLDAPMappedAttributes() { johnRep = john.toRepresentation(); johnRep.setRequiredActions(Collections.singletonList(UserModel.RequiredAction.CONFIGURE_TOTP.toString())); john.update(johnRep); - Assert.fail("Not supposed to successfully add requiredAction to the user"); + Assertions.fail("Not supposed to successfully add requiredAction to the user"); } catch (BadRequestException bre) { // Expected } @@ -337,7 +337,7 @@ public void testImpossibleToChangeNonLDAPMappedAttributes() { johnRep = john.toRepresentation(); johnRep.singleAttribute("foo", "bar"); john.update(johnRep); - Assert.fail("Not supposed to successfully add attribute to the user"); + Assertions.fail("Not supposed to successfully add attribute to the user"); } catch (BadRequestException bre) { // Expected } @@ -350,9 +350,9 @@ public void testImpossibleToChangeNonLDAPMappedAttributes() { john.update(johnRep); johnRep = john.toRepresentation(); - Assert.assertEquals("John2", johnRep.getFirstName()); - Assert.assertEquals("Doe2", johnRep.getLastName()); - Assert.assertEquals("654321", johnRep.getAttributes().get("postal_code").get(0)); + Assertions.assertEquals("John2", johnRep.getFirstName()); + Assertions.assertEquals("Doe2", johnRep.getLastName()); + Assertions.assertEquals("654321", johnRep.getAttributes().get("postal_code").get(0)); } finally { // Revert johnRep = john.toRepresentation(); @@ -360,10 +360,10 @@ public void testImpossibleToChangeNonLDAPMappedAttributes() { johnRep.setLastName(lastNameOrig); johnRep.singleAttribute("postal_code", postalCodeOrig); john.update(johnRep); - Assert.assertEquals(firstNameOrig, johnRep.getFirstName()); - Assert.assertEquals(lastNameOrig, johnRep.getLastName()); - Assert.assertEquals(emailOrig, johnRep.getEmail()); - Assert.assertEquals(postalCodeOrig, johnRep.getAttributes().get("postal_code").get(0)); + Assertions.assertEquals(firstNameOrig, johnRep.getFirstName()); + Assertions.assertEquals(lastNameOrig, johnRep.getLastName()); + Assertions.assertEquals(emailOrig, johnRep.getEmail()); + Assertions.assertEquals(postalCodeOrig, johnRep.getAttributes().get("postal_code").get(0)); } } @@ -377,7 +377,7 @@ public void testCannotUpdateReadOnlyUserImportDisabled() { user.update(rep); fail("Should fail as the user is read-only"); } catch (BadRequestException bde) { - Assert.assertEquals("The user is read-only. Not possible to write 'required action VERIFY_EMAIL' when updating user 'johnkeycloak'.", bde.getResponse().readEntity(ErrorRepresentation.class).getErrorMessage()); + Assertions.assertEquals("The user is read-only. Not possible to write 'required action VERIFY_EMAIL' when updating user 'johnkeycloak'.", bde.getResponse().readEntity(ErrorRepresentation.class).getErrorMessage()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPRoleMappingsNoImportTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPRoleMappingsNoImportTest.java index 4e987a324c54..ea650b213317 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPRoleMappingsNoImportTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPRoleMappingsNoImportTest.java @@ -40,10 +40,10 @@ import org.keycloak.testsuite.util.LDAPRule; import org.keycloak.testsuite.util.LDAPTestUtils; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; /** @@ -147,7 +147,7 @@ public void test01ReadMappings() { UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); // make sure we are in no-import mode! - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "marykeycloak")); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "marykeycloak")); // This role should already exists as it was imported from LDAP RoleModel realmRole1 = appRealm.getRole("realmRole1"); @@ -156,8 +156,8 @@ public void test01ReadMappings() { RoleModel realmRole2 = appRealm.getRole("realmRole2"); Set maryRoles = mary.getRealmRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertTrue(maryRoles.contains(realmRole1)); - Assert.assertTrue(maryRoles.contains(realmRole2)); + Assertions.assertTrue(maryRoles.contains(realmRole1)); + Assertions.assertTrue(maryRoles.contains(realmRole2)); // Add some role mappings directly into LDAP ComponentModel roleMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "realmRolesMapper"); @@ -182,8 +182,8 @@ public void test01ReadMappings() { RoleModel realmRole2 = appRealm.getRole("realmRole2"); Set maryRoles = mary.getRealmRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertFalse(maryRoles.contains(realmRole1)); - Assert.assertFalse(maryRoles.contains(realmRole2)); + Assertions.assertFalse(maryRoles.contains(realmRole1)); + Assertions.assertFalse(maryRoles.contains(realmRole2)); }); } @@ -201,8 +201,8 @@ public void test02WriteMappings() { UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); // make sure we are in no-import mode - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "johnkeycloak")); - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "marykeycloak")); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "johnkeycloak")); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "marykeycloak")); // 1 - Grant some roles in LDAP @@ -241,8 +241,8 @@ public void test02WriteMappings() { UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak"); // make sure we are in no-import mode - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "johnkeycloak")); - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "marykeycloak")); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "johnkeycloak")); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "marykeycloak")); RoleModel realmRole1 = appRealm.getRole("realmRole1"); RoleModel realmRole2 = appRealm.getRole("realmRole2"); @@ -254,19 +254,19 @@ public void test02WriteMappings() { // 3 - Check that role mappings are in LDAP and hence available through federation Set johnRoles = john.getRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertTrue(johnRoles.contains(realmRole1)); - Assert.assertFalse(johnRoles.contains(realmRole2)); - Assert.assertTrue(johnRoles.contains(realmRole3)); - Assert.assertTrue(johnRoles.contains(financeRole1)); + Assertions.assertTrue(johnRoles.contains(realmRole1)); + Assertions.assertFalse(johnRoles.contains(realmRole2)); + Assertions.assertTrue(johnRoles.contains(realmRole3)); + Assertions.assertTrue(johnRoles.contains(financeRole1)); Set johnRealmRoles = john.getRealmRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertEquals(2, johnRealmRoles.size()); - Assert.assertTrue(johnRealmRoles.contains(realmRole1)); - Assert.assertTrue(johnRealmRoles.contains(realmRole3)); + Assertions.assertEquals(2, johnRealmRoles.size()); + Assertions.assertTrue(johnRealmRoles.contains(realmRole1)); + Assertions.assertTrue(johnRealmRoles.contains(realmRole3)); Set johnFinanceRoles = john.getClientRoleMappingsStream(financeApp).collect(Collectors.toSet()); - Assert.assertEquals(1, johnFinanceRoles.size()); - Assert.assertTrue(johnFinanceRoles.contains(financeRole1)); + Assertions.assertEquals(1, johnFinanceRoles.size()); + Assertions.assertTrue(johnFinanceRoles.contains(financeRole1)); // 4 - Delete some role mappings and check they are deleted @@ -275,10 +275,10 @@ public void test02WriteMappings() { john.deleteRoleMapping(financeRole1); johnRoles = john.getRoleMappingsStream().collect(Collectors.toSet()); - Assert.assertFalse(johnRoles.contains(realmRole1)); - Assert.assertFalse(johnRoles.contains(realmRole2)); - Assert.assertFalse(johnRoles.contains(realmRole3)); - Assert.assertFalse(johnRoles.contains(financeRole1)); + Assertions.assertFalse(johnRoles.contains(realmRole1)); + Assertions.assertFalse(johnRoles.contains(realmRole2)); + Assertions.assertFalse(johnRoles.contains(realmRole3)); + Assertions.assertFalse(johnRoles.contains(financeRole1)); // Cleanup mary.deleteRoleMapping(realmRole2); @@ -302,13 +302,13 @@ public void test03_newUserDefaultRolesNoImportModeTest() throws Exception { UserModel david = session.users().addUser(appRealm, "davidkeycloak"); // make sure we are in no-import mode - Assert.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "davidkeycloak")); + Assertions.assertNull(UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(appRealm, "davidkeycloak")); RoleModel defaultRole = appRealm.getRole("realmRole1"); RoleModel realmRole2 = appRealm.getRole("realmRole2"); - Assert.assertNotNull(defaultRole); - Assert.assertNotNull(realmRole2); + Assertions.assertNotNull(defaultRole); + Assertions.assertNotNull(realmRole2); // Set a default role on the realm appRealm.addToDefaultRoles(defaultRole); @@ -316,17 +316,17 @@ public void test03_newUserDefaultRolesNoImportModeTest() throws Exception { Set davidRoles = david.getRealmRoleMappingsStream().collect(Collectors.toSet()); // default role is not assigned directly - Assert.assertFalse(davidRoles.contains(defaultRole)); - Assert.assertFalse(davidRoles.contains(realmRole2)); + Assertions.assertFalse(davidRoles.contains(defaultRole)); + Assertions.assertFalse(davidRoles.contains(realmRole2)); // but david should have the role as effective - Assert.assertTrue(david.hasRole(defaultRole)); - Assert.assertFalse(david.hasRole(realmRole2)); + Assertions.assertTrue(david.hasRole(defaultRole)); + Assertions.assertFalse(david.hasRole(realmRole2)); // Make sure john has not received the default role UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak"); - Assert.assertFalse(john.hasRole(defaultRole)); + Assertions.assertFalse(john.hasRole(defaultRole)); }); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPSearchForUsersPaginationNoImportTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPSearchForUsersPaginationNoImportTest.java index deb31586d16f..bcd58a622f56 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPSearchForUsersPaginationNoImportTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPSearchForUsersPaginationNoImportTest.java @@ -34,10 +34,10 @@ import org.keycloak.testsuite.util.LDAPTestUtils; import org.keycloak.testsuite.util.UserBuilder; -import org.junit.Assert; import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import static org.hamcrest.MatcherAssert.assertThat; @@ -152,12 +152,12 @@ public void testSearchLDAPStreet() { Set usernames = testRealm().users().searchByAttributes("street:\"Acacia Avenue\"") .stream().map(UserRepresentation::getUsername) .collect(Collectors.toSet()); - Assert.assertEquals(Set.of("john", "john00", "john01"), usernames); + Assertions.assertEquals(Set.of("john", "john00", "john01"), usernames); usernames = testRealm().users().searchByAttributes(0, 5, true, true, "street:\"Acacia Avenue\"") .stream().map(UserRepresentation::getUsername) .collect(Collectors.toSet()); - Assert.assertEquals(Set.of("john", "john00", "john01"), usernames); + Assertions.assertEquals(Set.of("john", "john00", "john01"), usernames); } @Test @@ -166,37 +166,37 @@ public void testSearchNonExact() { .stream() .map(UserRepresentation::getUsername) .collect(Collectors.toSet()); - Assert.assertEquals(Set.of("john01", "john11"), usernames); + Assertions.assertEquals(Set.of("john01", "john11"), usernames); usernames = testRealm().users().searchByEmail("1@email.org", false) .stream() .map(UserRepresentation::getUsername) .collect(Collectors.toSet()); - Assert.assertEquals(Set.of("john01", "john11"), usernames); + Assertions.assertEquals(Set.of("john01", "john11"), usernames); } @Test public void testSearchLDAPLdapId() { UserRepresentation john = testRealm().users().search("john", true).stream().findAny().orElse(null); - Assert.assertNotNull(john); - Assert.assertNotNull(john.firstAttribute(LDAPConstants.LDAP_ID)); + Assertions.assertNotNull(john); + Assertions.assertNotNull(john.firstAttribute(LDAPConstants.LDAP_ID)); Set usernames = testRealm().users() .searchByAttributes(LDAPConstants.LDAP_ID + ":" + john.firstAttribute(LDAPConstants.LDAP_ID)) .stream().map(UserRepresentation::getUsername) .collect(Collectors.toSet()); - Assert.assertEquals(Set.of("john"), usernames); + Assertions.assertEquals(Set.of("john"), usernames); } @Test public void testSearchLDAPLdapEntryDn() { UserRepresentation john = testRealm().users().search("john", true).stream().findAny().orElse(null); - Assert.assertNotNull(john); - Assert.assertNotNull(john.firstAttribute(LDAPConstants.LDAP_ENTRY_DN)); + Assertions.assertNotNull(john); + Assertions.assertNotNull(john.firstAttribute(LDAPConstants.LDAP_ENTRY_DN)); Set usernames = testRealm().users() .searchByAttributes(LDAPConstants.LDAP_ENTRY_DN + ":" + john.firstAttribute(LDAPConstants.LDAP_ENTRY_DN)) .stream().map(UserRepresentation::getUsername) .collect(Collectors.toSet()); - Assert.assertEquals(Set.of("john"), usernames); + Assertions.assertEquals(Set.of("john"), usernames); } public void testDuplicateEmailInDatabase() { @@ -207,7 +207,7 @@ public void testDuplicateEmailInDatabase() { .username("jdoe").firstName("John").lastName("Doe") .email("john14@email.org") .build())); - Assert.assertNotNull("User not created", userId); + Assertions.assertNotNull(userId, "User not created"); getCleanup().addUserId(userId); } finally { setLDAPEnabled(true); @@ -216,9 +216,9 @@ public void testDuplicateEmailInDatabase() { List search = adminClient.realm(TEST_REALM_NAME).users() .search("john14@email.org", null, null) .stream().collect(Collectors.toList()); - Assert.assertEquals("User not found", 1, search.size()); - Assert.assertEquals("Incorrect User", "jdoe", search.get(0).getUsername()); - Assert.assertTrue("Duplicated user created", adminClient.realm(TEST_REALM_NAME).users().search("john", true).isEmpty()); + Assertions.assertEquals(1, search.size(), "User not found"); + Assertions.assertEquals("jdoe", search.get(0).getUsername(), "Incorrect User"); + Assertions.assertTrue(adminClient.realm(TEST_REALM_NAME).users().search("john", true).isEmpty(), "Duplicated user created"); } private void setLDAPEnabled(final boolean enabled) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/BackwardsCompatibilityUserStorageTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/BackwardsCompatibilityUserStorageTest.java index e71f0fc1e23d..a0e5e70bf1ba 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/BackwardsCompatibilityUserStorageTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/BackwardsCompatibilityUserStorageTest.java @@ -69,6 +69,7 @@ import org.jboss.arquillian.graphene.page.Page; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebDriver; import static org.wildfly.common.Assert.assertTrue; @@ -180,7 +181,7 @@ private String addUserAndResetPassword(String username, String password) { Response response = testRealm().users().create(user); String userId = ApiUtil.getCreatedId(response); - Assert.assertEquals(backwardsCompProviderId, new StorageId(userId).getProviderId()); + Assertions.assertEquals(backwardsCompProviderId, new StorageId(userId).getProviderId()); // Update his password CredentialRepresentation passwordRep = new CredentialRepresentation(); @@ -225,7 +226,7 @@ public void testOTPUpdateAndLogin() throws URISyntaxException, IOException { loginTotpPage.assertCurrent(); loginTotpPage.login("7123456"); loginTotpPage.assertCurrent(); - Assert.assertNotNull(loginTotpPage.getInputError()); + Assertions.assertNotNull(loginTotpPage.getInputError()); // Authenticate as the user with correct OTP loginTotpPage.login(totp.generateTOTP(totpSecret)); @@ -318,17 +319,17 @@ public void testOTPSetupAndRemoveThroughAccountMgmtAndLogin() throws URISyntaxEx // Get credentials by account REST. User should have OTP credential List otpCreds = getOtpCredentialFromAccountREST(accountCredentialsUrl, httpClient, tokenUtil); - Assert.assertEquals(1, otpCreds.size()); + Assertions.assertEquals(1, otpCreds.size()); String otpCredentialId = otpCreds.get(0).getCredential().getId(); // Delete OTP credential from federated storage int deleteStatus = SimpleHttpDefault.doDelete(accountCredentialsUrl + "/" + otpCredentialId, oauth.httpClient().get()) .auth(accountToken).acceptJson().asStatus(); - Assert.assertEquals(204, deleteStatus); + Assertions.assertEquals(204, deleteStatus); // Get credentials by account REST. User should not have OTP credential otpCreds = getOtpCredentialFromAccountREST(accountCredentialsUrl, httpClient, tokenUtil); - Assert.assertEquals(0, otpCreds.size()); + Assertions.assertEquals(0, otpCreds.size()); assertUserDontHaveDBCredentials(); assertUserHasOTPCredentialInUserStorage(false); @@ -438,7 +439,7 @@ private void assertUserDontHaveDBCredentials() { testingClient.server().run(session -> { RealmModel realm1 = session.realms().getRealmByName("test"); UserModel user1 = session.users().getUserByUsername(realm1, "otp1"); - Assert.assertEquals(0, user1.credentialManager().getStoredCredentialsStream().count()); + Assertions.assertEquals(0, user1.credentialManager().getStoredCredentialsStream().count()); }); } @@ -448,7 +449,7 @@ private void assertUserHasOTPCredentialInUserStorage(boolean expectedUserHasOTP) .getProviderFactory(UserStorageProvider.class, BackwardsCompatibilityUserStorageFactory.PROVIDER_ID); return storageFactory.hasUserOTP("otp1"); }, Boolean.class); - Assert.assertEquals(expectedUserHasOTP, hasUserOTP); + Assertions.assertEquals(expectedUserHasOTP, hasUserOTP); } private void assertUserHasRecoveryKeysCredentialInUserStorage(boolean expectedUserHasRecoveryKeys) { @@ -457,7 +458,7 @@ private void assertUserHasRecoveryKeysCredentialInUserStorage(boolean expectedUs .getProviderFactory(UserStorageProvider.class, BackwardsCompatibilityUserStorageFactory.PROVIDER_ID); return storageFactory.hasRecoveryCodes("otp1"); }, Boolean.class); - Assert.assertEquals(expectedUserHasRecoveryKeys, hasRecoveryKeys); + Assertions.assertEquals(expectedUserHasRecoveryKeys, hasRecoveryKeys); } private List getOtpCredentialFromAccountREST(String accountCredentialsUrl, CloseableHttpClient httpClient, TokenUtil tokenUtil) throws IOException { @@ -476,7 +477,7 @@ private void enterRecoveryCodes(EnterRecoveryAuthnCodePage enterRecoveryAuthnCod enterRecoveryAuthnCodePage.setDriver(driver); enterRecoveryAuthnCodePage.assertCurrent(); int requestedCode = enterRecoveryAuthnCodePage.getRecoveryAuthnCodeToEnterNumber(); - org.junit.Assert.assertEquals("Incorrect code presented to login", expectedCode, requestedCode); + Assertions.assertEquals(expectedCode, requestedCode, "Incorrect code presented to login"); enterRecoveryAuthnCodePage.enterRecoveryAuthnCode(generatedRecoveryAuthnCodes.get(requestedCode)); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/BrokenUserStorageTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/BrokenUserStorageTest.java index 913958eed629..37d0380e5b0d 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/BrokenUserStorageTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/BrokenUserStorageTest.java @@ -34,8 +34,8 @@ import org.jboss.arquillian.graphene.page.Page; import org.jboss.arquillian.test.api.ArquillianResource; import org.junit.After; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * KEYCLOAK-3903 and KEYCLOAK-3620 @@ -62,8 +62,8 @@ public void configureTestRealm(RealmRepresentation testRealm) { private void loginSuccessAndLogout(String username, String password) { oauth.openLoginForm(); loginPage.login(username, password); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); oauth.openLogoutForm(); } @@ -101,12 +101,12 @@ public void testBootWithBadProviderId() throws Exception { found = rep; } } - Assert.assertNotNull(found); + Assertions.assertNotNull(found); master.components().component(found.getId()).remove(); List components2 = master.components().query(masterId, UserStorageProvider.class.getName()); - Assert.assertEquals(components.size() - 1, components2.size()); + Assertions.assertEquals(components.size() - 1, components2.size()); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/ClientStorageTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/ClientStorageTest.java index cd2e041c7f75..938f51a3f621 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/ClientStorageTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/ClientStorageTest.java @@ -65,10 +65,10 @@ import org.keycloak.util.TokenUtil; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static java.util.Calendar.DAY_OF_WEEK; import static java.util.Calendar.HOUR_OF_DAY; @@ -80,7 +80,7 @@ import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test that clients can override auth flows @@ -209,20 +209,20 @@ public void testClientStats() throws Exception { boolean directTested = false; for (Map entry : list) { if (entry.get("clientId").equals("hardcoded-client")) { - Assert.assertEquals("2", entry.get("active")); - Assert.assertEquals("2", entry.get("offline")); + Assertions.assertEquals("2", entry.get("active")); + Assertions.assertEquals("2", entry.get("offline")); hardTested = true; } else if (entry.get("clientId").equals("test-app")) { - Assert.assertEquals("1", entry.get("active")); - Assert.assertEquals("0", entry.get("offline")); + Assertions.assertEquals("1", entry.get("active")); + Assertions.assertEquals("0", entry.get("offline")); testAppTested = true; } else if (entry.get("clientId").equals("direct-grant")) { - Assert.assertEquals("1", entry.get("active")); - Assert.assertEquals("2", entry.get("offline")); + Assertions.assertEquals("1", entry.get("active")); + Assertions.assertEquals("2", entry.get("offline")); directTested = true; } } - Assert.assertTrue(hardTested && testAppTested && directTested); + Assertions.assertTrue(hardTested && testAppTested && directTested); testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); @@ -230,14 +230,14 @@ public void testClientStats() throws Exception { ClientModel hardcoded = realm.getClientByClientId("hardcoded-client"); long activeUserSessions = session.sessions().getActiveUserSessions(realm, hardcoded); long offlineSessionsCount = session.sessions().getOfflineSessionsCount(realm, hardcoded); - Assert.assertEquals(2, activeUserSessions); - Assert.assertEquals(2, offlineSessionsCount); + Assertions.assertEquals(2, activeUserSessions); + Assertions.assertEquals(2, offlineSessionsCount); ClientModel direct = realm.getClientByClientId("direct-grant"); activeUserSessions = session.sessions().getActiveUserSessions(realm, direct); offlineSessionsCount = session.sessions().getOfflineSessionsCount(realm, direct); - Assert.assertEquals(1, activeUserSessions); - Assert.assertEquals(2, offlineSessionsCount); + Assertions.assertEquals(1, activeUserSessions); + Assertions.assertEquals(2, offlineSessionsCount); }); } @@ -257,8 +257,8 @@ private void testBrowser(String clientId) { events.expectLogin().client(clientId).detail(Details.USERNAME, "test-user@localhost").assertEvent(); AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(response.getCode()); - Assert.assertNotNull(tokenResponse.getAccessToken()); - Assert.assertNotNull(tokenResponse.getRefreshToken()); + Assertions.assertNotNull(tokenResponse.getAccessToken()); + Assertions.assertNotNull(tokenResponse.getRefreshToken()); events.clear(); @@ -398,8 +398,8 @@ private void testNotCached() { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); ClientModel hardcoded = realm.getClientByClientId("hardcoded-client"); - Assert.assertNotNull(hardcoded); - Assert.assertFalse(hardcoded instanceof ClientAdapter); + Assertions.assertNotNull(hardcoded); + Assertions.assertFalse(hardcoded instanceof ClientAdapter); }); } @@ -409,8 +409,8 @@ public void testIsCached() { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); ClientModel hardcoded = realm.getClientByClientId("hardcoded-client"); - Assert.assertNotNull(hardcoded); - Assert.assertTrue(hardcoded instanceof org.keycloak.models.cache.infinispan.ClientAdapter); + Assertions.assertNotNull(hardcoded); + Assertions.assertTrue(hardcoded instanceof org.keycloak.models.cache.infinispan.ClientAdapter); }); } @@ -452,7 +452,7 @@ public void offlineTokenDirectGrantFlow() throws Exception { oauth.scope(OAuth2Constants.OFFLINE_ACCESS); oauth.client("hardcoded-client", "password"); AccessTokenResponse tokenResponse = oauth.doPasswordGrantRequest("test-user@localhost", "password"); - Assert.assertNull(tokenResponse.getErrorDescription()); + Assertions.assertNull(tokenResponse.getErrorDescription()); AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken()); String offlineTokenString = tokenResponse.getRefreshToken(); RefreshToken offlineToken = oauth.parseRefreshToken(offlineTokenString); @@ -471,8 +471,8 @@ public void offlineTokenDirectGrantFlow() throws Exception { .removeDetail(Details.CONSENT) .assertEvent(); - Assert.assertEquals(TokenUtil.TOKEN_TYPE_OFFLINE, offlineToken.getType()); - Assert.assertNull(offlineToken.getExp()); + Assertions.assertEquals(TokenUtil.TOKEN_TYPE_OFFLINE, offlineToken.getType()); + Assertions.assertNull(offlineToken.getExp()); testRefreshWithOfflineToken(token, offlineToken, offlineTokenString, token.getSessionState(), userId); @@ -483,7 +483,7 @@ public void offlineTokenDirectGrantFlowNoRefresh(String clientId) throws Excepti oauth.scope(OAuth2Constants.OFFLINE_ACCESS); oauth.clientId(clientId); AccessTokenResponse tokenResponse = oauth.doPasswordGrantRequest("test-user@localhost", "password"); - Assert.assertNull(tokenResponse.getErrorDescription()); + Assertions.assertNull(tokenResponse.getErrorDescription()); AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken()); String offlineTokenString = tokenResponse.getRefreshToken(); RefreshToken offlineToken = oauth.parseRefreshToken(offlineTokenString); @@ -493,8 +493,8 @@ private String testRefreshWithOfflineToken(AccessToken oldToken, RefreshToken of final String sessionId, String userId) { // Change offset to big value to ensure userSession expired setTimeOffset(99999); - Assert.assertFalse(oldToken.isActive()); - Assert.assertTrue(offlineToken.isActive()); + Assertions.assertFalse(oldToken.isActive()); + Assertions.assertTrue(offlineToken.isActive()); // Assert userSession expired testingClient.testing().removeExpired("test"); @@ -509,17 +509,17 @@ private String testRefreshWithOfflineToken(AccessToken oldToken, RefreshToken of String offlineUserSessionId = testingClient.server().fetch((KeycloakSession session) -> session.sessions().getOfflineUserSession(session.realms().getRealmByName("test"), offlineToken.getSessionState()).getId(), String.class); - Assert.assertEquals(200, response.getStatusCode()); - Assert.assertEquals(offlineUserSessionId, refreshedToken.getSessionState()); + Assertions.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(offlineUserSessionId, refreshedToken.getSessionState()); // Assert new refreshToken in the response String newRefreshToken = response.getRefreshToken(); - Assert.assertNotNull(newRefreshToken); - Assert.assertNotEquals(oldToken.getId(), refreshedToken.getId()); + Assertions.assertNotNull(newRefreshToken); + Assertions.assertNotEquals(oldToken.getId(), refreshedToken.getId()); - Assert.assertEquals(userId, refreshedToken.getSubject()); + Assertions.assertEquals(userId, refreshedToken.getSubject()); - Assert.assertTrue(refreshedToken.getRealmAccess().isUserInRole(Constants.OFFLINE_ACCESS_ROLE)); + Assertions.assertTrue(refreshedToken.getRealmAccess().isUserInRole(Constants.OFFLINE_ACCESS_ROLE)); EventRepresentation refreshEvent = events.expectRefresh(offlineToken.getId(), sessionId) @@ -528,7 +528,7 @@ private String testRefreshWithOfflineToken(AccessToken oldToken, RefreshToken of .removeDetail(Details.UPDATED_REFRESH_TOKEN_ID) .detail(Details.REFRESH_TOKEN_TYPE, TokenUtil.TOKEN_TYPE_OFFLINE) .assertEvent(); - Assert.assertNotEquals(oldToken.getId(), refreshEvent.getDetails().get(Details.TOKEN_ID)); + Assertions.assertNotEquals(oldToken.getId(), refreshEvent.getDetails().get(Details.TOKEN_ID)); setTimeOffset(0); return newRefreshToken; diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/ComponentExportImportTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/ComponentExportImportTest.java index 69b0f062e742..7f45e54d3f3f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/ComponentExportImportTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/ComponentExportImportTest.java @@ -23,13 +23,13 @@ import org.keycloak.testsuite.federation.UserMapStorageFactory; import org.keycloak.testsuite.util.RealmBuilder; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.storage.UserStorageProviderModel.IMPORT_ENABLED; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @@ -136,21 +136,21 @@ public void testSingleFile() { try { testRealmResource().toRepresentation(); - Assert.fail("Realm wasn't expected to be found"); + Assertions.fail("Realm wasn't expected to be found"); } catch (NotFoundException nfe) { // Expected } // import testingClient.server().run(session -> { - Assert.assertNull(session.realms().getRealmByName(REALM_NAME)); + Assertions.assertNull(session.realms().getRealmByName(REALM_NAME)); try (Closeable c = ExportImportConfig.setAction(ExportImportConfig.ACTION_IMPORT)) { new ExportImportManager(session).runImport(); } }); // Assert realm was imported - Assert.assertNotNull(testRealmResource().toRepresentation()); + Assertions.assertNotNull(testRealmResource().toRepresentation()); try { parentComponent = testRealmResource().components().component(parentComponentId).toRepresentation(); @@ -159,19 +159,19 @@ public void testSingleFile() { fail("Components not found after import."); } - Assert.assertEquals(parentComponent.getParentId(), realmId); - Assert.assertEquals(parentComponent.getName(), "parent"); - Assert.assertEquals(parentComponent.getSubType(), "subtype"); - Assert.assertEquals(parentComponent.getProviderId(), UserMapStorageFactory.PROVIDER_ID); - Assert.assertEquals(parentComponent.getProviderType(), UserStorageProvider.class.getName()); - Assert.assertEquals(parentComponent.getConfig().getFirst("attr"), "value"); - - Assert.assertEquals(subcomponent.getParentId(), parentComponent.getId()); - Assert.assertEquals(subcomponent.getName(), "child"); - Assert.assertEquals(subcomponent.getSubType(), "subtype2"); - Assert.assertEquals(subcomponent.getProviderId(), UserMapStorageFactory.PROVIDER_ID); - Assert.assertEquals(subcomponent.getProviderType(), UserStorageProvider.class.getName()); - Assert.assertEquals(subcomponent.getConfig().getFirst("attr"), "value2"); + Assertions.assertEquals(parentComponent.getParentId(), realmId); + Assertions.assertEquals(parentComponent.getName(), "parent"); + Assertions.assertEquals(parentComponent.getSubType(), "subtype"); + Assertions.assertEquals(parentComponent.getProviderId(), UserMapStorageFactory.PROVIDER_ID); + Assertions.assertEquals(parentComponent.getProviderType(), UserStorageProvider.class.getName()); + Assertions.assertEquals(parentComponent.getConfig().getFirst("attr"), "value"); + + Assertions.assertEquals(subcomponent.getParentId(), parentComponent.getId()); + Assertions.assertEquals(subcomponent.getName(), "child"); + Assertions.assertEquals(subcomponent.getSubType(), "subtype2"); + Assertions.assertEquals(subcomponent.getProviderId(), UserMapStorageFactory.PROVIDER_ID); + Assertions.assertEquals(subcomponent.getProviderType(), UserStorageProvider.class.getName()); + Assertions.assertEquals(subcomponent.getConfig().getFirst("attr"), "value2"); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/FederatedStorageExportImportTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/FederatedStorageExportImportTest.java index 99b1c51d4a6b..643910fc61c3 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/FederatedStorageExportImportTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/FederatedStorageExportImportTest.java @@ -44,11 +44,11 @@ import org.keycloak.testsuite.AbstractAuthTest; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Bill Burke @@ -135,7 +135,7 @@ public void testSingleFile() { }); testingClient.server().run(session -> { - Assert.assertNull(session.realms().getRealmByName(REALM_NAME)); + Assertions.assertNull(session.realms().getRealmByName(REALM_NAME)); try (Closeable c = ExportImportConfig.setAction(ExportImportConfig.ACTION_IMPORT)) { new ExportImportManager(session).runImport(); } @@ -143,24 +143,24 @@ public void testSingleFile() { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName(REALM_NAME); - Assert.assertNotNull(realm); + Assertions.assertNotNull(realm); RoleModel role = realm.getRole("test-role"); GroupModel group = realm.getGroupById(groupId); - Assert.assertEquals(1, UserStorageUtil.userFederatedStorage(session).getStoredUsersCount(realm)); + Assertions.assertEquals(1, UserStorageUtil.userFederatedStorage(session).getStoredUsersCount(realm)); MultivaluedHashMap attributes = UserStorageUtil.userFederatedStorage(session).getAttributes(realm, userId); - Assert.assertEquals(3, attributes.size()); - Assert.assertEquals("value1", attributes.getFirst("single1")); - Assert.assertTrue(attributes.getList("list1").contains("1")); - Assert.assertTrue(attributes.getList("list1").contains("2")); - Assert.assertTrue(UserStorageUtil.userFederatedStorage(session).getRequiredActionsStream(realm, userId) + Assertions.assertEquals(3, attributes.size()); + Assertions.assertEquals("value1", attributes.getFirst("single1")); + Assertions.assertTrue(attributes.getList("list1").contains("1")); + Assertions.assertTrue(attributes.getList("list1").contains("2")); + Assertions.assertTrue(UserStorageUtil.userFederatedStorage(session).getRequiredActionsStream(realm, userId) .collect(Collectors.toSet()).contains("UPDATE_PASSWORD")); - Assert.assertTrue(UserStorageUtil.userFederatedStorage(session).getRoleMappingsStream(realm, userId) + Assertions.assertTrue(UserStorageUtil.userFederatedStorage(session).getRoleMappingsStream(realm, userId) .collect(Collectors.toSet()).contains(role)); - Assert.assertTrue(UserStorageUtil.userFederatedStorage(session).getGroupsStream(realm, userId).collect(Collectors.toSet()).contains(group)); + Assertions.assertTrue(UserStorageUtil.userFederatedStorage(session).getGroupsStream(realm, userId).collect(Collectors.toSet()).contains(group)); List creds = UserStorageUtil.userFederatedStorage(session).getStoredCredentialsStream(realm, userId).collect(Collectors.toList()); - Assert.assertEquals(1, creds.size()); - Assert.assertTrue(FederatedStorageExportImportTest.getHashProvider(session, realm.getPasswordPolicy()) + Assertions.assertEquals(1, creds.size()); + Assertions.assertTrue(FederatedStorageExportImportTest.getHashProvider(session, realm.getPasswordPolicy()) .verify("password", PasswordCredentialModel.createFromCredentialModel(creds.get(0)))); }); } @@ -186,7 +186,7 @@ public void testCreateCredentialWithDuplicateUserLabelShouldFail() { try { UserStorageUtil.userFederatedStorage(session).createCredential(realm, userId, cred2); - Assert.fail("Expected ModelDuplicateException was not thrown"); + Assertions.fail("Expected ModelDuplicateException was not thrown"); } catch (ModelDuplicateException ex) { assertEquals("Device already exists with the same name", ex.getMessage()); } @@ -225,7 +225,7 @@ public void testUpdateCredentialWithDuplicateUserLabelShouldFail() { try { UserStorageUtil.userFederatedStorage(session).updateCredential(realm, userId, credentialModelUpdate); - Assert.fail("Expected ModelDuplicateException was not thrown"); + Assertions.fail("Expected ModelDuplicateException was not thrown"); } catch (ModelDuplicateException ex) { assertEquals("Device already exists with the same name", ex.getMessage()); } @@ -273,7 +273,7 @@ public void testDir() { testingClient.server().run(session -> { - Assert.assertNull(session.realms().getRealmByName(REALM_NAME)); + Assertions.assertNull(session.realms().getRealmByName(REALM_NAME)); try (Closeable c = ExportImportConfig.setAction(ExportImportConfig.ACTION_IMPORT)) { new ExportImportManager(session).runImport(); } @@ -281,25 +281,25 @@ public void testDir() { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName(REALM_NAME); - Assert.assertNotNull(realm); + Assertions.assertNotNull(realm); RoleModel role = realm.getRole("test-role"); GroupModel group = realm.getGroupById(groupId); - Assert.assertEquals(1, UserStorageUtil.userFederatedStorage(session).getStoredUsersCount(realm)); + Assertions.assertEquals(1, UserStorageUtil.userFederatedStorage(session).getStoredUsersCount(realm)); MultivaluedHashMap attributes = UserStorageUtil.userFederatedStorage(session).getAttributes(realm, userId); - Assert.assertEquals(3, attributes.size()); - Assert.assertEquals("value1", attributes.getFirst("single1")); - Assert.assertTrue(attributes.getList("list1").contains("1")); - Assert.assertTrue(attributes.getList("list1").contains("2")); - Assert.assertTrue(UserStorageUtil.userFederatedStorage(session).getRequiredActionsStream(realm, userId) + Assertions.assertEquals(3, attributes.size()); + Assertions.assertEquals("value1", attributes.getFirst("single1")); + Assertions.assertTrue(attributes.getList("list1").contains("1")); + Assertions.assertTrue(attributes.getList("list1").contains("2")); + Assertions.assertTrue(UserStorageUtil.userFederatedStorage(session).getRequiredActionsStream(realm, userId) .collect(Collectors.toSet()).contains("UPDATE_PASSWORD")); - Assert.assertTrue(UserStorageUtil.userFederatedStorage(session).getRoleMappingsStream(realm, userId) + Assertions.assertTrue(UserStorageUtil.userFederatedStorage(session).getRoleMappingsStream(realm, userId) .collect(Collectors.toSet()).contains(role)); - Assert.assertTrue(UserStorageUtil.userFederatedStorage(session).getGroupsStream(realm, userId).collect(Collectors.toSet()).contains(group)); - Assert.assertEquals(50, UserStorageUtil.userFederatedStorage(session).getNotBeforeOfUser(realm, userId)); + Assertions.assertTrue(UserStorageUtil.userFederatedStorage(session).getGroupsStream(realm, userId).collect(Collectors.toSet()).contains(group)); + Assertions.assertEquals(50, UserStorageUtil.userFederatedStorage(session).getNotBeforeOfUser(realm, userId)); List creds = UserStorageUtil.userFederatedStorage(session).getStoredCredentialsStream(realm, userId).collect(Collectors.toList()); - Assert.assertEquals(1, creds.size()); - Assert.assertTrue(FederatedStorageExportImportTest.getHashProvider(session, realm.getPasswordPolicy()) + Assertions.assertEquals(1, creds.size()); + Assertions.assertTrue(FederatedStorageExportImportTest.getHashProvider(session, realm.getPasswordPolicy()) .verify("password", PasswordCredentialModel.createFromCredentialModel(creds.get(0)))); }); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/GroupStorageTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/GroupStorageTest.java index 7ecb6f31b521..1e73c9a55f4b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/GroupStorageTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/GroupStorageTest.java @@ -43,7 +43,7 @@ import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; public class GroupStorageTest extends AbstractTestRealmKeycloakTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/RoleStorageTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/RoleStorageTest.java index 678e5baf7640..f05164372709 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/RoleStorageTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/RoleStorageTest.java @@ -43,7 +43,7 @@ import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; public class RoleStorageTest extends AbstractTestRealmKeycloakTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageFailureTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageFailureTest.java index 96c251500395..69712f38b25c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageFailureTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageFailureTest.java @@ -58,17 +58,17 @@ import org.jboss.arquillian.container.test.api.ContainerController; import org.jboss.arquillian.graphene.page.Page; import org.jboss.arquillian.test.api.ArquillianResource; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.storage.CacheableStorageProviderModel.CACHE_POLICY; import static org.keycloak.storage.CacheableStorageProviderModel.MAX_LIFESPAN; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Bill Burke @@ -131,7 +131,7 @@ public void addProvidersBeforeTest() { UserModel serviceAccount = manager.getSession().users().addUser(appRealm, ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + offlineClient.getClientId()); serviceAccount.setEnabled(true); RoleModel role = appRealm.getRole("offline_access"); - Assert.assertNotNull(role); + Assertions.assertNotNull(role); serviceAccount.grantRole(role); serviceAccount.setServiceAccountClientLink(offlineClient.getClientId()); @@ -188,7 +188,7 @@ public void testKeycloak5350() throws Exception { // test that once user storage provider is available again we can still access the token. tokenResponse = oauth.doRefreshTokenRequest(offlineTokenString); - Assert.assertNotNull(tokenResponse.getAccessToken()); + Assertions.assertNotNull(tokenResponse.getAccessToken()); oauth.verifyToken(tokenResponse.getAccessToken()); offlineTokenString = tokenResponse.getRefreshToken(); oauth.parseRefreshToken(offlineTokenString); @@ -244,9 +244,9 @@ private void loginSuccessAndLogout(String username, String password) { loginPage.login(username, password); System.out.println(driver.getCurrentUrl()); System.out.println(driver.getPageSource()); - Assert.assertTrue(appPage.isCurrent()); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertTrue(appPage.isCurrent()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); oauth.openLogoutForm(); } @@ -270,7 +270,7 @@ public void testKeycloak5926() { RealmModel realm = session.realms().getRealmByName(AuthRealm.TEST); UserModel user = session.users().getUserByUsername(realm, FailableHardcodedStorageProvider.username); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); }); @@ -289,29 +289,29 @@ public void testKeycloak5926() { RealmModel realm = session.realms().getRealmByName(AuthRealm.TEST); UserModel local = session.users().getUserByUsername(realm, LOCAL_USER); - Assert.assertNotNull(local); + Assertions.assertNotNull(local); Stream result; result = session.users().searchForUserStream(realm, Map.of(UserModel.SEARCH, LOCAL_USER)); - Assert.assertEquals(1, result.count()); + Assertions.assertEquals(1, result.count()); result = session.users().searchForUserStream(realm, Map.of(UserModel.SEARCH, FailableHardcodedStorageProvider.username)); - Assert.assertEquals(1, result.count()); + Assertions.assertEquals(1, result.count()); result = session.users().searchForUserStream(realm, Map.of(UserModel.SEARCH, LOCAL_USER), 0, 2); - Assert.assertEquals(1, result.count()); + Assertions.assertEquals(1, result.count()); result = session.users().searchForUserStream(realm, Map.of(UserModel.SEARCH, FailableHardcodedStorageProvider.username), 0, 2); - Assert.assertEquals(1, result.count()); + Assertions.assertEquals(1, result.count()); Map localParam = new HashMap<>(); localParam.put("username", LOCAL_USER); Map hardcodedParam = new HashMap<>(); hardcodedParam.put("username", FailableHardcodedStorageProvider.username); result = session.users().searchForUserStream(realm, localParam); - Assert.assertEquals(1, result.count()); + Assertions.assertEquals(1, result.count()); result = session.users().searchForUserStream(realm, hardcodedParam); - Assert.assertEquals(1, result.count()); + Assertions.assertEquals(1, result.count()); result = session.users().searchForUserStream(realm, localParam, 0, 2); - Assert.assertEquals(1, result.count()); + Assertions.assertEquals(1, result.count()); result = session.users().searchForUserStream(realm, hardcodedParam, 0, 2); - Assert.assertEquals(1, result.count()); + Assertions.assertEquals(1, result.count()); // we run a terminal operation on the stream to make sure it is consumed. session.users().searchForUserStream(realm, Collections.emptyMap()).count(); @@ -319,12 +319,12 @@ public void testKeycloak5926() { UserModel user = session.users().getUserByUsername(realm, FailableHardcodedStorageProvider.username); assertFalse(user instanceof CachedUserModel); - Assert.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername()); - Assert.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail()); + Assertions.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername()); + Assertions.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail()); assertFalse(user.isEnabled()); try { user.setEmail("error@error.com"); - Assert.fail(); + Assertions.fail(); } catch (Exception ex) { } @@ -336,8 +336,8 @@ public void testKeycloak5926() { UserModel user = session.users().getUserByUsername(realm, FailableHardcodedStorageProvider.username); assertFalse(user instanceof CachedUserModel); - Assert.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername()); - Assert.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail()); + Assertions.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername()); + Assertions.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail()); }); // make ABSOLUTELY sure user isn't cached as provider is disabled @@ -346,8 +346,8 @@ public void testKeycloak5926() { UserModel user = session.users().getUserByUsername(realm, FailableHardcodedStorageProvider.username); assertFalse(user instanceof CachedUserModel); - Assert.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername()); - Assert.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail()); + Assertions.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername()); + Assertions.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail()); }); @@ -360,9 +360,9 @@ public void testKeycloak5926() { RealmModel realm = session.realms().getRealmByName(AuthRealm.TEST); UserModel user = session.users().getUserByUsername(realm, FailableHardcodedStorageProvider.username); - Assert.assertTrue(user instanceof CachedUserModel); - Assert.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername()); - Assert.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail()); + Assertions.assertTrue(user instanceof CachedUserModel); + Assertions.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername()); + Assertions.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail()); }); events.clear(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageOTPTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageOTPTest.java index eecaa82b2ade..89ae373f4631 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageOTPTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageOTPTest.java @@ -54,6 +54,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.storage.UserStorageProviderModel.IMPORT_ENABLED; import static org.keycloak.testsuite.federation.storage.UserStorageTest.addComponent; @@ -115,7 +116,7 @@ public void addProvidersBeforeTest() throws URISyntaxException, IOException { public void testCredentialsThroughRESTAPI() { // Test that test-user has federation link on him UserResource user = AdminApiUtil.findUserByUsernameId(testRealm(), "test-user"); - Assert.assertEquals(componentId, user.toRepresentation().getFederationLink()); + Assertions.assertEquals(componentId, user.toRepresentation().getFederationLink()); // Test that both "password" and "otp" are configured for the test-user List userStorageCredentialTypes = user.getConfiguredUserStorageCredentialTypes(); @@ -133,13 +134,13 @@ public void testAuthentication() { loginTotpPage.login("654321"); loginTotpPage.assertCurrent(); - Assert.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); + Assertions.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); loginTotpPage.login(DummyUserFederationProvider.HARDCODED_OTP); appPage.assertCurrent(); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); } @@ -163,7 +164,7 @@ public void testUpdateOTP() throws IOException { // Dummy OTP code won't work when configure new OTP loginConfigTotpPage.configure(DummyUserFederationProvider.HARDCODED_OTP); - Assert.assertEquals("Invalid authenticator code.", loginConfigTotpPage.getInputCodeError()); + Assertions.assertEquals("Invalid authenticator code.", loginConfigTotpPage.getInputCodeError()); // This will save the credential to the local DB String totpSecret = loginConfigTotpPage.getTotpSecret(); @@ -223,11 +224,11 @@ public void testNormalUser() { // Assert he has federation link on him UserResource userResource = AdminApiUtil.findUserByUsernameId(testRealm(), "test-user2"); - Assert.assertEquals(componentId, userResource.toRepresentation().getFederationLink()); + Assertions.assertEquals(componentId, userResource.toRepresentation().getFederationLink()); // Assert no userStorage supported credentials shown through admin REST API for that user. For this user, the validation of password and OTP is not delegated // to the dummy user storage provider - Assert.assertTrue(userResource.getConfiguredUserStorageCredentialTypes().isEmpty()); + Assertions.assertTrue(userResource.getConfiguredUserStorageCredentialTypes().isEmpty()); // Update password AdminApiUtil.resetUserPassword(userResource, "pass", false); @@ -237,8 +238,8 @@ public void testNormalUser() { loginPage.login("test-user2", "pass"); appPage.assertCurrent(); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java index a2b82fa47591..9eb294363078 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java @@ -76,11 +76,11 @@ import org.hamcrest.Matchers; import org.jboss.arquillian.graphene.page.Page; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.Cookie; import static java.util.Calendar.DAY_OF_WEEK; @@ -103,11 +103,11 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @@ -195,7 +195,7 @@ public void afterTestCleanUp() throws URISyntaxException, IOException { //we need to clear userPasswords and userGroups from UserMapStorageFactory UserMapStorageFactory userMapStorageFactory = (UserMapStorageFactory) session.getKeycloakSessionFactory().getProviderFactory(UserStorageProvider.class, UserMapStorageFactory.PROVIDER_ID); - Assert.assertNotNull(userMapStorageFactory); + Assertions.assertNotNull(userMapStorageFactory); userMapStorageFactory.clear(); }); resetTimeOffset(); @@ -276,8 +276,8 @@ public void testLoginSuccessWithSpecialCharacter() { Cookie sameSiteSessionCookie = driver.manage().getCookieNamed(CookieType.SESSION.getName()); - Assert.assertNotNull(sameSiteSessionCookie); - Assert.assertNotNull(sameSiteSessionCookie.getValue()); + Assertions.assertNotNull(sameSiteSessionCookie); + Assertions.assertNotNull(sameSiteSessionCookie.getValue()); String cookieValue = sameSiteSessionCookie.getValue(); assertThat(cookieValue.contains("spécial"), is(false)); assertThat(cookieValue.contains("sp%C3%A9cial"), is(false)); @@ -304,13 +304,13 @@ public void testUpdate() { // check entity thor = AdminApiUtil.findUserByUsername(testRealmResource(), "thor"); - Assert.assertEquals("Stian", thor.getFirstName()); - Assert.assertEquals("Thorgersen", thor.getLastName()); - Assert.assertEquals("thor@hammer.com", thor.getEmail()); - Assert.assertTrue(thor.getAttributes().containsKey("test-attribute")); - Assert.assertEquals(1, thor.getAttributes().get("test-attribute").size()); - Assert.assertEquals("value", thor.getAttributes().get("test-attribute").get(0)); - Assert.assertTrue(thor.isEmailVerified()); + Assertions.assertEquals("Stian", thor.getFirstName()); + Assertions.assertEquals("Thorgersen", thor.getLastName()); + Assertions.assertEquals("thor@hammer.com", thor.getEmail()); + Assertions.assertTrue(thor.getAttributes().containsKey("test-attribute")); + Assertions.assertEquals(1, thor.getAttributes().get("test-attribute").size()); + Assertions.assertEquals("value", thor.getAttributes().get("test-attribute").get(0)); + Assertions.assertTrue(thor.isEmailVerified()); // update group GroupRepresentation g = new GroupRepresentation(); @@ -326,7 +326,7 @@ public void testUpdate() { foundGroup = true; } } - Assert.assertTrue(foundGroup); + Assertions.assertTrue(foundGroup); // check required actions assertTrue(thor.getRequiredActions().contains(UPDATE_PROFILE.name())); @@ -360,12 +360,12 @@ public void testUpdate() { thor = AdminApiUtil.findUserByUsername(testRealmResource(), "thor"); - Assert.assertNull(thor.getFirstName()); - Assert.assertNull(thor.getLastName()); - Assert.assertNull(thor.getEmail()); + Assertions.assertNull(thor.getFirstName()); + Assertions.assertNull(thor.getLastName()); + Assertions.assertNull(thor.getEmail()); // user after logout has set this attribute: fedNotBefore - Assert.assertTrue(thor.getAttributes().size() == 1); - Assert.assertFalse(thor.isEmailVerified()); + Assertions.assertTrue(thor.getAttributes().size() == 1); + Assertions.assertFalse(thor.isEmailVerified()); foundGroup = false; for (GroupRepresentation ug : testRealmResource().users().get(thor.getId()).groups()) { @@ -373,7 +373,7 @@ public void testUpdate() { foundGroup = true; } } - Assert.assertFalse(foundGroup); + Assertions.assertFalse(foundGroup); foundRole = false; for (RoleRepresentation rr : user(thor.getId()).roles().getAll().getRealmMappings()) { @@ -405,7 +405,7 @@ public void testRegisterWithRequiredEmail() throws Exception { verifyEmailPage.assertCurrent(); - Assert.assertEquals(1, greenMail.getReceivedMessages().length); + Assertions.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; @@ -437,7 +437,7 @@ public void testRegistration() { assertNotNull(memuser); assertNotNull(memuser.getFederationLink()); ComponentRepresentation origin = testRealmResource().components().component(memuser.getFederationLink()).toRepresentation(); - Assert.assertEquals("memory", origin.getName()); + Assertions.assertEquals("memory", origin.getName()); testRealmResource().users().get(memuser.getId()).remove(); try { @@ -466,17 +466,17 @@ public void testQuery() { usernames.add(user.getUsername()); log.info(user.getUsername()); } - Assert.assertEquals(10, queried.size()); - Assert.assertTrue(usernames.contains("thor")); - Assert.assertTrue(usernames.contains("zeus")); - Assert.assertTrue(usernames.contains("apollo")); - Assert.assertTrue(usernames.contains("perseus")); - Assert.assertTrue(usernames.contains("spécial")); - Assert.assertTrue(usernames.contains("tbrady")); - Assert.assertTrue(usernames.contains("rob")); - Assert.assertTrue(usernames.contains("jules")); - Assert.assertTrue(usernames.contains("danny")); - Assert.assertTrue(usernames.contains("UPPERCASE")); + Assertions.assertEquals(10, queried.size()); + Assertions.assertTrue(usernames.contains("thor")); + Assertions.assertTrue(usernames.contains("zeus")); + Assertions.assertTrue(usernames.contains("apollo")); + Assertions.assertTrue(usernames.contains("perseus")); + Assertions.assertTrue(usernames.contains("spécial")); + Assertions.assertTrue(usernames.contains("tbrady")); + Assertions.assertTrue(usernames.contains("rob")); + Assertions.assertTrue(usernames.contains("jules")); + Assertions.assertTrue(usernames.contains("danny")); + Assertions.assertTrue(usernames.contains("UPPERCASE")); // test searchForUser List users = testRealmResource().users().search("tbrady", 0, -1); @@ -511,10 +511,10 @@ public void testQuery() { usernames.add(u.getUsername()); log.info(u.getUsername()); } - Assert.assertEquals(3, queried.size()); - Assert.assertTrue(usernames.contains("apollo")); - Assert.assertTrue(usernames.contains("zeus")); - Assert.assertTrue(usernames.contains("thor")); + Assertions.assertEquals(3, queried.size()); + Assertions.assertTrue(usernames.contains("apollo")); + Assertions.assertTrue(usernames.contains("zeus")); + Assertions.assertTrue(usernames.contains("thor")); // search by single attribute testingClient.server().run(session -> { @@ -526,8 +526,8 @@ public void testQuery() { List userModels = session.users().searchForUserByUserAttributeStream(realm, "weapon", "hammer") .peek(System.out::println).collect(Collectors.toList()); - Assert.assertEquals(1, userModels.size()); - Assert.assertEquals("thor", userModels.get(0).getUsername()); + Assertions.assertEquals(1, userModels.size()); + Assertions.assertEquals("thor", userModels.get(0).getUsername()); }); } @@ -742,14 +742,14 @@ public void testNoCache() { RealmModel realm = session.realms().getRealmByName("test"); UserModel user = session.users().getUserByUsername(realm, "thor"); System.out.println("User class: " + user.getClass()); - Assert.assertFalse(user instanceof CachedUserModel); // should be evicted + Assertions.assertFalse(user instanceof CachedUserModel); // should be evicted }); testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); UserModel thor2 = session.users().getUserByUsername(realm, "thor"); - Assert.assertFalse(thor2 instanceof CachedUserModel); + Assertions.assertFalse(thor2 instanceof CachedUserModel); }); propProviderRW = testRealmResource().components().component(propProviderRWId).toRepresentation(); @@ -762,7 +762,7 @@ public void testNoCache() { testingClient.server().run(session -> { RealmModel realm = session.realms().getRealmByName("test"); UserModel user = session.users().getUserByUsername(realm, "thor"); - Assert.assertTrue(user instanceof CachedUserModel); + Assertions.assertTrue(user instanceof CachedUserModel); }); } @@ -775,19 +775,19 @@ public void testLifecycle() { RealmModel realm = session.realms().getRealmByName("test"); UserModel user = session.users().addUser(realm, "memuser"); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); user = session.users().getUserByUsername(realm, "nonexistent"); - Assert.assertNull(user); + Assertions.assertNull(user); - Assert.assertEquals(1, UserMapStorage.allocations.get()); - Assert.assertEquals(0, UserMapStorage.closings.get()); + Assertions.assertEquals(1, UserMapStorage.allocations.get()); + Assertions.assertEquals(0, UserMapStorage.closings.get()); session.users().removeUser(realm,session.users().getUserByUsername(realm, "memuser")); }); testingClient.server().run(session -> { - Assert.assertEquals(1, UserMapStorage.allocations.get()); - Assert.assertEquals(1, UserMapStorage.closings.get()); + Assertions.assertEquals(1, UserMapStorage.allocations.get()); + Assertions.assertEquals(1, UserMapStorage.closings.get()); }); } @@ -810,7 +810,7 @@ public void testEntityRemovalHooks() { testRealmResource().groups().group(gid1).remove(); testRealmResource().groups().group(gid2).remove(); testingClient.server().run(session -> { - Assert.assertEquals(2, UserMapStorage.groupRemovals.get()); + Assertions.assertEquals(2, UserMapStorage.groupRemovals.get()); UserMapStorage.realmRemovals.set(0); }); @@ -824,7 +824,7 @@ public void testEntityRemovalHooks() { testRealmResource().roles().get("role1").remove(); testRealmResource().roles().get("role2").remove(); testingClient.server().run(session -> { - Assert.assertEquals(2, UserMapStorage.roleRemovals.get()); + Assertions.assertEquals(2, UserMapStorage.roleRemovals.get()); UserMapStorage.realmRemovals.set(0); }); @@ -832,7 +832,7 @@ public void testEntityRemovalHooks() { RealmRepresentation testRealmRepresentation = testRealmResource().toRepresentation(); testRealmResource().remove(); testingClient.server().run(session -> { - Assert.assertEquals(1, UserMapStorage.realmRemovals.get()); + Assertions.assertEquals(1, UserMapStorage.realmRemovals.get()); UserMapStorage.realmRemovals.set(0); }); @@ -863,11 +863,11 @@ public void testRoleMembership() { RoleModel roleModel2 = session.roles().getRealmRole(realm, "role2"); List users = session.users().getRoleMembersStream(realm, roleModel1).map(UserModel::getUsername).collect(Collectors.toList()); - Assert.assertEquals(2, users.size()); + Assertions.assertEquals(2, users.size()); MatcherAssert.assertThat(users, Matchers.containsInAnyOrder("thor", "zeus")); users = session.users().getRoleMembersStream(realm, roleModel2).map(UserModel::getUsername).collect(Collectors.toList()); - Assert.assertEquals(1, users.size()); + Assertions.assertEquals(1, users.size()); MatcherAssert.assertThat(users, Matchers.containsInAnyOrder("thor")); }); @@ -901,9 +901,9 @@ public void testEntityRemovalHooksCascade() { // remove realm with groups and roles in it testRealmResource().remove(); testingClient.server().run(session -> { - Assert.assertEquals(1, UserMapStorage.realmRemovals.get()); - Assert.assertEquals(2, UserMapStorage.groupRemovals.get()); // check if group removal hooks were called - Assert.assertEquals(2, UserMapStorage.roleRemovals.get()); // check if role removal hooks were called + Assertions.assertEquals(1, UserMapStorage.realmRemovals.get()); + Assertions.assertEquals(2, UserMapStorage.groupRemovals.get()); // check if group removal hooks were called + Assertions.assertEquals(2, UserMapStorage.roleRemovals.get()); // check if role removal hooks were called }); } @@ -921,10 +921,10 @@ public void testCredentialCRUD(KeycloakSession session) { currentSession.getContext().setRealm(realm); UserModel user = currentSession.users().getUserByUsername(realm, "thor"); - Assert.assertFalse(StorageId.isLocalStorage(user.getId())); + Assertions.assertFalse(StorageId.isLocalStorage(user.getId())); Stream credentials = user.credentialManager().getStoredCredentialsStream(); - org.keycloak.testsuite.Assert.assertEquals(0, credentials.count()); + Assertions.assertEquals(0, credentials.count()); // Create password CredentialModel passwordCred = PasswordCredentialModel.createFromValues("my-algorithm", "theSalt".getBytes(), 22, "ABC"); @@ -972,7 +972,7 @@ public void testCredentialCRUD(KeycloakSession session) { assertOrder(list, passwordId.get(), otp2Id.get(), otp1Id.get()); // Move otp2 to the top - org.keycloak.testsuite.Assert.assertTrue(user.credentialManager().moveStoredCredentialTo(otp2Id.get(), null)); + Assertions.assertTrue(user.credentialManager().moveStoredCredentialTo(otp2Id.get(), null)); }); KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { @@ -1036,7 +1036,7 @@ public void testCRUDCredentialsOfDifferentUser() { RealmModel realm = session.realms().getRealmByName("test"); UserModel user = session.users().getUserByUsername(realm, "thor"); - Assert.assertFalse(StorageId.isLocalStorage(user.getId())); + Assertions.assertFalse(StorageId.isLocalStorage(user.getId())); CredentialModel otp1 = OTPCredentialModel.createFromPolicy(realm, "secret1"); user.credentialManager().createStoredCredential(otp1); @@ -1052,21 +1052,21 @@ public void testCRUDCredentialsOfDifferentUser() { UserResource user2 = AdminApiUtil.findUserByUsernameId(testRealmResource(), "tbrady"); try { user2.setCredentialUserLabel(otpCredential.getId(), "new-label"); - Assert.fail("Not expected to successfully update user label"); + Assertions.fail("Not expected to successfully update user label"); } catch (NotFoundException nfe) { // Expected } try { user2.moveCredentialToFirst(otpCredential.getId()); - Assert.fail("Not expected to successfully move credential"); + Assertions.fail("Not expected to successfully move credential"); } catch (NotFoundException nfe) { // Expected } try { user2.removeCredential(otpCredential.getId()); - Assert.fail("Not expected to successfully remove credential"); + Assertions.fail("Not expected to successfully remove credential"); } catch (NotFoundException nfe) { // Expected } @@ -1076,8 +1076,8 @@ public void testCRUDCredentialsOfDifferentUser() { .filter(credentialRep -> OTPCredentialModel.TYPE.equals(credentialRep.getType())) .findFirst() .get(); - Assert.assertTrue(ObjectUtil.isEqualOrBothNull(otpCredential.getUserLabel(), otpCredentialLoaded.getUserLabel())); - Assert.assertTrue(ObjectUtil.isEqualOrBothNull(otpCredential.getPriority(), otpCredentialLoaded.getPriority())); + Assertions.assertTrue(ObjectUtil.isEqualOrBothNull(otpCredential.getUserLabel(), otpCredentialLoaded.getUserLabel())); + Assertions.assertTrue(ObjectUtil.isEqualOrBothNull(otpCredential.getPriority(), otpCredentialLoaded.getPriority())); } @Test @@ -1105,12 +1105,12 @@ public void testRespectUsernameFormatFromStorage() { } private void assertOrder(List creds, String... expectedIds) { - org.keycloak.testsuite.Assert.assertEquals(expectedIds.length, creds.size()); + Assertions.assertEquals(expectedIds.length, creds.size()); if (creds.size() == 0) return; for (int i=0 ; i changed=" + changed); - Assert.assertTrue("Assertion failed. newChanged=" + newChanged + ", changed=" + changed, newChanged > (changed + 1)); + Assertions.assertTrue(newChanged > (changed + 1), "Assertion failed. newChanged=" + newChanged + ", changed=" + changed); // Assert that dummy provider won't be invoked anymore sleep(1800); - Assert.assertEquals(full, dummyFedFactory.getFullSyncCounter()); + Assertions.assertEquals(full, dummyFedFactory.getFullSyncCounter()); int newestChanged = dummyFedFactory.getChangedSyncCounter(); - Assert.assertEquals("Assertion failed. newChanged=" + newChanged + ", newestChanged=" + newestChanged, newChanged, newestChanged); + Assertions.assertEquals(newChanged, newestChanged, "Assertion failed. newChanged=" + newChanged + ", newestChanged=" + newestChanged); }); @@ -317,7 +317,7 @@ public void test03ConcurrentSync() { try { SyncDummyUserFederationProviderFactory.latchStarted.await(20000, TimeUnit.MILLISECONDS); SynchronizationResult syncResult = UserStoragePrivateUtil.runPeriodicSync(sessionFactory, dummyModel); - Assert.assertTrue(syncResult.isIgnored()); + Assertions.assertTrue(syncResult.isIgnored()); // Cancel timer StoreSyncEvent.fire(session, appRealm, dummyModel, true); @@ -372,16 +372,16 @@ public void test04IgnoredSync() throws Exception { UserStorageProviderModel dummyModel = findDummyProviderModel(appRealm); KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory(); SynchronizationResult syncResult = UserStoragePrivateUtil.runFullSync(sessionFactory, dummyModel); - Assert.assertTrue(syncResult.isIgnored()); + Assertions.assertTrue(syncResult.isIgnored()); syncResult = UserStoragePrivateUtil.runPeriodicSync(sessionFactory, dummyModel); - Assert.assertTrue(syncResult.isIgnored()); + Assertions.assertTrue(syncResult.isIgnored()); }); // assert the last sync is not updated testingClient.server().run(session -> { RealmModel appRealm = session.realms().getRealmByName(AuthRealm.TEST); UserStorageProviderModel dummyModel = findDummyProviderModel(appRealm); - Assert.assertEquals(0, dummyModel.getLastSync()); + Assertions.assertEquals(0, dummyModel.getLastSync()); }); // remove provider @@ -413,16 +413,16 @@ public void test05LongSync() throws Exception { UserStorageProviderModel dummyModel = findDummyProviderModel(appRealm); KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory(); SynchronizationResult syncResult = UserStoragePrivateUtil.runFullSync(sessionFactory, dummyModel); - Assert.assertTrue(syncResult.isIgnored()); + Assertions.assertTrue(syncResult.isIgnored()); syncResult = UserStoragePrivateUtil.runPeriodicSync(sessionFactory, dummyModel); - Assert.assertTrue(syncResult.isIgnored()); + Assertions.assertTrue(syncResult.isIgnored()); }); // assert the last sync is not updated testingClient.server().run(session -> { RealmModel appRealm = session.realms().getRealmByName(AuthRealm.TEST); UserStorageProviderModel dummyModel = findDummyProviderModel(appRealm); - Assert.assertEquals(0, dummyModel.getLastSync()); + Assertions.assertEquals(0, dummyModel.getLastSync()); }); // remove provider diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AccountConsoleTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AccountConsoleTest.java index 9a2f09581fa3..5bb3598d9267 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AccountConsoleTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AccountConsoleTest.java @@ -5,7 +5,6 @@ import org.keycloak.models.Constants; import org.keycloak.protocol.oidc.OIDCLoginProtocol; import org.keycloak.testsuite.AbstractChangeImportedUserPasswordsTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.arquillian.annotation.IgnoreBrowserDriver; import org.keycloak.testsuite.pages.LoginPage; import org.keycloak.testsuite.util.WaitUtils; @@ -13,6 +12,7 @@ import org.apache.http.client.utils.URIBuilder; import org.jboss.arquillian.graphene.page.Page; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; @@ -28,7 +28,7 @@ public void redirectToLoginIfNotAuthenticated() { driver.navigate().to(getAccount()); WaitUtils.waitForPageToLoad(); loginPage.assertCurrent(); - Assert.assertTrue(driver.getCurrentUrl().contains("client_id=" + Constants.ACCOUNT_CONSOLE_CLIENT_ID)); + Assertions.assertTrue(driver.getCurrentUrl().contains("client_id=" + Constants.ACCOUNT_CONSOLE_CLIENT_ID)); } @Test @@ -40,27 +40,27 @@ public void testScopesPresentInAuthorizationRequest() { driver.navigate().to(redirectLocation); WaitUtils.waitForPageToLoad(); loginPage.login("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertTrue(driver.getPageSource().contains("\"scope\": \"" + expectedScopes + "\"")); + Assertions.assertTrue(driver.getPageSource().contains("\"scope\": \"" + expectedScopes + "\"")); // should render the account with the address scope only expectedScopes = "openid address"; redirectLocation = getAccount(expectedScopes); driver.navigate().to(redirectLocation); WaitUtils.waitForPageToLoad(); - Assert.assertTrue(driver.getPageSource().contains("\"scope\": \"" + expectedScopes + "\"")); + Assertions.assertTrue(driver.getPageSource().contains("\"scope\": \"" + expectedScopes + "\"")); // should render the account with the phone and address scopes expectedScopes = "openid phone address"; redirectLocation = getAccount(expectedScopes); driver.navigate().to(redirectLocation); WaitUtils.waitForPageToLoad(); - Assert.assertTrue(driver.getPageSource().contains("\"scope\": \"" + expectedScopes + "\"")); + Assertions.assertTrue(driver.getPageSource().contains("\"scope\": \"" + expectedScopes + "\"")); // should keep previously requested scopes when not setting the scope parameter redirectLocation = getAccount(); driver.navigate().to(redirectLocation); WaitUtils.waitForPageToLoad(); - Assert.assertTrue(driver.getPageSource().contains("\"scope\": \"" + expectedScopes + "\"")); + Assertions.assertTrue(driver.getPageSource().contains("\"scope\": \"" + expectedScopes + "\"")); } private String getAccount() { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AllowDenyAuthenticatorTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AllowDenyAuthenticatorTest.java index c30e2f9b2d48..5e7313780abf 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AllowDenyAuthenticatorTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AllowDenyAuthenticatorTest.java @@ -30,8 +30,8 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Martin Bartos diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AltSubflowForCredentialResetTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AltSubflowForCredentialResetTest.java index d5acb7bcadf3..028fe5db4960 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AltSubflowForCredentialResetTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AltSubflowForCredentialResetTest.java @@ -39,14 +39,14 @@ import org.keycloak.testsuite.util.UserBuilder; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests setting up alternative reset credentials sub flow to prevent signing in after clicking "forgot password" @@ -119,12 +119,12 @@ public void alternativeSubflowStaySignedOutTest() { try { oauth.openLoginForm(); loginPage.resetPassword(); - Assert.assertTrue(loginPasswordResetPage.isCurrent()); + Assertions.assertTrue(loginPasswordResetPage.isCurrent()); loginPasswordResetPage.changePassword("login@test.com.com"); - Assert.assertTrue(loginPage.isCurrent()); + Assertions.assertTrue(loginPage.isCurrent()); assertEquals("You should receive an email shortly with further instructions.", loginUsernameOnlyPage.getSuccessMessage()); oauth.openLoginForm(); - Assert.assertTrue(loginPage.isCurrent()); + Assertions.assertTrue(loginPage.isCurrent()); } finally { testRealm().flows().getFlows().clear(); RealmRepresentation realm = testRealm().toRepresentation(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AuthenticatorSubflowsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AuthenticatorSubflowsTest.java index 932fd05e8505..93394b7ee371 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AuthenticatorSubflowsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AuthenticatorSubflowsTest.java @@ -37,10 +37,10 @@ import org.keycloak.testsuite.util.UIUtils; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; @@ -278,7 +278,7 @@ public void testSubflow2() throws Exception { // Don't add 'foo' parameter. I am redirected to subflow2 - push the button oauth.loginForm().open(); - Assert.assertEquals("PushTheButton", driver.getTitle()); + Assertions.assertEquals("PushTheButton", driver.getTitle()); // Push the button. I am redirected to username+password form UIUtils.clickLink(driver.findElement(By.name("submit1"))); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AuthenticatorSubflowsTest2.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AuthenticatorSubflowsTest2.java index be97d603200e..3cc98b471c98 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AuthenticatorSubflowsTest2.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/AuthenticatorSubflowsTest2.java @@ -36,10 +36,10 @@ import org.keycloak.testsuite.pages.LoginPage; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; /** @@ -179,7 +179,7 @@ public void testSubflow2() throws Exception { // Fill username+password. I am redirected push the button. oauth.fillLoginForm("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertEquals("PushTheButton", driver.getTitle()); + Assertions.assertEquals("PushTheButton", driver.getTitle()); // Push the button. I am successfully authenticated. driver.findElement(By.name("submit1")).click(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BrowserButtonsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BrowserButtonsTest.java index 6de7c3c24cce..d94dc5b43314 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BrowserButtonsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BrowserButtonsTest.java @@ -48,7 +48,7 @@ import org.junit.Rule; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for browser back/forward/refresh buttons diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BrowserFlowTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BrowserFlowTest.java index 84a5765c7e9a..8000765b1f16 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BrowserFlowTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BrowserFlowTest.java @@ -51,9 +51,9 @@ import org.jboss.arquillian.drone.api.annotation.Drone; import org.jboss.arquillian.graphene.page.Page; import org.jboss.arquillian.test.api.ArquillianResource; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; @@ -131,79 +131,79 @@ private String getOtpCode(String key) { @Test public void testUserWithoutAdditionalFactorConnection() { provideUsernamePassword("test-user@localhost"); - Assert.assertFalse(loginPage.isCurrent()); - Assert.assertFalse(oneTimeCodePage.isOtpLabelPresent()); - Assert.assertFalse(loginTotpPage.isCurrent()); + Assertions.assertFalse(loginPage.isCurrent()); + Assertions.assertFalse(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertFalse(loginTotpPage.isCurrent()); loginTotpPage.assertOtpCredentialSelectorAvailability(false); } @Test public void testUserWithOneAdditionalFactorOtpFails() { provideUsernamePassword("user-with-one-configured-otp"); - Assert.assertTrue(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertTrue(oneTimeCodePage.isOtpLabelPresent()); loginTotpPage.assertCurrent(); loginTotpPage.assertOtpCredentialSelectorAvailability(false); // Use 7 digits instead 6 to have 100% probability of failure oneTimeCodePage.sendCode("1234567"); - Assert.assertEquals(INVALID_AUTH_CODE, oneTimeCodePage.getInputError()); - Assert.assertTrue(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertEquals(INVALID_AUTH_CODE, oneTimeCodePage.getInputError()); + Assertions.assertTrue(oneTimeCodePage.isOtpLabelPresent()); } @Test public void testUserWithOneAdditionalFactorOtpSuccess() { provideUsernamePassword("user-with-one-configured-otp"); - Assert.assertTrue(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertTrue(oneTimeCodePage.isOtpLabelPresent()); loginTotpPage.assertCurrent(); loginTotpPage.assertOtpCredentialSelectorAvailability(false); oneTimeCodePage.sendCode(getOtpCode(USER_WITH_ONE_OTP_OTP_SECRET)); - Assert.assertFalse(loginPage.isCurrent()); - Assert.assertFalse(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertFalse(loginPage.isCurrent()); + Assertions.assertFalse(oneTimeCodePage.isOtpLabelPresent()); } @Test public void testUserWithTwoAdditionalFactors() { // Provide username and password provideUsernamePassword("user-with-two-configured-otp"); - Assert.assertTrue(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertTrue(oneTimeCodePage.isOtpLabelPresent()); loginTotpPage.assertCurrent(); loginTotpPage.assertOtpCredentialSelectorAvailability(true); loginTotpPage.selectOtpCredential("first"); // Check that selected credential is "first" - Assert.assertEquals("first", loginTotpPage.getSelectedOtpCredential()); + Assertions.assertEquals("first", loginTotpPage.getSelectedOtpCredential()); // Select "second" factor (which is unnamed as it doesn't have userLabel) but try to connect with the OTP code from the "first" one loginTotpPage.selectOtpCredential(OTPFormAuthenticator.UNNAMED); loginTotpPage.login(getOtpCode(USER_WITH_TWO_OTPS_OTP1_SECRET)); - Assert.assertEquals(INVALID_AUTH_CODE, oneTimeCodePage.getInputError()); + Assertions.assertEquals(INVALID_AUTH_CODE, oneTimeCodePage.getInputError()); // Select "first" factor but try to connect with the OTP code from the "second" one loginTotpPage.selectOtpCredential("first"); loginTotpPage.login(getOtpCode(USER_WITH_TWO_OTPS_OTP2_SECRET)); - Assert.assertEquals(INVALID_AUTH_CODE, oneTimeCodePage.getInputError()); + Assertions.assertEquals(INVALID_AUTH_CODE, oneTimeCodePage.getInputError()); // Select "second" factor and try to connect with its OTP code loginTotpPage.selectOtpCredential(OTPFormAuthenticator.UNNAMED); loginTotpPage.login(getOtpCode(USER_WITH_TWO_OTPS_OTP2_SECRET)); - Assert.assertFalse(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertFalse(oneTimeCodePage.isOtpLabelPresent()); } private void testCredentialsOrder(String username, List orderedCredentials) { // Provide username and password provideUsernamePassword(username); - Assert.assertTrue(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertTrue(oneTimeCodePage.isOtpLabelPresent()); loginTotpPage.assertCurrent(); loginTotpPage.assertOtpCredentialSelectorAvailability(true); loginTotpPage.selectOtpCredential(orderedCredentials.get(0)); // Check that preferred credential is selected - Assert.assertEquals(orderedCredentials.get(0), loginTotpPage.getSelectedOtpCredential()); + Assertions.assertEquals(orderedCredentials.get(0), loginTotpPage.getSelectedOtpCredential()); // Check credentials order List creds = loginTotpPage.getAvailableOtpCredentials(); - Assert.assertEquals(2, creds.size()); - Assert.assertEquals(orderedCredentials, creds); + Assertions.assertEquals(2, creds.size()); + Assertions.assertEquals(orderedCredentials, creds); } @Test @@ -248,12 +248,12 @@ private boolean needsPassword(String username) { public void testFlowDisabledWhenConditionalAuthenticatorIsMissing() { try { configureBrowserFlowWithConditionalSubFlowHavingConditionalAuthenticator("browser - non missing conditional authenticator", true); - Assert.assertTrue(needsPassword("user-with-two-configured-otp")); + Assertions.assertTrue(needsPassword("user-with-two-configured-otp")); configureBrowserFlowWithConditionalSubFlowHavingConditionalAuthenticator("browser - missing conditional authenticator", false); // Flow is conditional but it is missing a conditional authentication executor // The whole flow is disabled - Assert.assertFalse(needsPassword("user-with-two-configured-otp")); + Assertions.assertFalse(needsPassword("user-with-two-configured-otp")); } finally { revertFlows("browser - non missing conditional authenticator"); } @@ -286,7 +286,7 @@ public void testFlowDisabledWhenConditionalAuthenticatorIsDisabled() { configureBrowserFlowWithConditionalSubFlowHavingDisabledConditionalAuthenticator("browser - disabled conditional authenticator"); // Flow is conditional but it is missing a conditional authentication executor // The whole flow is disabled - Assert.assertFalse(needsPassword("user-with-two-configured-otp")); + Assertions.assertFalse(needsPassword("user-with-two-configured-otp")); } finally { revertFlows("browser - disabled conditional authenticator"); } @@ -365,14 +365,14 @@ public void testConditionalRoleAuthenticator() { try { // user-with-two-configured-otp has been configured with role "user". He should be asked for an OTP code provideUsernamePassword("user-with-two-configured-otp"); - Assert.assertTrue(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertTrue(oneTimeCodePage.isOtpLabelPresent()); loginTotpPage.assertCurrent(); loginTotpPage.assertOtpCredentialSelectorAvailability(true); // user-with-one-configured-otp has not configured role. He should not be asked for an OTP code provideUsernamePassword("user-with-one-configured-otp"); - Assert.assertFalse(oneTimeCodePage.isOtpLabelPresent()); - Assert.assertFalse(loginTotpPage.isCurrent()); + Assertions.assertFalse(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertFalse(loginTotpPage.isCurrent()); } finally { revertFlows("browser - rule"); } @@ -410,14 +410,14 @@ public void testConditionalRoleAuthenticatorWithRealmRoleIncludedInCompositeReal // user-with-two-configured-otp has been configured with role "composite-realm-role-1". // He should be asked for an OTP code provideUsernamePassword("user-with-two-configured-otp"); - Assert.assertTrue(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertTrue(oneTimeCodePage.isOtpLabelPresent()); loginTotpPage.assertCurrent(); loginTotpPage.assertOtpCredentialSelectorAvailability(true); // user-with-one-configured-otp doesn't have the role. He should not be asked for an OTP code provideUsernamePassword("user-with-one-configured-otp"); - Assert.assertFalse(oneTimeCodePage.isOtpLabelPresent()); - Assert.assertFalse(loginTotpPage.isCurrent()); + Assertions.assertFalse(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertFalse(loginTotpPage.isCurrent()); } finally { testRealm().roles().deleteRole(childRealmRoleName); testRealm().roles().deleteRole(compositeRealmRoleName); @@ -460,14 +460,14 @@ public void testConditionalRoleAuthenticatorWithClientRoleIncludedInCompositeCli try { // user-with-two-configured-otp has been configured with role "test-app.child-client-role-1". He should be asked for an OTP code provideUsernamePassword("user-with-two-configured-otp"); - Assert.assertTrue(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertTrue(oneTimeCodePage.isOtpLabelPresent()); loginTotpPage.assertCurrent(); loginTotpPage.assertOtpCredentialSelectorAvailability(true); // user-with-one-configured-otp doesn't have the role. He should not be asked for an OTP code provideUsernamePassword("user-with-one-configured-otp"); - Assert.assertFalse(oneTimeCodePage.isOtpLabelPresent()); - Assert.assertFalse(loginTotpPage.isCurrent()); + Assertions.assertFalse(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertFalse(loginTotpPage.isCurrent()); } finally { testRealm().clients().get(testClient.getId()).roles().deleteRole(childClientRoleName); testRealm().clients().get(testClient.getId()).roles().deleteRole(compositeClientRoleName); @@ -527,7 +527,7 @@ public void testConditionalAuthenticatorWithConditionalSubFlowWithChangingCondit passwordPage.assertCurrent(); passwordPage.login(getPassword("user-with-two-configured-otp")); - Assert.assertTrue(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertTrue(oneTimeCodePage.isOtpLabelPresent()); } finally { revertFlows("browser - changing condition"); } @@ -710,12 +710,12 @@ public void testConditionalFlowWithConditionalAuthenticatorEvaluatingToTrueActsA loginUsernameOnlyPage.login("user-with-one-configured-otp"); // Assert on password page now - Assert.assertTrue(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertTrue(oneTimeCodePage.isOtpLabelPresent()); loginTotpPage.assertCurrent(); loginTotpPage.assertOtpCredentialSelectorAvailability(false); loginTotpPage.login(getOtpCode(USER_WITH_ONE_OTP_OTP_SECRET)); - Assert.assertFalse(loginTotpPage.isCurrent()); + Assertions.assertFalse(loginTotpPage.isCurrent()); events.expectLogin().user(testRealm().users().search("user-with-one-configured-otp").get(0).getId()) .detail(Details.USERNAME, "user-with-one-configured-otp").assertEvent(); @@ -776,12 +776,12 @@ public void testConditionalFlowWithMultipleConditionalAuthenticatorsWithUserWith .assertEvent(); // Assert on otp page now - Assert.assertTrue(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertTrue(oneTimeCodePage.isOtpLabelPresent()); loginTotpPage.assertCurrent(); loginTotpPage.assertOtpCredentialSelectorAvailability(true); loginTotpPage.login(getOtpCode(USER_WITH_TWO_OTPS_OTP1_SECRET)); - Assert.assertFalse(loginTotpPage.isCurrent()); + Assertions.assertFalse(loginTotpPage.isCurrent()); events.expectLogin().user(userId).detail(Details.USERNAME, "user-with-two-configured-otp").assertEvent(); } finally { revertFlows("browser - copy 1"); @@ -806,8 +806,8 @@ public void testConditionalFlowWithMultipleConditionalAuthenticatorsWithUserWith .removeDetail(Details.CONSENT) .assertEvent(); // Assert not on otp page now - Assert.assertFalse(oneTimeCodePage.isOtpLabelPresent()); - Assert.assertFalse(loginTotpPage.isCurrent()); + Assertions.assertFalse(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertFalse(loginTotpPage.isCurrent()); events.expectLogin().user(userId).detail(Details.USERNAME, "user-with-one-configured-otp").assertEvent(); } finally { @@ -918,7 +918,7 @@ public void testLoginWithWithNoOTPCredential(){ provideUsernamePassword("test-user@localhost"); // Assert that in this case you arrive to an OTP setup - Assert.assertTrue(driver.getCurrentUrl().contains("required-action?execution=CONFIGURE_TOTP")); + Assertions.assertTrue(driver.getCurrentUrl().contains("required-action?execution=CONFIGURE_TOTP")); } finally { revertFlows("browser - copy 1"); @@ -985,7 +985,7 @@ public void testLoginWithWithNoWebAuthnCredential(){ provideUsernamePassword("test-user@localhost"); // Assert that in this case you arrive to an webauthn setup - Assert.assertTrue(driver.getCurrentUrl().contains("required-action?execution=" + WebAuthnRegisterFactory.PROVIDER_ID)); + Assertions.assertTrue(driver.getCurrentUrl().contains("required-action?execution=" + WebAuthnRegisterFactory.PROVIDER_ID)); } finally { revertFlows("browser - copy 1"); UserRepresentation user = testRealm().users().search("test-user@localhost").get(0); @@ -1042,19 +1042,19 @@ public void testLoginWithWithNoOTPCredentialAndAlternativeActionProvider(){ @Test public void testLoginWithWrongCredentialsMessage() { UserRepresentation user = testRealm().users().search("test-user@localhost").get(0); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); oauth.openLoginForm(); loginPage.assertCurrent(); loginPage.login(user.getUsername(), getPassword("test-user@localhost") + "wrong_password"); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); events.clear(); loginPage.assertCurrent(); loginPage.login(user.getUsername(), getPassword("test-user@localhost")); - Assert.assertFalse(loginPage.isCurrent()); + Assertions.assertFalse(loginPage.isCurrent()); events.expectLogin() .user(user) .detail(Details.USERNAME, "test-user@localhost") @@ -1068,7 +1068,7 @@ public void testLoginWithWrongCredentialsMessage() { public void testLoginMultiFactorWithWrongCredentialsMessage() { UserRepresentation user = testRealm().users().search("test-user@localhost").get(0); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); MultiFactorAuthenticationTest.configureBrowserFlowWithAlternativeCredentials(testingClient); try { @@ -1079,28 +1079,28 @@ public void testLoginMultiFactorWithWrongCredentialsMessage() { oauth.openLoginForm(); loginUsernameOnlyPage.assertCurrent(); loginUsernameOnlyPage.login("non_existing_user"); - Assert.assertEquals("Invalid username.", loginUsernameOnlyPage.getUsernameError()); - Assert.assertEquals("Invalid username.", loginUsernameOnlyPage.getUsernameError()); + Assertions.assertEquals("Invalid username.", loginUsernameOnlyPage.getUsernameError()); + Assertions.assertEquals("Invalid username.", loginUsernameOnlyPage.getUsernameError()); realm.setLoginWithEmailAllowed(true); testRealm().update(realm); loginUsernameOnlyPage.login("non_existing_user"); - Assert.assertEquals("Invalid username or email.", loginUsernameOnlyPage.getUsernameError()); - Assert.assertEquals("Invalid username or email.", loginUsernameOnlyPage.getUsernameError()); + Assertions.assertEquals("Invalid username or email.", loginUsernameOnlyPage.getUsernameError()); + Assertions.assertEquals("Invalid username or email.", loginUsernameOnlyPage.getUsernameError()); loginUsernameOnlyPage.login(user.getUsername()); passwordPage.assertCurrent(); passwordPage.login("wrong_password"); - Assert.assertEquals("Invalid password.", passwordPage.getPasswordError()); - Assert.assertEquals("Invalid password.", passwordPage.getPasswordError()); + Assertions.assertEquals("Invalid password.", passwordPage.getPasswordError()); + Assertions.assertEquals("Invalid password.", passwordPage.getPasswordError()); passwordPage.assertCurrent(); events.clear(); passwordPage.login(getPassword(user.getUsername())); - Assert.assertFalse(loginUsernameOnlyPage.isCurrent()); - Assert.assertFalse(passwordPage.isCurrent()); + Assertions.assertFalse(loginUsernameOnlyPage.isCurrent()); + Assertions.assertFalse(passwordPage.isCurrent()); events.expectLogin() .user(user) @@ -1189,8 +1189,8 @@ public void testLoginWithAlternativeOTPAndConditionalPassword(){ passwordPage.assertTryAnotherWayLinkAvailability(true); passwordPage.login(getPassword("user-with-one-configured-otp")); - Assert.assertFalse(loginPage.isCurrent()); - Assert.assertFalse(oneTimeCodePage.isOtpLabelPresent()); + Assertions.assertFalse(loginPage.isCurrent()); + Assertions.assertFalse(oneTimeCodePage.isOtpLabelPresent()); events.expectLogin().user(testRealm().users().search("user-with-one-configured-otp").get(0).getId()) .detail(Details.USERNAME, "user-with-one-configured-otp").assertEvent(); } finally { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BruteForceTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BruteForceTest.java index cae5af4787e4..9f72e3a9c8e7 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BruteForceTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BruteForceTest.java @@ -65,17 +65,17 @@ import org.hamcrest.MatcherAssert; import org.jboss.arquillian.graphene.page.Page; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stian Thorgersen @@ -264,33 +264,33 @@ public void testGrantInvalidPassword() { { String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), totpSecret); - Assert.assertNotNull(response.getAccessToken()); - Assert.assertNull(response.getError()); + Assertions.assertNotNull(response.getAccessToken()); + Assertions.assertNull(response.getError()); events.clear(); } { String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken("invalid" + getPassword("test-user@localhost"), totpSecret); - Assert.assertNull(response.getAccessToken()); - Assert.assertEquals(response.getError(), "invalid_grant"); - Assert.assertEquals(response.getErrorDescription(), "Invalid user credentials"); + Assertions.assertNull(response.getAccessToken()); + Assertions.assertEquals(response.getError(), "invalid_grant"); + Assertions.assertEquals(response.getErrorDescription(), "Invalid user credentials"); events.clear(); } { String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken("invalid" + getPassword("test-user@localhost"), totpSecret); - Assert.assertNull(response.getAccessToken()); - Assert.assertEquals(response.getError(), "invalid_grant"); - Assert.assertEquals(response.getErrorDescription(), "Invalid user credentials"); + Assertions.assertNull(response.getAccessToken()); + Assertions.assertEquals(response.getError(), "invalid_grant"); + Assertions.assertEquals(response.getErrorDescription(), "Invalid user credentials"); events.clear(); } { String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), totpSecret); - Assert.assertNull(response.getAccessToken()); - Assert.assertNotNull(response.getError()); - Assert.assertEquals("invalid_grant", response.getError()); - Assert.assertEquals("Invalid user credentials", response.getErrorDescription()); + Assertions.assertNull(response.getAccessToken()); + Assertions.assertNotNull(response.getError()); + Assertions.assertEquals("invalid_grant", response.getError()); + Assertions.assertEquals("Invalid user credentials", response.getErrorDescription()); assertUserDisabledEvent(Errors.USER_TEMPORARILY_DISABLED); events.clear(); } @@ -298,8 +298,8 @@ public void testGrantInvalidPassword() { { String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), totpSecret); - Assert.assertNotNull(response.getAccessToken()); - Assert.assertNull(response.getError()); + Assertions.assertNotNull(response.getAccessToken()); + Assertions.assertNull(response.getError()); events.clear(); } @@ -310,31 +310,31 @@ public void testGrantInvalidOtp() { { String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), totpSecret); - Assert.assertNotNull(response.getAccessToken()); - Assert.assertNull(response.getError()); + Assertions.assertNotNull(response.getAccessToken()); + Assertions.assertNull(response.getError()); events.clear(); } { AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), "shite"); - Assert.assertNull(response.getAccessToken()); - Assert.assertEquals(response.getError(), "invalid_grant"); - Assert.assertEquals(response.getErrorDescription(), "Invalid user credentials"); + Assertions.assertNull(response.getAccessToken()); + Assertions.assertEquals(response.getError(), "invalid_grant"); + Assertions.assertEquals(response.getErrorDescription(), "Invalid user credentials"); events.clear(); } { AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), "shite"); - Assert.assertNull(response.getAccessToken()); - Assert.assertEquals(response.getError(), "invalid_grant"); - Assert.assertEquals(response.getErrorDescription(), "Invalid user credentials"); + Assertions.assertNull(response.getAccessToken()); + Assertions.assertEquals(response.getError(), "invalid_grant"); + Assertions.assertEquals(response.getErrorDescription(), "Invalid user credentials"); events.clear(); } { String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), totpSecret); assertTokenNull(response); - Assert.assertNotNull(response.getError()); - Assert.assertEquals(response.getError(), "invalid_grant"); - Assert.assertEquals("Invalid user credentials", response.getErrorDescription()); + Assertions.assertNotNull(response.getError()); + Assertions.assertEquals(response.getError(), "invalid_grant"); + Assertions.assertEquals("Invalid user credentials", response.getErrorDescription()); assertUserDisabledEvent(Errors.USER_TEMPORARILY_DISABLED); events.clear(); } @@ -342,15 +342,15 @@ public void testGrantInvalidOtp() { { String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), totpSecret); - Assert.assertNotNull(response.getAccessToken()); - Assert.assertNull(response.getError()); + Assertions.assertNotNull(response.getAccessToken()); + Assertions.assertNull(response.getError()); events.clear(); } } public void assertTokenNull(AccessTokenResponse response) { - Assert.assertNull(response.getAccessToken()); + Assertions.assertNull(response.getAccessToken()); } @Test @@ -358,31 +358,31 @@ public void testGrantMissingOtp() { { String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), totpSecret); - Assert.assertNotNull(response.getAccessToken()); - Assert.assertNull(response.getError()); + Assertions.assertNotNull(response.getAccessToken()); + Assertions.assertNull(response.getError()); events.clear(); } { AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), null); - Assert.assertNull(response.getAccessToken()); - Assert.assertEquals(response.getError(), "invalid_grant"); - Assert.assertEquals(response.getErrorDescription(), "Invalid user credentials"); + Assertions.assertNull(response.getAccessToken()); + Assertions.assertEquals(response.getError(), "invalid_grant"); + Assertions.assertEquals(response.getErrorDescription(), "Invalid user credentials"); events.clear(); } { AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), null); - Assert.assertNull(response.getAccessToken()); - Assert.assertEquals(response.getError(), "invalid_grant"); - Assert.assertEquals(response.getErrorDescription(), "Invalid user credentials"); + Assertions.assertNull(response.getAccessToken()); + Assertions.assertEquals(response.getError(), "invalid_grant"); + Assertions.assertEquals(response.getErrorDescription(), "Invalid user credentials"); events.clear(); } { String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), totpSecret); assertTokenNull(response); - Assert.assertNotNull(response.getError()); - Assert.assertEquals(response.getError(), "invalid_grant"); - Assert.assertEquals("Invalid user credentials", response.getErrorDescription()); + Assertions.assertNotNull(response.getError()); + Assertions.assertEquals(response.getError(), "invalid_grant"); + Assertions.assertEquals("Invalid user credentials", response.getErrorDescription()); assertUserDisabledEvent(Errors.USER_TEMPORARILY_DISABLED); events.clear(); } @@ -390,8 +390,8 @@ public void testGrantMissingOtp() { { String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), totpSecret); - Assert.assertNotNull(response.getAccessToken()); - Assert.assertNull(response.getError()); + Assertions.assertNotNull(response.getAccessToken()); + Assertions.assertNull(response.getError()); events.clear(); } @@ -404,28 +404,28 @@ public void testGrantPermamentOtpAbsolut() throws Exception { .setQuickLoginCheckMilliSeconds(0L) // allow fail OTP .update()) { // assert that brute force is checking for secondary auth failures - Assert.assertTrue(testRealm().toRepresentation().getMaxSecondaryAuthFailures() > 0); + Assertions.assertTrue(testRealm().toRepresentation().getMaxSecondaryAuthFailures() > 0); { // successful login String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), totpSecret); - Assert.assertNotNull(response.getAccessToken()); - Assert.assertNull(response.getError()); + Assertions.assertNotNull(response.getAccessToken()); + Assertions.assertNull(response.getError()); events.clear(); } for (int i = 0; i <= testRealm().toRepresentation().getMaxSecondaryAuthFailures(); i++) { AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), null); - Assert.assertNull(response.getAccessToken()); - Assert.assertEquals("invalid_grant", response.getError()); - Assert.assertEquals("Invalid user credentials", response.getErrorDescription()); + Assertions.assertNull(response.getAccessToken()); + Assertions.assertEquals("invalid_grant", response.getError()); + Assertions.assertEquals("Invalid user credentials", response.getErrorDescription()); events.clear(); } { String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), totpSecret); assertTokenNull(response); - Assert.assertNotNull(response.getError()); - Assert.assertEquals("invalid_grant", response.getError()); - Assert.assertEquals("Invalid user credentials", response.getErrorDescription()); + Assertions.assertNotNull(response.getError()); + Assertions.assertEquals("invalid_grant", response.getError()); + Assertions.assertEquals("Invalid user credentials", response.getErrorDescription()); assertUserDisabledReason(BruteForceProtector.DISABLED_BY_PERMANENT_LOCKOUT); } @@ -447,9 +447,9 @@ public void testNumberOfFailuresForDisabledUsersWithPasswordGrantType() { // Wrong password on disabled user should return "Invalid user credentials" (not reveal disabled status) AccessTokenResponse response = getTestToken("invalid", "invalid"); - Assert.assertNull(response.getAccessToken()); - Assert.assertEquals(response.getError(), "invalid_grant"); - Assert.assertEquals(response.getErrorDescription(), "Invalid user credentials"); + Assertions.assertNull(response.getAccessToken()); + Assertions.assertEquals(response.getError(), "invalid_grant"); + Assertions.assertEquals(response.getErrorDescription(), "Invalid user credentials"); events.clear(); assertUserNumberOfFailures(user.getId(), 0); @@ -457,9 +457,9 @@ public void testNumberOfFailuresForDisabledUsersWithPasswordGrantType() { // Correct password on disabled user should return "Account disabled" String totpSecret = totp.generateTOTP("totpSecret"); response = getTestToken(getPassword("test-user@localhost"), totpSecret); - Assert.assertNull(response.getAccessToken()); - Assert.assertEquals(response.getError(), "invalid_grant"); - Assert.assertEquals(response.getErrorDescription(), "Account disabled"); + Assertions.assertNull(response.getAccessToken()); + Assertions.assertEquals(response.getError(), "invalid_grant"); + Assertions.assertEquals(response.getErrorDescription(), "Account disabled"); events.clear(); assertUserNumberOfFailures(user.getId(), 0); @@ -566,7 +566,7 @@ public void testCacheExpiryForTemporaryLockout() { RealmModel realmModel = session.realms().getRealm(realmId); UserModel userModel = session.users().getUserByEmail(realmModel, "test-user@localhost"); UserLoginFailureModel userLoginFailure = session.loginFailures().getUserLoginFailure(realmModel, userModel.getId()); - Assert.assertNull("cache entry should have expired", userLoginFailure); + Assertions.assertNull(userLoginFailure, "cache entry should have expired"); }); } @@ -782,7 +782,7 @@ public void testBrowserInvalidTotp() { @Test public void testBrowserInvalidTotpAbsolut() { // assert that brute force is checking for secondary auth failures - Assert.assertTrue(testRealm().toRepresentation().getMaxSecondaryAuthFailures() > 0); + Assertions.assertTrue(testRealm().toRepresentation().getMaxSecondaryAuthFailures() > 0); loginWithTotpFailure(); for (int i = 0; i < testRealm().toRepresentation().getMaxSecondaryAuthFailures(); i++ ) { continueLoginWithInvalidTotp(); @@ -810,13 +810,13 @@ public void testBrowserTotpSessionInvalidAfterLockout() { } private void checkEmailPresent(String subject) { - Assert.assertFalse("No email with subject: " + subject, Arrays.stream(greenMail.getReceivedMessages()).filter(m -> { + Assertions.assertFalse(Arrays.stream(greenMail.getReceivedMessages()).filter(m -> { try { return subject.equals(m.getSubject()); } catch (MessagingException ex) { return false; } - }).findAny().isEmpty()); + }).findAny().isEmpty(), "No email with subject: " + subject); } @Test @@ -998,17 +998,17 @@ public void testResetLoginFailureCount() { public void testFailureCountResetWithPasswordGrantType() { String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken("invalid", totpSecret); - Assert.assertNull(response.getAccessToken()); - Assert.assertEquals(response.getError(), "invalid_grant"); - Assert.assertEquals(response.getErrorDescription(), "Invalid user credentials"); + Assertions.assertNull(response.getAccessToken()); + Assertions.assertEquals(response.getError(), "invalid_grant"); + Assertions.assertEquals(response.getErrorDescription(), "Invalid user credentials"); UserRepresentation user = adminClient.realm("test").users().search("test-user@localhost", 0, 1).get(0); Map userAttackInfo = adminClient.realm("test").attackDetection().bruteForceUserStatus(user.getId()); assertThat((Integer) userAttackInfo.get("numFailures"), is(1)); response = getTestToken(getPassword("test-user@localhost"), totpSecret); - Assert.assertNotNull(response.getAccessToken()); - Assert.assertNull(response.getError()); + Assertions.assertNotNull(response.getAccessToken()); + Assertions.assertNull(response.getError()); events.clear(); userAttackInfo = adminClient.realm("test").attackDetection().bruteForceUserStatus(user.getId()); @@ -1067,7 +1067,7 @@ public void testResetPassword() throws Exception { bruteForceStatus = testRealm().attackDetection().bruteForceUserStatus(userId); assertEquals(Boolean.FALSE, bruteForceStatus.get("disabled")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); String code = oauth.parseLoginResponse().getCode(); String idTokenHint = oauth.doAccessTokenRequest(code).getIdToken(); @@ -1091,7 +1091,7 @@ public void testRaceAttackTemporaryLockout() throws Exception { testRealm().users().get(user.getId()).update(user); String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), totpSecret); - Assert.assertNotNull(response.getAccessToken()); + Assertions.assertNotNull(response.getAccessToken()); raceAttack(user); } finally { realm.setWaitIncrementSeconds(5); @@ -1117,7 +1117,7 @@ public void testRaceAttackPermanentLockout() throws Exception { testRealm().users().get(user.getId()).update(user); String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), totpSecret); - Assert.assertNotNull(response.getAccessToken()); + Assertions.assertNotNull(response.getAccessToken()); } finally { realm.setPermanentLockout(false); testRealm().update(realm); @@ -1139,7 +1139,7 @@ private void raceAttack(UserRepresentation user) throws Exception { threads[i].join(); } int invalidCount = (int) adminClient.realm("test").attackDetection().bruteForceUserStatus(user.getId()).get("numFailures"); - assertTrue("Invalid count should be less than or equal 3 but was: " + invalidCount, invalidCount <= 3); + assertTrue(invalidCount <= 3, "Invalid count should be less than or equal 3 but was: " + invalidCount); } public class LoginThread extends Thread { @@ -1148,9 +1148,9 @@ public void run() { try { String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken("invalid", totpSecret); - Assert.assertNull(response.getAccessToken()); - Assert.assertEquals(response.getError(), "invalid_grant"); - Assert.assertEquals(response.getErrorDescription(), "Invalid user credentials"); + Assertions.assertNull(response.getAccessToken()); + Assertions.assertEquals(response.getError(), "invalid_grant"); + Assertions.assertEquals(response.getErrorDescription(), "Invalid user credentials"); } catch (Exception ex) { ex.printStackTrace(); } @@ -1170,7 +1170,7 @@ public void expectTemporarilyDisabled(String username, String userId, String pas loginPage.login(username, password); loginPage.assertCurrent(); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); ExpectedEvent event = events.expectLogin() .session((String) null) .error(Errors.USER_TEMPORARILY_DISABLED) @@ -1191,7 +1191,7 @@ public void expectPermanentlyDisabled(String username) { loginPage.login(username, getPassword(username)); loginPage.assertCurrent(); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); ExpectedEvent event = events.expectLogin() .session((String) null) .error(Errors.USER_DISABLED) @@ -1219,7 +1219,7 @@ public void loginSuccess(String username) { String totpSecret = totp.generateTOTP("totpSecret"); loginTotpPage.login(totpSecret); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().assertEvent(); @@ -1237,7 +1237,7 @@ public void loginWithTotpFailure() { loginTotpPage.login("123456"); loginTotpPage.assertCurrent(); - Assert.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); + Assertions.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); events.clear(); } @@ -1247,7 +1247,7 @@ public void continueLoginWithTotp() { String totpSecret = totp.generateTOTP("totpSecret"); loginTotpPage.login(totpSecret); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().assertEvent(); String code = oauth.parseLoginResponse().getCode(); @@ -1263,7 +1263,7 @@ public void continueLoginWithCorrectTotpExpectFailure() { loginTotpPage.login(totpSecret); loginTotpPage.assertCurrent(); - Assert.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); + Assertions.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); events.clear(); } @@ -1274,7 +1274,7 @@ public void continueLoginWithInvalidTotp() { loginTotpPage.login("123456"); loginTotpPage.assertCurrent(); - Assert.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); + Assertions.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); } public void continueLoginWithMissingTotp() { @@ -1283,7 +1283,7 @@ public void continueLoginWithMissingTotp() { loginTotpPage.login(null); loginTotpPage.assertCurrent(); - Assert.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); + Assertions.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); events.clear(); } @@ -1295,7 +1295,7 @@ public void loginWithMissingTotp() { loginTotpPage.login(null); loginTotpPage.assertCurrent(); - Assert.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); + Assertions.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); events.clear(); } @@ -1314,7 +1314,7 @@ public void loginInvalidPassword(String username, boolean clearEventsQueue) { loginPage.assertCurrent(); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); if (clearEventsQueue) { events.clear(); @@ -1327,7 +1327,7 @@ public void loginMissingPassword() { loginPage.assertCurrent(); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); events.clear(); } @@ -1339,7 +1339,7 @@ public void registerUser(String username) { final String password = generatePassword("user"); registerPage.register("user", "name", username + "@localhost", username, password, password); - Assert.assertNull(registerPage.getInstruction()); + Assertions.assertNull(registerPage.getInstruction()); events.clear(); } @@ -1368,17 +1368,17 @@ private void assertUserNumberOfFailures(String userId, Integer numberOfFailures) private void sendInvalidPasswordPasswordGrant() { String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken("invalid", totpSecret); - Assert.assertNull(response.getAccessToken()); - Assert.assertEquals(response.getError(), "invalid_grant"); - Assert.assertEquals(response.getErrorDescription(), "Invalid user credentials"); + Assertions.assertNull(response.getAccessToken()); + Assertions.assertEquals(response.getError(), "invalid_grant"); + Assertions.assertEquals(response.getErrorDescription(), "Invalid user credentials"); events.clear(); } private void lockUserWithPasswordGrant() { String totpSecret = totp.generateTOTP("totpSecret"); AccessTokenResponse response = getTestToken(getPassword("test-user@localhost"), totpSecret); - Assert.assertNotNull(response.getAccessToken()); - Assert.assertNull(response.getError()); + Assertions.assertNotNull(response.getAccessToken()); + Assertions.assertNull(response.getError()); events.clear(); for (int i = 0; i < failureFactor; ++i) { @@ -1406,6 +1406,6 @@ public void assertIsContained(ExpectedEvent expectedEvent, ListStian Thorgersen @@ -240,7 +240,7 @@ public void testRequiredAfterAlternative() { rep.setBrowserFlow(flowAlias); testRealm().update(rep); rep = testRealm().toRepresentation(); - Assert.assertEquals(flowAlias, rep.getBrowserFlow()); + Assertions.assertEquals(flowAlias, rep.getBrowserFlow()); } @@ -250,7 +250,7 @@ public void testRequiredAfterAlternative() { loginPage.login("test-user@localhost", "bad-password"); Assert.assertTrue(loginPage.isCurrent()); loginPage.login("test-user@localhost", "password");*/ - Assert.assertTrue(termsPage.isCurrent()); + Assertions.assertTrue(termsPage.isCurrent()); // Revert dummy flow rep.setBrowserFlow("dummy"); @@ -307,8 +307,8 @@ public void loginSuccess() { oauth.openLoginForm(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent(); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/CustomRegistrationFlowTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/CustomRegistrationFlowTest.java index 4952ce7461fd..3eafc695c85b 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/CustomRegistrationFlowTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/CustomRegistrationFlowTest.java @@ -31,10 +31,10 @@ import org.keycloak.testsuite.util.FlowBuilder; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @author Stian Thorgersen @@ -96,7 +96,7 @@ public void registerUserSuccess() { oauth.openLoginForm(); loginPage.clickRegister(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); String userId = events.expectRegister(PassThroughRegistration.username, PassThroughRegistration.email).assertEvent().getUserId(); events.expectLogin().detail("username", PassThroughRegistration.username).user(userId).assertEvent(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/DirectGrantFlowTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/DirectGrantFlowTest.java index 87636dc9260d..dd02381bf43d 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/DirectGrantFlowTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/DirectGrantFlowTest.java @@ -41,7 +41,7 @@ import org.junit.Test; import org.openqa.selenium.WebDriver; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test of custom configurations of DirectGrant flow (Resource Owner Password Credentials Grant) diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/FlowOverrideTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/FlowOverrideTest.java index 49d873794862..1f3a98cb7404 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/FlowOverrideTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/FlowOverrideTest.java @@ -60,13 +60,13 @@ import org.keycloak.util.BasicAuthHelper; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test that clients can override auth flows @@ -204,7 +204,7 @@ public void testWithClientBrowserOverride() throws Exception { oauth.clientId(TEST_APP_FLOW); oauth.openLoginForm(); - Assert.assertEquals("PushTheButton", driver.getTitle()); + Assertions.assertEquals("PushTheButton", driver.getTitle()); // Push the button. I am redirected to username+password form UIUtils.clickLink(driver.findElement(By.name("submit1"))); @@ -338,7 +338,7 @@ public void testRestInterface() throws Exception { List query = clients.findByClientId(TEST_APP_DIRECT_OVERRIDE); ClientRepresentation clientRep = query.get(0); String directGrantFlowId = clientRep.getAuthenticationFlowBindingOverrides().get(AuthenticationFlowBindings.DIRECT_GRANT_BINDING); - Assert.assertNotNull(directGrantFlowId); + Assertions.assertNotNull(directGrantFlowId); clientRep.getAuthenticationFlowBindingOverrides().put(AuthenticationFlowBindings.DIRECT_GRANT_BINDING, ""); clients.get(clientRep.getId()).update(clientRep); testDirectGrantNoOverride(TEST_APP_DIRECT_OVERRIDE); @@ -349,7 +349,7 @@ public void testRestInterface() throws Exception { query = clients.findByClientId(TEST_APP_FLOW); clientRep = query.get(0); String browserFlowId = clientRep.getAuthenticationFlowBindingOverrides().get(AuthenticationFlowBindings.BROWSER_BINDING); - Assert.assertNotNull(browserFlowId); + Assertions.assertNotNull(browserFlowId); clientRep.getAuthenticationFlowBindingOverrides().put(AuthenticationFlowBindings.BROWSER_BINDING, ""); clients.get(clientRep.getId()).update(clientRep); testNoOverrideBrowser(TEST_APP_FLOW); @@ -369,19 +369,19 @@ public void testRestInterfaceWithBadId() throws Exception { clientRep.getAuthenticationFlowBindingOverrides().put(AuthenticationFlowBindings.BROWSER_BINDING, "bad-id"); try { clients.get(clientRep.getId()).update(clientRep); - Assert.fail(); + Assertions.fail(); } catch (Exception e) { } query = clients.findByClientId(TEST_APP_FLOW); clientRep = query.get(0); - Assert.assertEquals(browserFlowId, clientRep.getAuthenticationFlowBindingOverrides().get(AuthenticationFlowBindings.BROWSER_BINDING)); + Assertions.assertEquals(browserFlowId, clientRep.getAuthenticationFlowBindingOverrides().get(AuthenticationFlowBindings.BROWSER_BINDING)); } private void testWithRemovedFlowOverrideByClient(String binding, Consumer testNoOverride) { ClientResource clientResource = AdminApiUtil.findClientByClientId(testRealm(), "test-app"); - Assert.assertNotNull(clientResource); + Assertions.assertNotNull(clientResource); ClientRepresentation clientRep = clientResource.toRepresentation(); String newFlowAlias = "Copy of Browser Flow"; diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/HiddenProviderTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/HiddenProviderTest.java index 7a9bbf53890a..3650cfb61118 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/HiddenProviderTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/HiddenProviderTest.java @@ -23,8 +23,8 @@ import org.keycloak.testsuite.util.IdentityProviderBuilder; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; public class HiddenProviderTest extends AbstractTestRealmKeycloakTest { @@ -54,12 +54,12 @@ public void configureTestRealm(RealmRepresentation testRealm) { @Test public void testVisibleProviderButton() { oauth.openLoginForm(); - Assert.assertNotNull(loginPage.findSocialButton("visible-oidc")); + Assertions.assertNotNull(loginPage.findSocialButton("visible-oidc")); } @Test(expected=org.openqa.selenium.NoSuchElementException.class) public void testHiddenProviderButton() { oauth.openLoginForm(); - Assert.assertNull(loginPage.findSocialButton("hidden-oidc")); + Assertions.assertNull(loginPage.findSocialButton("hidden-oidc")); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LevelOfAssuranceFlowTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LevelOfAssuranceFlowTest.java index 76dbc0800814..3d83c61b5949 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LevelOfAssuranceFlowTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LevelOfAssuranceFlowTest.java @@ -94,6 +94,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.actions.AppInitiatedActionDeleteCredentialTest.getKcActionParamForDeleteCredential; @@ -170,7 +171,7 @@ public void beforeTest() { .totpSecret("totpSecret") .otpEnabled(); Response response = testRealm().users().create(userRep); - Assert.assertEquals(201, response.getStatus()); + Assertions.assertEquals(201, response.getStatus()); response.close(); } @@ -532,7 +533,7 @@ public void testClientDefaultAcrValuesValidation() throws IOException { OIDCAdvancedConfigWrapper.fromClientRepresentation(testClientRep).setAttributeMultivalued(Constants.DEFAULT_ACR_VALUES, Arrays.asList("silver", "2", "foo")); try { testClient.update(testClientRep); - Assert.fail("Should not successfully update client"); + Assertions.fail("Should not successfully update client"); } catch (BadRequestException bre) { // Expected } @@ -541,7 +542,7 @@ public void testClientDefaultAcrValuesValidation() throws IOException { OIDCAdvancedConfigWrapper.fromClientRepresentation(testClientRep).setAttributeMultivalued(Constants.DEFAULT_ACR_VALUES, Arrays.asList("silver", "2", "5")); try { testClient.update(testClientRep); - Assert.fail("Should not successfully update client"); + Assertions.fail("Should not successfully update client"); } catch (BadRequestException bre) { // Expected } @@ -571,13 +572,13 @@ public void testClientMinimumAcrValueValidation() throws IOException { ClientResource testClient = AdminApiUtil.findClientByClientId(testRealm(), CLIENT_ID); ClientRepresentation testClientRep = testClient.toRepresentation(); OIDCAdvancedConfigWrapper.fromClientRepresentation(testClientRep).setMinimumAcrValue("foo"); - Assert.assertThrows(BadRequestException.class, () -> { + Assertions.assertThrows(BadRequestException.class, () -> { testClient.update(testClientRep); }); // Realm value should not be considered either OIDCAdvancedConfigWrapper.fromClientRepresentation(testClientRep).setMinimumAcrValue("realm:silver"); - Assert.assertThrows(BadRequestException.class, () -> { + Assertions.assertThrows(BadRequestException.class, () -> { testClient.update(testClientRep); }); @@ -835,7 +836,7 @@ public void testWithMultipleOTPCodes() throws Exception { .build()) { otpCredentialId = accountRestClient.getCredentialByUserLabel("totp2-label").getId(); try (SimpleHttpResponse response = accountRestClient.removeCredential(otpCredentialId)) { - Assert.assertEquals(403, response.getStatus()); + Assertions.assertEquals(403, response.getStatus()); } } @@ -846,9 +847,9 @@ public void testWithMultipleOTPCodes() throws Exception { .build()) { otpCredentialId = accountRestClient.getCredentialByUserLabel("totp2-label").getId(); try (SimpleHttpResponse response = accountRestClient.removeCredential(otpCredentialId)) { - Assert.assertEquals(204, response.getStatus()); + Assertions.assertEquals(204, response.getStatus()); } - Assert.assertNull(accountRestClient.getCredentialByUserLabel("totp2-label")); + Assertions.assertNull(accountRestClient.getCredentialByUserLabel("totp2-label")); } } @@ -928,7 +929,7 @@ public void testWithOTPAndRecoveryCodesAtLevel2() { // Trying to delete existing OTP. Should require authentication with this OTP String otpCredentialId = getCredentialIdByType(OTPCredentialModel.TYPE); oauth.loginForm().kcAction(getKcActionParamForDeleteCredential(otpCredentialId)).open(); - Assert.assertEquals("Strong authentication required to continue", loginPage.getInfoMessage()); + Assertions.assertEquals("Strong authentication required to continue", loginPage.getInfoMessage()); authenticateWithTotp(); deleteCredentialPage.assertCurrent(); @@ -965,7 +966,7 @@ public void testWithOTPAndRecoveryCodesAtLevel2() { loginTotpPage.assertCurrent(); loginTotpPage.clickTryAnotherWayLink(); selectAuthenticatorPage.assertCurrent(); - Assert.assertEquals(Arrays.asList(SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION, SelectAuthenticatorPage.RECOVERY_AUTHN_CODES), selectAuthenticatorPage.getAvailableLoginMethods()); + Assertions.assertEquals(Arrays.asList(SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION, SelectAuthenticatorPage.RECOVERY_AUTHN_CODES), selectAuthenticatorPage.getAvailableLoginMethods()); selectAuthenticatorPage.selectLoginMethod(SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION); loginTotpPage.assertCurrent(); loginTotpPage.login(totp.generateTOTP(totp2Secret)); @@ -1157,7 +1158,7 @@ private void authenticateWithUsernamePassword() { private void reauthenticateWithPassword() { WaitUtils.waitUntilPageIsCurrent(loginPage); loginPage.assertCurrent(); - Assert.assertEquals("test-user@localhost", loginPage.getAttemptedUsername()); + Assertions.assertEquals("test-user@localhost", loginPage.getAttemptedUsername()); loginPage.login(getPassword("test-user@localhost")); } @@ -1177,13 +1178,13 @@ private TokenCtx assertLoggedInWithAcr(String acr) { EventRepresentation loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent(); AccessTokenResponse tokenResponse = sendTokenRequestAndGetResponse(loginEvent); IDToken idToken = oauth.verifyIDToken(tokenResponse.getIdToken()); - Assert.assertEquals(acr, idToken.getAcr()); + Assertions.assertEquals(acr, idToken.getAcr()); return new TokenCtx(tokenResponse.getAccessToken(), idToken); } private void assertErrorPage(String expectedError) { assertThat(true, is(errorPage.isCurrent())); - Assert.assertEquals(expectedError, errorPage.getError()); + Assertions.assertEquals(expectedError, errorPage.getError()); events.clear(); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginHotpTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginHotpTest.java index 93872475bb70..23d912ac655c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginHotpTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginHotpTest.java @@ -35,10 +35,10 @@ import org.keycloak.testsuite.util.UserBuilder; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @author Stian Thorgersen @@ -102,11 +102,11 @@ public void loginWithHotpFailure() throws Exception { oauth.openLoginForm(); loginPage.login("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertTrue(loginTotpPage.isCurrent()); + Assertions.assertTrue(loginTotpPage.isCurrent()); loginTotpPage.login("123456"); loginTotpPage.assertCurrent(); - Assert.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); + Assertions.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); //loginPage.assertCurrent(); // Invalid authenticator code. //Assert.assertEquals("Invalid username or password.", loginPage.getError()); @@ -121,11 +121,11 @@ public void loginWithMissingHotp() throws Exception { oauth.openLoginForm(); loginPage.login("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertTrue(loginTotpPage.isCurrent()); + Assertions.assertTrue(loginTotpPage.isCurrent()); loginTotpPage.login(null); loginTotpPage.assertCurrent(); - Assert.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); + Assertions.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); //loginPage.assertCurrent(); // Invalid authenticator code. //Assert.assertEquals("Invalid username or password.", loginPage.getError()); @@ -140,13 +140,13 @@ public void loginWithHotpSuccess() throws Exception { oauth.openLoginForm(); loginPage.login("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertTrue("expecting totpPage got: " + driver.getCurrentUrl(), loginTotpPage.isCurrent()); + Assertions.assertTrue(loginTotpPage.isCurrent(), "expecting totpPage got: " + driver.getCurrentUrl()); loginTotpPage.login(otp.generateHOTP("hotpSecret", counter++)); appPage.assertCurrent(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().assertEvent(); } @@ -156,9 +156,9 @@ public void loginWithHotpInvalidPassword() throws Exception { oauth.openLoginForm(); loginPage.login("test-user@localhost", "invalid"); - Assert.assertTrue(loginPage.isCurrent()); + Assertions.assertTrue(loginPage.isCurrent()); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); events.expectLogin().error("invalid_user_credentials").session((String) null) .removeDetail(Details.CONSENT) diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTest.java index f48a96a48970..0eebd7cec46f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTest.java @@ -78,9 +78,9 @@ import org.apache.commons.lang3.RandomStringUtils; import org.hamcrest.MatcherAssert; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.Cookie; import org.openqa.selenium.JavascriptExecutor; @@ -93,12 +93,12 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stian Thorgersen @@ -180,7 +180,7 @@ public void testBrowserSecurityHeaders() { if (expectedValue.isEmpty()) { assertNull(headerValue); } else { - Assert.assertNotNull(headerValue); + Assertions.assertNotNull(headerValue); assertThat(headerValue, is(equalTo(expectedValue))); } } @@ -256,10 +256,10 @@ public void loginChangeUserAfterInvalidPassword() { loginPage.assertCurrent(); - Assert.assertEquals("login-test2", loginPage.getUsername()); - Assert.assertEquals("", loginPage.getPassword()); + Assertions.assertEquals("login-test2", loginPage.getUsername()); + Assertions.assertEquals("", loginPage.getPassword()); - Assert.assertEquals("Invalid username or password.", loginPage.getUsernameInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getUsernameInputError()); assertNull(loginPage.getPasswordInputError()); events.expectLogin().user(user2Id).session((String) null).error("invalid_user_credentials") @@ -269,8 +269,8 @@ public void loginChangeUserAfterInvalidPassword() { loginPage.login("login-test", getPassword("login-test")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent(); } @@ -283,10 +283,10 @@ public void loginInvalidPassword() { loginPage.assertCurrent(); // KEYCLOAK-1741 - assert form field values kept - Assert.assertEquals("login-test", loginPage.getUsername()); - Assert.assertEquals("", loginPage.getPassword()); + Assertions.assertEquals("login-test", loginPage.getUsername()); + Assertions.assertEquals("", loginPage.getPassword()); - Assert.assertEquals("Invalid username or password.", loginPage.getUsernameInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getUsernameInputError()); assertNull(loginPage.getPasswordInputError()); events.expectLogin().user(userId).session((String) null).error("invalid_user_credentials") @@ -303,10 +303,10 @@ public void loginMissingPassword() { loginPage.assertCurrent(); // KEYCLOAK-1741 - assert form field values kept - Assert.assertEquals("login-test", loginPage.getUsername()); - Assert.assertEquals("", loginPage.getPassword()); + Assertions.assertEquals("login-test", loginPage.getUsername()); + Assertions.assertEquals("", loginPage.getPassword()); - Assert.assertEquals("Invalid username or password.", loginPage.getUsernameInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getUsernameInputError()); assertNull(loginPage.getPasswordInputError()); events.expectLogin().user(userId).session((String) null).error("invalid_user_credentials") @@ -332,11 +332,11 @@ public void loginInvalidPasswordDisabledUser() { loginPage.assertCurrent(); // KEYCLOAK-1741 - assert form field values kept - Assert.assertEquals("login-test", loginPage.getUsername()); - Assert.assertEquals("", loginPage.getPassword()); + Assertions.assertEquals("login-test", loginPage.getUsername()); + Assertions.assertEquals("", loginPage.getPassword()); // KEYCLOAK-2024 - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); events.expectLogin().user(userId).session((String) null).error("invalid_user_credentials") .detail(Details.USERNAME, "login-test") @@ -358,11 +358,11 @@ public void loginDisabledUser() { loginPage.assertCurrent(); // KEYCLOAK-1741 - assert form field values kept - Assert.assertEquals("login-test", loginPage.getUsername()); - Assert.assertEquals("", loginPage.getPassword()); + Assertions.assertEquals("login-test", loginPage.getUsername()); + Assertions.assertEquals("", loginPage.getPassword()); // KEYCLOAK-2024 - Assert.assertEquals("Account is disabled, contact your administrator.", loginPage.getError()); + Assertions.assertEquals("Account is disabled, contact your administrator.", loginPage.getError()); events.expectLogin().user(userId).session((String) null).error("user_disabled") .detail(Details.USERNAME, "login-test") @@ -406,10 +406,10 @@ public void loginInvalidUsername() { loginPage.assertCurrent(); // KEYCLOAK-1741 - assert form field values kept - Assert.assertEquals("invalid", loginPage.getUsername()); - Assert.assertEquals("", loginPage.getPassword()); + Assertions.assertEquals("invalid", loginPage.getUsername()); + Assertions.assertEquals("", loginPage.getPassword()); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); events.expectLogin().user((String) null).session((String) null).error("user_not_found") .detail(Details.USERNAME, "invalid") @@ -418,8 +418,8 @@ public void loginInvalidUsername() { loginPage.login("login-test", getPassword("login-test")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent(); } @@ -431,7 +431,7 @@ public void loginMissingUsername() { loginPage.assertCurrent(); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); events.expectLogin().user((String) null).session((String) null).error("user_not_found") .removeDetail(Details.CONSENT) @@ -444,8 +444,8 @@ public void loginUserWithEmailAsUsername() { oauth.openLoginForm(); loginPage.login("login@test.com", getPassword("login-test")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); events.expectLogin().user(userId).detail(Details.USERNAME, "login@test.com").assertEvent(); } @@ -455,8 +455,8 @@ public void loginSuccess() { oauth.openLoginForm(); loginPage.login("login-test", getPassword("login-test")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent(); } @@ -468,8 +468,8 @@ public void loginSuccessRealmSigningAlgorithms() throws JWSInputException { oauth.openLoginForm(); loginPage.login("login-test", getPassword("login-test")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent(); @@ -484,7 +484,7 @@ public void loginSuccessRealmSigningAlgorithms() throws JWSInputException { TokenSignatureUtil.changeRealmTokenSignatureProvider(adminClient, Algorithm.ES256); oauth.openLoginForm(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); driver.navigate().to(getAuthServerContextRoot() + "/auth/realms/test/"); keycloakIdentity = driver.manage().getCookieNamed("KEYCLOAK_IDENTITY").getValue(); @@ -495,7 +495,7 @@ public void loginSuccessRealmSigningAlgorithms() throws JWSInputException { // Check identity cookie still works oauth.openLoginForm(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); } finally { TokenSignatureUtil.changeRealmTokenSignatureProvider(adminClient, Algorithm.RS256); } @@ -506,8 +506,8 @@ public void loginWithWhitespaceSuccess() { oauth.openLoginForm(); loginPage.login(" login-test \t ", getPassword("login-test")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent(); } @@ -517,8 +517,8 @@ public void loginWithEmailWhitespaceSuccess() { oauth.openLoginForm(); loginPage.login(" login@test.com ", getPassword("login-test")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); events.expectLogin().user(userId).assertEvent(); } @@ -554,7 +554,7 @@ public void loginWithForcePasswordChangePolicy() { String currentUrl = driver.getCurrentUrl(); String pageSource = driver.getPageSource(); - assertEquals("bad expectation, on page: " + currentUrl, RequestType.AUTH_RESPONSE, appPage.getRequestType()); + assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType(), "bad expectation, on page: " + currentUrl); events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent(); @@ -576,8 +576,8 @@ public void loginWithoutForcePasswordChangePolicy() { loginPage.login("login-test", getPassword("login-test")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); setTimeOffset(0); @@ -604,11 +604,11 @@ public void loginNoTimeoutWithLongWait() { public void loginLoginHint() { oauth.loginForm().param("login_hint", "login-test").open(); - Assert.assertEquals("login-test", loginPage.getUsername()); + Assertions.assertEquals("login-test", loginPage.getUsername()); loginPage.login(getPassword("login-test")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent(); } @@ -618,8 +618,8 @@ public void loginWithEmailSuccess() { oauth.openLoginForm(); loginPage.login("login@test.com", getPassword("login-test")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); events.expectLogin().user(userId).assertEvent(); } @@ -647,8 +647,8 @@ public void loginWithRememberMe() { assertTrue(loginPage.isRememberMeChecked()); loginPage.login("login-test", getPassword("login-test")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); EventRepresentation loginEvent = events.expectLogin().user(userId) .detail(Details.USERNAME, "login-test") .detail(Details.REMEMBER_ME, "true") @@ -661,7 +661,7 @@ public void loginWithRememberMe() { // Assert rememberMe checked and username/email prefilled oauth.openLoginForm(); assertTrue(loginPage.isRememberMeChecked()); - Assert.assertEquals("login-test", loginPage.getUsername()); + Assertions.assertEquals("login-test", loginPage.getUsername()); loginPage.setRememberMe(false); } finally { @@ -685,8 +685,8 @@ public void loginWithRememberMeNotSet() { loginPage.setRememberMe(true); loginPage.login("login-test", getPassword("login-test")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); EventRepresentation loginEvent = events.expectLogin().user(userId) .detail(Details.USERNAME, "login-test") .assertEvent(); @@ -707,8 +707,8 @@ public void loginAgainWithoutRememberMe() { assertTrue(loginPage.isRememberMeChecked()); loginPage.login("login-test", getPassword("login-test")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); EventRepresentation loginEvent = events.expectLogin().user(userId) .detail(Details.USERNAME, "login-test") .detail(Details.REMEMBER_ME, "true") @@ -721,7 +721,7 @@ public void loginAgainWithoutRememberMe() { // Assert rememberMe checked and username/email prefilled oauth.openLoginForm(); assertTrue(loginPage.isRememberMeChecked()); - Assert.assertEquals("login-test", loginPage.getUsername()); + Assertions.assertEquals("login-test", loginPage.getUsername()); //login without remember me loginPage.setRememberMe(false); @@ -754,8 +754,8 @@ public void loginWithEmailUserAndRememberMe() { assertTrue(loginPage.isRememberMeChecked()); loginPage.login("login@test.com", getPassword("login-test")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); EventRepresentation loginEvent = events.expectLogin().user(userId) .detail(Details.USERNAME, "login@test.com") .detail(Details.REMEMBER_ME, "true") @@ -769,7 +769,7 @@ public void loginWithEmailUserAndRememberMe() { oauth.openLoginForm(); assertTrue(loginPage.isRememberMeChecked()); - Assert.assertEquals("login@test.com", loginPage.getUsername()); + Assertions.assertEquals("login@test.com", loginPage.getUsername()); loginPage.setRememberMe(false); } finally { @@ -788,8 +788,8 @@ public void testLoginAfterDisablingRememberMeInRealmSettings() { assertTrue(loginPage.isRememberMeChecked()); loginPage.login("login@test.com", getPassword("login-test")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); events.expectLogin().user(userId) .detail(Details.USERNAME, "login@test.com") .detail(Details.REMEMBER_ME, "true") @@ -825,7 +825,7 @@ public void loginExpiredCode() { loginPage.login("login@test.com", getPassword("login-test")); loginPage.assertCurrent(); - Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); + Assertions.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); setTimeOffset(0); events.expectLogin().user((String) null).session((String) null).error(Errors.EXPIRED_CODE).clearDetails() @@ -842,7 +842,7 @@ public void loginExpiredCodeWithExplicitRemoveExpired() { loginPage.assertCurrent(); - Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); + Assertions.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); setTimeOffset(0); @@ -887,7 +887,7 @@ public void loginExpiredCodeAndExpiredCookies() { String link = errorPage.getBackToApplicationLink(); ClientRepresentation thirdParty = findClientByClientId(adminClient.realm("test"), "third-party").toRepresentation(); - Assert.assertNotNull(link, thirdParty.getBaseUrl()); + Assertions.assertNotNull(thirdParty.getBaseUrl(), link); } @Test @@ -967,7 +967,7 @@ public void openLoginFormAfterExpiredCode() throws Exception { oauth.openLoginForm(); loginPage.assertCurrent(); - assertNull("Not expected to have error on loginForm.", loginPage.getError()); + assertNull(loginPage.getError(), "Not expected to have error on loginForm."); loginPage.login("test-user@localhost", getPassword("test-user@localhost")); appPage.assertCurrent(); @@ -983,17 +983,17 @@ public void testAuthenticationSessionExpiresEarlyAfterAuthentication() throws Ex // Assert authenticationSession in cache with 2 tabs String authSessionId = driver.manage().getCookieNamed(CookieType.AUTH_SESSION_ID.getName()).getValue(); - Assert.assertEquals((Integer) 2, getTestingClient().testing().getAuthenticationSessionTabsCount("test", authSessionId)); + Assertions.assertEquals((Integer) 2, getTestingClient().testing().getAuthenticationSessionTabsCount("test", authSessionId)); loginPage.login("test-user@localhost", getPassword("test-user@localhost")); appPage.assertCurrent(); // authentication session should still exists with remaining browser tab - Assert.assertEquals((Integer) 1, getTestingClient().testing().getAuthenticationSessionTabsCount("test", authSessionId)); + Assertions.assertEquals((Integer) 1, getTestingClient().testing().getAuthenticationSessionTabsCount("test", authSessionId)); // authentication session should be expired after 1 minute setTimeOffset(300); - Assert.assertEquals((Integer) 0, getTestingClient().testing().getAuthenticationSessionTabsCount("test", authSessionId)); + Assertions.assertEquals((Integer) 0, getTestingClient().testing().getAuthenticationSessionTabsCount("test", authSessionId)); } @@ -1086,7 +1086,7 @@ public void loginSuccessfulWithoutWebAuthn() { try { oauth.openLoginForm(); loginPage.login("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().assertEvent(); } finally { testingClient.enableFeature(Profile.Feature.WEB_AUTHN); @@ -1097,7 +1097,7 @@ public void loginSuccessfulWithoutWebAuthn() { public void testExecuteActionIfSessionExists() { oauth.openLoginForm(); loginPage.login("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().assertEvent(); UsersResource users = adminClient.realm("test").users(); @@ -1131,15 +1131,15 @@ public void testAuthSessionIdCookieFormat(){ oauth.openLoginForm(); String encodedBase64AuthSessionId = driver.manage().getCookieNamed(CookieType.AUTH_SESSION_ID.getName()).getValue(); String decodedAuthSessionId = new String(Base64Url.decode(encodedBase64AuthSessionId), StandardCharsets.UTF_8); - Assert.assertTrue(decodedAuthSessionId.contains(".")); + Assertions.assertTrue(decodedAuthSessionId.contains(".")); String authSessionId = decodedAuthSessionId.substring(0, decodedAuthSessionId.indexOf(".")); String signature = decodedAuthSessionId.substring(decodedAuthSessionId.indexOf(".") + 1); - Assert.assertNotNull(authSessionId); + Assertions.assertNotNull(authSessionId); MatcherAssert.assertThat(authSessionId, AssertEvents.isSessionId()); - Assert.assertNotNull(signature); + Assertions.assertNotNull(signature); testingClient.server().run(session-> { - Assert.assertNotNull(session.authenticationSessions().getRootAuthenticationSession(session.getContext().getRealm(), authSessionId)); + Assertions.assertNotNull(session.authenticationSessions().getRootAuthenticationSession(session.getContext().getRealm(), authSessionId)); }); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTotpTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTotpTest.java index 860ec09a55e0..c01f6443ed92 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTotpTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTotpTest.java @@ -54,10 +54,10 @@ import org.keycloak.util.JsonSerialization; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.auth.page.AuthRealm.TEST; @@ -105,11 +105,11 @@ public void loginWithTotpFailure() throws Exception { oauth.openLoginForm(); loginPage.login("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertTrue(loginTotpPage.isCurrent()); + Assertions.assertTrue(loginTotpPage.isCurrent()); loginTotpPage.login("123456"); loginTotpPage.assertCurrent(); - Assert.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); + Assertions.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); //loginPage.assertCurrent(); // Invalid authenticator code. //Assert.assertEquals("Invalid username or password.", loginPage.getError()); @@ -124,11 +124,11 @@ public void loginWithMissingTotp() throws Exception { oauth.openLoginForm(); loginPage.login("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertTrue(loginTotpPage.isCurrent()); + Assertions.assertTrue(loginTotpPage.isCurrent()); loginTotpPage.login(null); loginTotpPage.assertCurrent(); - Assert.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); + Assertions.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); //loginPage.assertCurrent(); // Invalid authenticator code. //Assert.assertEquals("Invalid username or password.", loginPage.getError()); @@ -143,13 +143,13 @@ public void loginWithTotpSuccess() throws Exception { oauth.openLoginForm(); loginPage.login("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertTrue(loginTotpPage.isCurrent()); + Assertions.assertTrue(loginTotpPage.isCurrent()); setOtpTimeOffset(TimeBasedOTP.DEFAULT_INTERVAL_SECONDS, totp); loginTotpPage.login(totp.generateTOTP("totpSecret")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().assertEvent(); } @@ -160,7 +160,7 @@ public void loginWithTotpRefreshTotpPage() throws Exception { oauth.openLoginForm(); loginPage.login("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertTrue(loginTotpPage.isCurrent()); + Assertions.assertTrue(loginTotpPage.isCurrent()); // Refresh TOTP page driver.navigate().refresh(); @@ -169,7 +169,7 @@ public void loginWithTotpRefreshTotpPage() throws Exception { loginTotpPage.login(totp.generateTOTP("totpSecret")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().assertEvent(); } @@ -179,9 +179,9 @@ public void loginWithTotpInvalidPassword() throws Exception { oauth.openLoginForm(); loginPage.login("test-user@localhost", "invalid"); - Assert.assertTrue(loginPage.isCurrent()); + Assertions.assertTrue(loginPage.isCurrent()); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); events.expectLogin().error("invalid_user_credentials").session((String) null) .removeDetail(Details.CONSENT) @@ -198,11 +198,11 @@ public void loginWithTotp_testAttemptedUsernameAndResetLogin() throws Exception loginPage.login("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertTrue(loginTotpPage.isCurrent()); + Assertions.assertTrue(loginTotpPage.isCurrent()); // Assert attempted-username available loginPage.assertAttemptedUsernameAvailability(true); - Assert.assertEquals("test-user@localhost", loginPage.getAttemptedUsername()); + Assertions.assertEquals("test-user@localhost", loginPage.getAttemptedUsername()); // Reset login and assert back on the login screen loginTotpPage.clickResetLogin(); @@ -230,13 +230,13 @@ public void loginWithTotp_getToken_checkCompatibilityCLI() throws IOException { Response response = exchangeUrl.request() .post(Entity.form(form.param("otp", totp.generateTOTP("totpSecret")))); - Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); response.close(); response = exchangeUrl.request() .post(Entity.form(form.param("totp", totp.generateTOTP("totpSecret")))); - Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); response.close(); } finally { @@ -253,7 +253,7 @@ public void testBase32EncodedSecret() throws IOException { .filter(c -> OTPCredentialModel.TYPE.equals(c.getType())) .findAny().orElse(null); - Assert.assertNotNull(otpCredential); + Assertions.assertNotNull(otpCredential); OTPCredentialData credentialData = JsonSerialization.readValue(otpCredential.getCredentialData(), OTPCredentialData.class); OTPCredentialData newCredentialData = new OTPCredentialData(credentialData.getSubType(), credentialData.getDigits(), credentialData.getCounter(), credentialData.getPeriod(), credentialData.getAlgorithm(), @@ -277,12 +277,12 @@ public void testBase32EncodedSecret() throws IOException { oauth.openLoginForm(); loginPage.login(newUser.getUsername(), getPassword("test-otp-user@localhost")); - Assert.assertTrue(loginTotpPage.isCurrent()); + Assertions.assertTrue(loginTotpPage.isCurrent()); setOtpTimeOffset(TimeBasedOTP.DEFAULT_INTERVAL_SECONDS, totp); loginTotpPage.login(totp.generateTOTP(Base32.decode(rawSecret))); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/MultiFactorAuthenticationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/MultiFactorAuthenticationTest.java index d159b62fe93e..f47724c4359d 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/MultiFactorAuthenticationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/MultiFactorAuthenticationTest.java @@ -46,9 +46,9 @@ import org.jboss.arquillian.drone.api.annotation.Drone; import org.jboss.arquillian.graphene.page.Page; import org.jboss.arquillian.test.api.ArquillianResource; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebDriver; /** @@ -108,11 +108,11 @@ public void testAlternativeCredentials() { passwordPage.clickTryAnotherWayLink(); selectAuthenticatorPage.assertCurrent(); - Assert.assertEquals(Arrays.asList(SelectAuthenticatorPage.PASSWORD, SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION), selectAuthenticatorPage.getAvailableLoginMethods()); + Assertions.assertEquals(Arrays.asList(SelectAuthenticatorPage.PASSWORD, SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION), selectAuthenticatorPage.getAvailableLoginMethods()); // Assert help texts - Assert.assertEquals("Sign in by entering your password.", selectAuthenticatorPage.getLoginMethodHelpText(SelectAuthenticatorPage.PASSWORD)); - Assert.assertEquals("Enter a verification code from authenticator application.", selectAuthenticatorPage.getLoginMethodHelpText(SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION)); + Assertions.assertEquals("Sign in by entering your password.", selectAuthenticatorPage.getLoginMethodHelpText(SelectAuthenticatorPage.PASSWORD)); + Assertions.assertEquals("Enter a verification code from authenticator application.", selectAuthenticatorPage.getLoginMethodHelpText(SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION)); // Select OTP and see that just single OTP is available for this user selectAuthenticatorPage.selectLoginMethod(SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION); @@ -133,7 +133,7 @@ public void testAlternativeCredentials() { loginTotpPage.clickTryAnotherWayLink(); selectAuthenticatorPage.assertCurrent(); - Assert.assertEquals(Arrays.asList(SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION, SelectAuthenticatorPage.PASSWORD), selectAuthenticatorPage.getAvailableLoginMethods()); + Assertions.assertEquals(Arrays.asList(SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION, SelectAuthenticatorPage.PASSWORD), selectAuthenticatorPage.getAvailableLoginMethods()); } finally { BrowserFlowTest.revertFlows(testRealm(), "browser - alternative"); } @@ -152,17 +152,17 @@ public void testChangingLocaleOnAuthenticationSelectorScreen() { passwordPage.clickTryAnotherWayLink(); selectAuthenticatorPage.assertCurrent(); - Assert.assertEquals(Arrays.asList(SelectAuthenticatorPage.PASSWORD, SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION), selectAuthenticatorPage.getAvailableLoginMethods()); + Assertions.assertEquals(Arrays.asList(SelectAuthenticatorPage.PASSWORD, SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION), selectAuthenticatorPage.getAvailableLoginMethods()); // Switch locale. Should be still on "selectAuthenticatorPage" selectAuthenticatorPage.openLanguage("Deutsch"); selectAuthenticatorPage.assertCurrent(); - Assert.assertEquals(Arrays.asList("Passwort", "Authenticator-Anwendung"), selectAuthenticatorPage.getAvailableLoginMethods()); + Assertions.assertEquals(Arrays.asList("Passwort", "Authenticator-Anwendung"), selectAuthenticatorPage.getAvailableLoginMethods()); // Change language back selectAuthenticatorPage.openLanguage("English"); selectAuthenticatorPage.assertCurrent(); - Assert.assertEquals(Arrays.asList(SelectAuthenticatorPage.PASSWORD, SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION), selectAuthenticatorPage.getAvailableLoginMethods()); + Assertions.assertEquals(Arrays.asList(SelectAuthenticatorPage.PASSWORD, SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION), selectAuthenticatorPage.getAvailableLoginMethods()); } finally { BrowserFlowTest.revertFlows(testRealm(), "browser - alternative"); } @@ -221,7 +221,7 @@ public void testAlternativeMechanismsInDifferentSubflows() { // Click "Try another way" . Ability to have both password and OTP should be possible even if OTP is in different subflow passwordPage.clickTryAnotherWayLink(); selectAuthenticatorPage.assertCurrent(); - Assert.assertEquals(Arrays.asList(SelectAuthenticatorPage.PASSWORD, SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION), selectAuthenticatorPage.getAvailableLoginMethods()); + Assertions.assertEquals(Arrays.asList(SelectAuthenticatorPage.PASSWORD, SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION), selectAuthenticatorPage.getAvailableLoginMethods()); selectAuthenticatorPage.selectLoginMethod(SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION); // Should be on the OTP now. Click "Try another way" again. Should see again both Password and OTP @@ -230,14 +230,14 @@ public void testAlternativeMechanismsInDifferentSubflows() { loginTotpPage.clickTryAnotherWayLink(); selectAuthenticatorPage.assertCurrent(); - Assert.assertEquals(Arrays.asList(SelectAuthenticatorPage.PASSWORD, SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION), selectAuthenticatorPage.getAvailableLoginMethods()); + Assertions.assertEquals(Arrays.asList(SelectAuthenticatorPage.PASSWORD, SelectAuthenticatorPage.AUTHENTICATOR_APPLICATION), selectAuthenticatorPage.getAvailableLoginMethods()); selectAuthenticatorPage.selectLoginMethod(SelectAuthenticatorPage.PASSWORD); passwordPage.assertCurrent(); passwordPage.login(getPassword("user-with-one-configured-otp")); - Assert.assertFalse(passwordPage.isCurrent()); - Assert.assertFalse(loginPage.isCurrent()); + Assertions.assertFalse(passwordPage.isCurrent()); + Assertions.assertFalse(loginPage.isCurrent()); events.expectLogin().user(testRealm().users().search("user-with-one-configured-otp").get(0).getId()) .detail(Details.USERNAME, "user-with-one-configured-otp").assertEvent(); } finally { @@ -283,7 +283,7 @@ public void testAlternativeMechanismsInDifferentSubflows_firstMechanismUnavailab // Successfully login with OTP loginTotpPage.login(new TimeBasedOTP().generateTOTP("DJmQfC73VGFhw7D4QJ8A")); - Assert.assertFalse(loginTotpPage.isCurrent()); + Assertions.assertFalse(loginTotpPage.isCurrent()); events.expectLogin().user(testRealm().users().search("user-with-one-configured-otp").get(0).getId()) .detail(Details.USERNAME, "user-with-one-configured-otp").assertEvent(); } finally { @@ -309,13 +309,13 @@ public void testUsernameLabelAndResetLogin() { // On the password page, username should be shown as we know the user passwordPage.assertCurrent(); passwordPage.assertAttemptedUsernameAvailability(true); - Assert.assertEquals("user-with-one-configured-otp", passwordPage.getAttemptedUsername()); + Assertions.assertEquals("user-with-one-configured-otp", passwordPage.getAttemptedUsername()); passwordPage.clickTryAnotherWayLink(); // On the select-authenticator page, username should be shown as we know the user selectAuthenticatorPage.assertCurrent(); selectAuthenticatorPage.assertAttemptedUsernameAvailability(true); - Assert.assertEquals("user-with-one-configured-otp", passwordPage.getAttemptedUsername()); + Assertions.assertEquals("user-with-one-configured-otp", passwordPage.getAttemptedUsername()); // Reset login selectAuthenticatorPage.clickResetLogin(); @@ -336,7 +336,7 @@ public void testUsernameLabelAndResetLogin() { // On the password page, the email of user should be shown passwordPage.assertCurrent(); passwordPage.assertAttemptedUsernameAvailability(true); - Assert.assertEquals("otp1@redhat.com", passwordPage.getAttemptedUsername()); + Assertions.assertEquals("otp1@redhat.com", passwordPage.getAttemptedUsername()); // Login passwordPage.login(getPassword("user-with-one-configured-otp")); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/MultipleTabsLoginTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/MultipleTabsLoginTest.java index 9882f02b03de..040cf2aa8d3f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/MultipleTabsLoginTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/MultipleTabsLoginTest.java @@ -45,7 +45,6 @@ import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.testsuite.AbstractChangeImportedUserPasswordsTest; import org.keycloak.testsuite.ActionURIUtils; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.pages.AppPage; @@ -84,6 +83,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import static org.keycloak.models.Constants.CLIENT_DATA; @@ -215,7 +215,7 @@ public void testWithAuthSessionExpiredInTheMiddle_badRedirectUri() throws Except // Simulate incorrect login attempt to make sure that URL is on LoginActionsService URL loginPage.login("invalid", "invalid"); String loginUrl = driver.getCurrentUrl(); - Assert.assertTrue(UriUtils.decodeQueryString(new URL(loginUrl).getQuery()).containsKey(CLIENT_DATA)); + Assertions.assertTrue(UriUtils.decodeQueryString(new URL(loginUrl).getQuery()).containsKey(CLIENT_DATA)); getLogger().info("URL in tab1: " + driver.getCurrentUrl()); oauth.openLoginForm(); @@ -226,7 +226,7 @@ public void testWithAuthSessionExpiredInTheMiddle_badRedirectUri() throws Except loginPage.login("login-test", getPassword("login-test")); loginPage.assertCurrent(); - Assert.assertEquals(loginPage.getError(), "Your login attempt timed out. Login will start from the beginning."); + Assertions.assertEquals(loginPage.getError(), "Your login attempt timed out. Login will start from the beginning."); events.clear(); loginSuccessAndDoRequiredActions(); @@ -243,7 +243,7 @@ public void testWithAuthSessionExpiredInTheMiddle_badRedirectUri() throws Except driver.navigate().to(loginUrl); errorPage.assertCurrent(); - Assert.assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); + Assertions.assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); events.expectLogin().user((String) null).session((String) null) .error(Errors.INVALID_REDIRECT_URI) @@ -274,7 +274,7 @@ private void multipleTabsParallelLogin(BrowserTabUtil tabUtil) { // Try to login in tab2. After fill login form, the login will be restarted (due KC_RESTART cookie). User can continue login loginPage.login("login-test", getPassword("login-test")); loginPage.assertCurrent(); - Assert.assertEquals(loginPage.getError(), "Your login attempt timed out. Login will start from the beginning."); + Assertions.assertEquals(loginPage.getError(), "Your login attempt timed out. Login will start from the beginning."); events.clear(); loginSuccessAndDoRequiredActions(); @@ -316,8 +316,8 @@ private void assertOnAppPageWithAlreadyLoggedInError(EventType expectedEventType .assertEvent(true); appPage.assertCurrent(); // Page "You are already logged in." should not be here AuthorizationEndpointResponse authzResponse = oauth.parseLoginResponse(); - Assert.assertEquals(OAuthErrorException.TEMPORARILY_UNAVAILABLE, authzResponse.getError()); - Assert.assertEquals(Constants.AUTHENTICATION_EXPIRED_MESSAGE, authzResponse.getErrorDescription()); + Assertions.assertEquals(OAuthErrorException.TEMPORARILY_UNAVAILABLE, authzResponse.getError()); + Assertions.assertEquals(Constants.AUTHENTICATION_EXPIRED_MESSAGE, authzResponse.getErrorDescription()); } @Test @@ -366,7 +366,7 @@ public void multipleTabsParallelLoginTestWithAuthSessionExpiredAndRequiredAction // Try to login in tab2. After fill login form, the login will be restarted (due KC_RESTART cookie). User can continue login loginPage.login("login-test", getPassword("login-test")); loginPage.assertCurrent(); - Assert.assertEquals(loginPage.getError(), "Your login attempt timed out. Login will start from the beginning."); + Assertions.assertEquals(loginPage.getError(), "Your login attempt timed out. Login will start from the beginning."); loginSuccessAndDoRequiredActions(); @@ -405,7 +405,7 @@ public void multipleTabsParallelLoginTestWithAuthSessionExpiredAndRefreshInTab1( // Try to login in tab2. After fill login form, the login will be restarted (due KC_RESTART cookie). User can continue login loginPage.login("login-test", getPassword("login-test")); loginPage.assertCurrent(); - Assert.assertEquals(loginPage.getError(), "Your login attempt timed out. Login will start from the beginning."); + Assertions.assertEquals(loginPage.getError(), "Your login attempt timed out. Login will start from the beginning."); loginSuccessAndDoRequiredActions(); @@ -509,12 +509,12 @@ public void expiredAuthenticationAction_expiredCodeCurrentExecution() { loginPage.login("invalid", "invalid"); loginPage.assertCurrent(); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); // Simulate going back to tab1 and confirm login form. Login page with "action expired" message should be shown (NOTE: WebDriver does it with GET, when real browser would do it with POST. Improve test if needed...) driver.navigate().to(actionUrl1); loginPage.assertCurrent(); - Assert.assertEquals("Action expired. Please continue with login now.", loginPage.getError()); + Assertions.assertEquals("Action expired. Please continue with login now.", loginPage.getError()); // Login success now loginSuccessAndDoRequiredActions(); @@ -635,7 +635,7 @@ public void loginWithSameClientDifferentStatesLoginInTab1() throws Exception { appPage.assertCurrent(); String currentUrl = driver.getCurrentUrl(); assertCurrentUrlStartsWith(redirectUri1); - Assert.assertTrue(currentUrl.contains("state1")); + Assertions.assertTrue(currentUrl.contains("state1")); } @@ -664,7 +664,7 @@ public void loginWithSameClientDifferentStatesLoginInTab2() throws Exception { appPage.assertCurrent(); String currentUrl = driver.getCurrentUrl(); assertCurrentUrlStartsWith(redirectUri2); - Assert.assertTrue(currentUrl.contains("state2")); + Assertions.assertTrue(currentUrl.contains("state2")); } // KEYCLOAK-12161 @@ -787,14 +787,14 @@ public void testRedirectToCorrectUrlAfterAuthSessionExpiration() { // Try to login in tab2. After fill login form, the login will be restarted (due KC_RESTART cookie). User can continue login loginPage.login("login-test", getPassword("login-test")); loginPage.assertCurrent(); - Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); + Assertions.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); events.clear(); loginSuccessAndDoRequiredActions(); getLogger().info("URL in after: " + driver.getCurrentUrl()); //redirected url should be the redirect uri 1 - Assert.assertTrue(driver.getCurrentUrl().startsWith(redirectUri1)); + Assertions.assertTrue(driver.getCurrentUrl().startsWith(redirectUri1)); } } @@ -894,14 +894,14 @@ public void testInjectRedirectUriInClientDataAfterAuthSessionExpiration() throws oauth.getDriver().navigate().to(injectedUrl); loginPage.assertCurrent(); - Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); + Assertions.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); events.clear(); loginPage.assertCurrent(); loginSuccessAndDoRequiredActions(); //injected redirected url should be ignored - Assert.assertTrue(driver.getCurrentUrl().startsWith(redirectUri2)); + Assertions.assertTrue(driver.getCurrentUrl().startsWith(redirectUri2)); } } @@ -931,21 +931,21 @@ public void testLogoutDifferentBrowserWithAuthenticationSessionStillPresent() th loginPage.login("test-user@localhost", getPassword("test-user@localhost")); appPage.assertCurrent(); AccessTokenResponse responseOnline = oauth.accessTokenRequest(oauth.parseLoginResponse().getCode()).send(); - Assert.assertNull(responseOnline.getError()); + Assertions.assertNull(responseOnline.getError()); RefreshToken onlineRefreshToken = oauth.parseRefreshToken(responseOnline.getRefreshToken()); - Assert.assertEquals(TokenUtil.TOKEN_TYPE_REFRESH, onlineRefreshToken.getType()); - Assert.assertEquals("test-user@localhost", oauth.verifyToken(responseOnline.getAccessToken()).getPreferredUsername()); + Assertions.assertEquals(TokenUtil.TOKEN_TYPE_REFRESH, onlineRefreshToken.getType()); + Assertions.assertEquals("test-user@localhost", oauth.verifyToken(responseOnline.getAccessToken()).getPreferredUsername()); // perform an offline request for the client, automatic login oauth.scope("openid offline_access"); oauth.openLoginForm(); appPage.assertCurrent(); AccessTokenResponse responseOffline = oauth.accessTokenRequest(oauth.parseLoginResponse().getCode()).send(); - Assert.assertNull(responseOffline.getError()); + Assertions.assertNull(responseOffline.getError()); RefreshToken offlineRefreshToken = oauth.parseRefreshToken(responseOffline.getRefreshToken()); - Assert.assertEquals(TokenUtil.TOKEN_TYPE_OFFLINE, offlineRefreshToken.getType()); - Assert.assertEquals("test-user@localhost", oauth.verifyToken(responseOffline.getAccessToken()).getPreferredUsername()); - Assert.assertEquals(onlineRefreshToken.getSessionId(), offlineRefreshToken.getSessionId()); + Assertions.assertEquals(TokenUtil.TOKEN_TYPE_OFFLINE, offlineRefreshToken.getType()); + Assertions.assertEquals("test-user@localhost", oauth.verifyToken(responseOffline.getAccessToken()).getPreferredUsername()); + Assertions.assertEquals(onlineRefreshToken.getSessionId(), offlineRefreshToken.getSessionId()); // remove the online session using logout but not having the cookies (different browser) HttpPost logoutPost = new HttpPost(OAuthClient.AUTH_SERVER_ROOT + "/realms/" + TEST_REALM_NAME + "/protocol/openid-connect/logout"); @@ -955,7 +955,7 @@ public void testLogoutDifferentBrowserWithAuthenticationSessionStillPresent() th logoutPost.setEntity(formEntity); try (CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse logoutResponse = httpClient.execute(logoutPost)) { - Assert.assertEquals(Response.Status.OK.getStatusCode(), logoutResponse.getStatusLine().getStatusCode()); + Assertions.assertEquals(Response.Status.OK.getStatusCode(), logoutResponse.getStatusLine().getStatusCode()); } // perform a second offline login after logoput with another user, auth session should be different @@ -964,18 +964,18 @@ public void testLogoutDifferentBrowserWithAuthenticationSessionStillPresent() th loginPage.login("non-duplicate-email-user", getPassword("non-duplicate-email-user")); appPage.assertCurrent(); responseOffline = oauth.accessTokenRequest(oauth.parseLoginResponse().getCode()).send(); - Assert.assertNull(responseOffline.getError()); + Assertions.assertNull(responseOffline.getError()); offlineRefreshToken = oauth.parseRefreshToken(responseOffline.getRefreshToken()); System.err.println(responseOffline.getRefreshToken()); - Assert.assertEquals(TokenUtil.TOKEN_TYPE_OFFLINE, offlineRefreshToken.getType()); - Assert.assertEquals("non-duplicate-email-user", oauth.verifyToken(responseOffline.getAccessToken()).getPreferredUsername()); - Assert.assertNotEquals(onlineRefreshToken.getSessionId(), offlineRefreshToken.getSessionId()); + Assertions.assertEquals(TokenUtil.TOKEN_TYPE_OFFLINE, offlineRefreshToken.getType()); + Assertions.assertEquals("non-duplicate-email-user", oauth.verifyToken(responseOffline.getAccessToken()).getPreferredUsername()); + Assertions.assertNotEquals(onlineRefreshToken.getSessionId(), offlineRefreshToken.getSessionId()); // refresh the token and check everything is correct responseOffline = oauth.doRefreshTokenRequest(responseOffline.getRefreshToken()); - Assert.assertNull(responseOffline.getError()); - Assert.assertEquals(TokenUtil.TOKEN_TYPE_OFFLINE, oauth.parseRefreshToken(responseOffline.getRefreshToken()).getType()); - Assert.assertEquals("non-duplicate-email-user", oauth.verifyToken(responseOffline.getAccessToken()).getPreferredUsername()); + Assertions.assertNull(responseOffline.getError()); + Assertions.assertEquals(TokenUtil.TOKEN_TYPE_OFFLINE, oauth.parseRefreshToken(responseOffline.getRefreshToken()).getType()); + Assertions.assertEquals("non-duplicate-email-user", oauth.verifyToken(responseOffline.getAccessToken()).getPreferredUsername()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/PasswordHashingTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/PasswordHashingTest.java index 37c4901b1890..337401499d23 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/PasswordHashingTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/PasswordHashingTest.java @@ -65,14 +65,14 @@ import org.bouncycastle.crypto.generators.Argon2BytesGenerator; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Assume; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Stian Thorgersen @@ -298,18 +298,18 @@ public void testArgon2() { PasswordCredentialModel credential = PasswordCredentialModel.createFromCredentialModel(fetchCredentials(username)); PasswordCredentialData data = credential.getPasswordCredentialData(); - Assert.assertEquals("argon2", data.getAlgorithm()); - Assert.assertEquals(5, data.getHashIterations()); - Assert.assertEquals("1.3", data.getAdditionalParameters().getFirst("version")); - Assert.assertEquals("id", data.getAdditionalParameters().getFirst("type")); - Assert.assertEquals("32", data.getAdditionalParameters().getFirst("hashLength")); - Assert.assertEquals("7168", data.getAdditionalParameters().getFirst("memory")); - Assert.assertEquals("1", data.getAdditionalParameters().getFirst("parallelism")); + Assertions.assertEquals("argon2", data.getAlgorithm()); + Assertions.assertEquals(5, data.getHashIterations()); + Assertions.assertEquals("1.3", data.getAdditionalParameters().getFirst("version")); + Assertions.assertEquals("id", data.getAdditionalParameters().getFirst("type")); + Assertions.assertEquals("32", data.getAdditionalParameters().getFirst("hashLength")); + Assertions.assertEquals("7168", data.getAdditionalParameters().getFirst("memory")); + Assertions.assertEquals("1", data.getAdditionalParameters().getFirst("parallelism")); oauth.openLoginForm(); loginPage.login("testArgon2", "invalid"); loginPage.assertCurrent(); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); loginPage.login("testArgon2", password); @@ -434,7 +434,7 @@ private void assertEncoded(PasswordCredentialModel credential, String password, byte[] result = new byte[32]; generator.generateBytes(password.toCharArray(), result); - Assert.assertEquals(Base64.getEncoder().encodeToString(result), credential.getPasswordSecretData().getValue()); + Assertions.assertEquals(Base64.getEncoder().encodeToString(result), credential.getPasswordSecretData().getValue()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/RPInitiatedFrontChannelLogoutTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/RPInitiatedFrontChannelLogoutTest.java index 3633837529a2..6ebac775ab12 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/RPInitiatedFrontChannelLogoutTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/RPInitiatedFrontChannelLogoutTest.java @@ -29,8 +29,8 @@ import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.keycloak.testsuite.util.oauth.OAuthClient; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @@ -53,12 +53,12 @@ public void testFrontChannelLogoutWithPostLogoutRedirectUri() throws Exception { oauth.logoutForm().idTokenHint(idTokenString) .postLogoutRedirectUri(OAuthClient.APP_AUTH_ROOT).open(); LogoutToken logoutToken = testingClient.testApp().getFrontChannelLogoutToken(); - Assert.assertNotNull(logoutToken); + Assertions.assertNotNull(logoutToken); IDToken idToken = new JWSInput(idTokenString).readJsonContent(IDToken.class); - Assert.assertEquals(logoutToken.getIssuer(), idToken.getIssuer()); - Assert.assertEquals(logoutToken.getSid(), idToken.getSessionId()); + Assertions.assertEquals(logoutToken.getIssuer(), idToken.getIssuer()); + Assertions.assertEquals(logoutToken.getSid(), idToken.getSessionId()); } finally { rep.setFrontchannelLogout(false); rep.getAttributes().put(OIDCConfigAttributes.FRONT_CHANNEL_LOGOUT_URI, ""); @@ -82,10 +82,10 @@ public void testFrontChannelLogoutWithoutSessionRequired() throws Exception { oauth.logoutForm().idTokenHint(idTokenString) .postLogoutRedirectUri(OAuthClient.APP_AUTH_ROOT).open(); LogoutToken logoutToken = testingClient.testApp().getFrontChannelLogoutToken(); - Assert.assertNotNull(logoutToken); + Assertions.assertNotNull(logoutToken); - Assert.assertNull(logoutToken.getIssuer()); - Assert.assertNull(logoutToken.getSid()); + Assertions.assertNull(logoutToken.getIssuer()); + Assertions.assertNull(logoutToken.getSid()); } finally { rep.setFrontchannelLogout(false); rep.getAttributes().put(OIDCConfigAttributes.FRONT_CHANNEL_LOGOUT_URI, ""); @@ -109,13 +109,13 @@ public void testFrontChannelLogout() throws Exception { String idTokenString = tokenResponse.getIdToken(); oauth.logoutForm().idTokenHint(idTokenString).open(); LogoutToken logoutToken = testingClient.testApp().getFrontChannelLogoutToken(); - org.keycloak.testsuite.Assert.assertNotNull(logoutToken); + Assertions.assertNotNull(logoutToken); IDToken idToken = new JWSInput(idTokenString).readJsonContent(IDToken.class); - org.keycloak.testsuite.Assert.assertEquals(logoutToken.getIssuer(), idToken.getIssuer()); - org.keycloak.testsuite.Assert.assertEquals(logoutToken.getSid(), idToken.getSessionId()); - Assert.assertTrue(driver.getTitle().equals("Logging out")); - Assert.assertTrue(driver.getPageSource().contains("You are logging out from following apps")); - Assert.assertTrue(driver.getPageSource().contains("My Testing App")); + Assertions.assertEquals(logoutToken.getIssuer(), idToken.getIssuer()); + Assertions.assertEquals(logoutToken.getSid(), idToken.getSessionId()); + Assertions.assertTrue(driver.getTitle().equals("Logging out")); + Assertions.assertTrue(driver.getPageSource().contains("You are logging out from following apps")); + Assertions.assertTrue(driver.getPageSource().contains("My Testing App")); } finally { rep.setFrontchannelLogout(false); rep.getAttributes().put(OIDCConfigAttributes.FRONT_CHANNEL_LOGOUT_URI, ""); @@ -140,13 +140,13 @@ public void testFrontChannelLogoutCustomCSP() throws Exception { String idTokenString = tokenResponse.getIdToken(); oauth.logoutForm().idTokenHint(idTokenString).open(); LogoutToken logoutToken = testingClient.testApp().getFrontChannelLogoutToken(); - Assert.assertNotNull(logoutToken); + Assertions.assertNotNull(logoutToken); IDToken idToken = new JWSInput(idTokenString).readJsonContent(IDToken.class); - Assert.assertEquals(logoutToken.getIssuer(), idToken.getIssuer()); - Assert.assertEquals(logoutToken.getSid(), idToken.getSessionId()); - Assert.assertTrue(driver.getTitle().equals("Logging out")); - Assert.assertTrue(driver.getPageSource().contains("You are logging out from following apps")); - Assert.assertTrue(driver.getPageSource().contains("My Testing App")); + Assertions.assertEquals(logoutToken.getIssuer(), idToken.getIssuer()); + Assertions.assertEquals(logoutToken.getSid(), idToken.getSessionId()); + Assertions.assertTrue(driver.getTitle().equals("Logging out")); + Assertions.assertTrue(driver.getPageSource().contains("You are logging out from following apps")); + Assertions.assertTrue(driver.getPageSource().contains("My Testing App")); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ReAuthenticationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ReAuthenticationTest.java index 9a9179c19729..ed176c884de1 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ReAuthenticationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ReAuthenticationTest.java @@ -32,7 +32,6 @@ import org.keycloak.representations.idm.IdentityProviderRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.AbstractChangeImportedUserPasswordsTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.auth.page.login.OneTimeCode; import org.keycloak.testsuite.broker.SocialLoginTest; @@ -54,6 +53,7 @@ import org.jboss.arquillian.graphene.page.Page; import org.jboss.arquillian.test.api.ArquillianResource; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; @@ -130,7 +130,7 @@ public void usernamePasswordFormReauthentication() { assertUsernameFieldAndOtherFields(true); assertSocialButtonsPresent(true, true); loginPage.login("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); // Set time offset setTimeOffset(10); @@ -149,12 +149,12 @@ public void usernamePasswordFormReauthentication() { // Try bad password and assert things still hidden loginPage.login("bad-password"); loginPage.assertCurrent(); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); assertUsernameFieldAndOtherFields(false); assertInfoMessageAboutReAuthenticate(false); loginPage.login(getPassword("test-user@localhost")); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); // Remove link user.removeFederatedIdentity("github"); @@ -169,7 +169,7 @@ public void usernamePasswordFormReauthenticationWithResetFlow() { assertUsernameFieldAndOtherFields(true); assertSocialButtonsPresent(true, true); loginPage.login("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); // Set time offset setTimeOffset(10); @@ -186,7 +186,7 @@ public void usernamePasswordFormReauthenticationWithResetFlow() { assertSocialButtonsPresent(false, false); // Try click "Reset password" . This will start login page from the beginning due SSO logout - Assert.assertEquals("test-user@localhost", loginPage.getAttemptedUsername()); + Assertions.assertEquals("test-user@localhost", loginPage.getAttemptedUsername()); loginPage.clickResetLogin(); // Username field should be back. Attempted username should not be shown @@ -199,7 +199,7 @@ public void usernamePasswordFormReauthenticationWithResetFlow() { // Successfully login as different user. It should be possible due previous SSO session was removed loginPage.login("john-doh@localhost", getPassword("john-doh@localhost")); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); } // Re-authentication with user form separate to the password form. The username form would be skipped @@ -216,7 +216,7 @@ public void identityFirstFormReauthentication() { loginUsernameOnlyPage.login("test-user@localhost"); passwordPage.assertCurrent(); passwordPage.login(getPassword("test-user@localhost")); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); // Set time offset setTimeOffset(10); @@ -226,13 +226,13 @@ public void identityFirstFormReauthentication() { // User directly on the password page. Info message should be shown here passwordPage.assertCurrent(); - Assert.assertEquals("test-user@localhost", passwordPage.getAttemptedUsername()); + Assertions.assertEquals("test-user@localhost", passwordPage.getAttemptedUsername()); assertInfoMessageAboutReAuthenticate(true); passwordPage.login("bad-password"); - Assert.assertEquals("Invalid password.", passwordPage.getPasswordError()); + Assertions.assertEquals("Invalid password.", passwordPage.getPasswordError()); passwordPage.login(getPassword("test-user@localhost")); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); // Revert flows BrowserFlowTest.revertFlows(testRealm(), "browser - identity first"); @@ -259,7 +259,7 @@ public void identityFirstFormReauthenticationWithGithubLink() { loginUsernameOnlyPage.login("test-user@localhost"); passwordPage.assertCurrent(); passwordPage.login(getPassword("test-user@localhost")); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); // See that user can re-authenticate with the github link present on the page as user has link to github social provider setTimeOffset(10); @@ -283,7 +283,7 @@ public void identityFirstFormReauthenticationWithGithubLink() { passwordPage.assertCurrent(); passwordPage.login(getPassword("test-user@localhost")); assertInfoMessageAboutReAuthenticate(false); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); // Remove link and flow user.removeFederatedIdentity("github"); @@ -308,8 +308,8 @@ public void restartLoginWithNewRootAuthSession() { AccessToken accessToken1 = oauth.verifyToken(response1.getAccessToken()); AccessToken accessToken2 = oauth.verifyToken(response2.getAccessToken()); - Assert.assertNotEquals(accessToken1.getSubject(), accessToken2.getSubject()); - Assert.assertNotEquals(accessToken1.getSessionId(), accessToken2.getSessionId()); + Assertions.assertNotEquals(accessToken1.getSubject(), accessToken2.getSubject()); + Assertions.assertNotEquals(accessToken1.getSessionId(), accessToken2.getSessionId()); } @Test @@ -341,8 +341,8 @@ public void loginAfterExpiredUserSession() { AccessToken accessToken1 = oauth.verifyToken(response1.getAccessToken()); AccessToken accessToken2 = oauth.verifyToken(response2.getAccessToken()); - Assert.assertNotEquals(accessToken1.getSubject(), accessToken2.getSubject()); - Assert.assertNotEquals(accessToken1.getSessionId(), accessToken2.getSessionId()); + Assertions.assertNotEquals(accessToken1.getSubject(), accessToken2.getSubject()); + Assertions.assertNotEquals(accessToken1.getSessionId(), accessToken2.getSessionId()); setTimeOffset(0); rep.setSsoSessionIdleTimeout(originalSsoSessionIdleTimeout); @@ -382,8 +382,8 @@ public void loginAfterLogoutWithDifferentSessionId() { AccessTokenResponse response2 = oauth.doAccessTokenRequest(code); AccessToken accessToken2 = oauth.verifyToken(response2.getAccessToken()); - Assert.assertNotEquals(accessToken1.getId(), accessToken2.getId()); - Assert.assertNotEquals(accessToken1.getSessionId(), accessToken2.getSessionId()); + Assertions.assertNotEquals(accessToken1.getId(), accessToken2.getId()); + Assertions.assertNotEquals(accessToken1.getSessionId(), accessToken2.getSessionId()); } private void setupIdentityFirstFlow() { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/RecoveryAuthnCodesAuthenticatorTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/RecoveryAuthnCodesAuthenticatorTest.java index 318b6e135d06..f18c52be36a4 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/RecoveryAuthnCodesAuthenticatorTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/RecoveryAuthnCodesAuthenticatorTest.java @@ -59,10 +59,10 @@ import org.hamcrest.Matchers; import org.jboss.arquillian.drone.api.annotation.Drone; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import org.openqa.selenium.WebDriver; @@ -70,7 +70,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Backup Code Authentication test @@ -175,7 +175,7 @@ private void testSetupRecoveryAuthnCodesLogoutOtherSessions(boolean logoutOtherS if (logoutOtherSessions) { setupRecoveryAuthnCodesPage.checkLogoutSessions(); } - Assert.assertEquals(logoutOtherSessions, setupRecoveryAuthnCodesPage.isLogoutSessionsChecked()); + Assertions.assertEquals(logoutOtherSessions, setupRecoveryAuthnCodesPage.isLogoutSessionsChecked()); setupRecoveryAuthnCodesPage.clickSaveRecoveryAuthnCodesButton(); assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); @@ -292,7 +292,7 @@ private void tryAnotherWay(PasswordPage passwordPage, WebDriver driver) { passwordPage.assertCurrent(); passwordPage.assertAttemptedUsernameAvailability(true); // On the password page, username should be shown as we know the user - Assert.assertEquals("test-user@localhost", passwordPage.getAttemptedUsername()); + Assertions.assertEquals("test-user@localhost", passwordPage.getAttemptedUsername()); passwordPage.assertTryAnotherWayLinkAvailability(true); passwordPage.clickTryAnotherWayLink(); } @@ -300,7 +300,7 @@ private void tryAnotherWay(PasswordPage passwordPage, WebDriver driver) { private void selectRecoveryAuthnCodes(SelectAuthenticatorPage selectAuthenticatorPage, WebDriver driver) { selectAuthenticatorPage.setDriver(driver); selectAuthenticatorPage.assertCurrent(); - Assert.assertEquals(Arrays.asList(SelectAuthenticatorPage.PASSWORD, SelectAuthenticatorPage.RECOVERY_AUTHN_CODES), selectAuthenticatorPage.getAvailableLoginMethods()); + Assertions.assertEquals(Arrays.asList(SelectAuthenticatorPage.PASSWORD, SelectAuthenticatorPage.RECOVERY_AUTHN_CODES), selectAuthenticatorPage.getAvailableLoginMethods()); selectAuthenticatorPage.selectLoginMethod(SelectAuthenticatorPage.RECOVERY_AUTHN_CODES); } @@ -309,7 +309,7 @@ private void enterRecoveryCodes(EnterRecoveryAuthnCodePage enterRecoveryAuthnCod enterRecoveryAuthnCodePage.setDriver(driver); enterRecoveryAuthnCodePage.assertCurrent(); int requestedCode = enterRecoveryAuthnCodePage.getRecoveryAuthnCodeToEnterNumber(); - Assert.assertEquals("Incorrect code presented to login", expectedCode, requestedCode); + Assertions.assertEquals(expectedCode, requestedCode, "Incorrect code presented to login"); enterRecoveryAuthnCodePage.enterRecoveryAuthnCode(generatedRecoveryAuthnCodes.get(requestedCode)); } @@ -344,7 +344,7 @@ private void assertIsContained(AssertEvents.ExpectedEvent expectedEvent, ListStian Thorgersen @@ -458,8 +458,8 @@ private UserRepresentation assertUserRegistered(String userId, String username, events.expectLogin().detail("username", username.toLowerCase()).user(userId).assertEvent(); UserRepresentation user = getUser(userId); - Assert.assertNotNull(user); - Assert.assertNotNull(user.getCreatedTimestamp()); + Assertions.assertNotNull(user); + Assertions.assertNotNull(user.getCreatedTimestamp()); // test that timestamp is current with 10s tollerance assertTrue((System.currentTimeMillis() - user.getCreatedTimestamp()) < 10000); assertUserBasicRegisterAttributes(userId, username, email, "firstName", "lastName"); @@ -645,8 +645,8 @@ public void registerUserSuccess_emailAsUsername() throws IOException { events.expectLogin().detail("username", "registerusersuccesse@email").user(userId).assertEvent(); UserRepresentation user = getUser(userId); - Assert.assertNotNull(user); - Assert.assertNotNull(user.getCreatedTimestamp()); + Assertions.assertNotNull(user); + Assertions.assertNotNull(user.getCreatedTimestamp()); // test that timestamp is current with 10s tollerance assertTrue((System.currentTimeMillis() - user.getCreatedTimestamp()) < 10000); } @@ -755,7 +755,7 @@ public void registerUserSuccessTermsAcceptanceWithRequiredActionEnabled() { // configure Terms and Conditions required action as enabled and default RequiredActionProviderRepresentation tacRep = testRealm().flows().getRequiredAction(UserModel.RequiredAction.TERMS_AND_CONDITIONS.name()); - Assert.assertNotNull(tacRep); + Assertions.assertNotNull(tacRep); tacRep.setEnabled(true); tacRep.setDefaultAction(true); testRealm().flows().updateRequiredAction(UserModel.RequiredAction.TERMS_AND_CONDITIONS.name(), tacRep); @@ -775,10 +775,10 @@ public void registerUserSuccessTermsAcceptanceWithRequiredActionEnabled() { String userId = events.expectRegister("registerUserSuccessTermsAcceptance2", "registerUserSuccessTermsAcceptance2@email") .assertEvent().getUserId(); UserRepresentation user = assertUserRegistered(userId, "registerUserSuccessTermsAcceptance2", "registerUserSuccessTermsAcceptance2@email"); - Assert.assertNotNull(user.getAttributes()); - Assert.assertNotNull(user.getAttributes().get(TermsAndConditions.USER_ATTRIBUTE)); - Assert.assertEquals(1, user.getAttributes().get(TermsAndConditions.USER_ATTRIBUTE).size()); - Assert.assertTrue(Integer.parseInt(user.getAttributes().get(TermsAndConditions.USER_ATTRIBUTE).get(0)) >= currentTime); + Assertions.assertNotNull(user.getAttributes()); + Assertions.assertNotNull(user.getAttributes().get(TermsAndConditions.USER_ATTRIBUTE)); + Assertions.assertEquals(1, user.getAttributes().get(TermsAndConditions.USER_ATTRIBUTE).size()); + Assertions.assertTrue(Integer.parseInt(user.getAttributes().get(TermsAndConditions.USER_ATTRIBUTE).get(0)) >= currentTime); } finally { tacRep.setEnabled(false); tacRep.setDefaultAction(false); @@ -803,7 +803,7 @@ public void testRegisterShouldFailBeforeUserCreationWhenUserIsInContext() { events.clear(); UIUtils.navigateBackWithRefresh(driver, errorPage); - Assert.assertEquals("Action expired. Please continue with login now.", errorPage.getError()); + Assertions.assertEquals("Action expired. Please continue with login now.", errorPage.getError()); events.expectRegister("registerUserMissingTermsAcceptance", "registerUserMissingTermsAcceptance@email") .removeDetail(Details.USERNAME) diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/RegisterWithUserProfileTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/RegisterWithUserProfileTest.java index f9e4c3f59e24..022dc25eeb76 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/RegisterWithUserProfileTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/RegisterWithUserProfileTest.java @@ -38,10 +38,10 @@ import org.apache.commons.lang3.StringUtils; import org.hamcrest.Matchers; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; @@ -57,9 +57,9 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test user registration with customized user-profile configurations @@ -269,11 +269,11 @@ public void testAttributeDisplayName() { //assert field names // i18n replaced - Assert.assertEquals("First name",registerPage.getLabelForField("firstName")); + Assertions.assertEquals("First name",registerPage.getLabelForField("firstName")); // attribute name used if no display name set - Assert.assertEquals("lastName",registerPage.getLabelForField("lastName")); + Assertions.assertEquals("lastName",registerPage.getLabelForField("lastName")); // direct value in display name - Assert.assertEquals("Department",registerPage.getLabelForField("department")); + Assertions.assertEquals("Department",registerPage.getLabelForField("department")); } @Test @@ -331,72 +331,72 @@ public void testAttributeInputTypes() { } public static void assertFieldTypes(WebDriver driver) { - Assert.assertEquals("text", driver.findElement(By.cssSelector("input#defaultType")).getAttribute("type")); - - Assert.assertEquals("text", driver.findElement(By.cssSelector("input#placeholderAttribute")).getAttribute("type")); - Assert.assertEquals("Example.", driver.findElement(By.cssSelector("input#placeholderAttribute")).getAttribute("placeholder")); - - Assert.assertEquals("Example bold text before.", driver.findElement(By.cssSelector("div#form-help-text-before-helperTexts")).getText()); - Assert.assertEquals("bold text", driver.findElement(By.cssSelector("div#form-help-text-before-helperTexts b")).getText()); - Assert.assertEquals("Example i text after.", driver.findElement(By.cssSelector("div#form-help-text-after-helperTexts")).getText()); - Assert.assertEquals("i text", driver.findElement(By.cssSelector("div#form-help-text-after-helperTexts i")).getText()); - - Assert.assertEquals("text", driver.findElement(By.cssSelector("input#textWithBasicAttributes")).getAttribute("type")); - Assert.assertEquals("35", driver.findElement(By.cssSelector("input#textWithBasicAttributes")).getAttribute("size")); - Assert.assertEquals("1", driver.findElement(By.cssSelector("input#textWithBasicAttributes")).getAttribute("minlength")); - Assert.assertEquals("10", driver.findElement(By.cssSelector("input#textWithBasicAttributes")).getAttribute("maxlength")); - Assert.assertEquals(".*", driver.findElement(By.cssSelector("input#textWithBasicAttributes")).getAttribute("pattern")); - - Assert.assertEquals("number", driver.findElement(By.cssSelector("input#html5NumberWithAttributes")).getAttribute("type")); - Assert.assertEquals("10", driver.findElement(By.cssSelector("input#html5NumberWithAttributes")).getAttribute("min")); - Assert.assertEquals("20", driver.findElement(By.cssSelector("input#html5NumberWithAttributes")).getAttribute("max")); - Assert.assertEquals("1", driver.findElement(By.cssSelector("input#html5NumberWithAttributes")).getAttribute("step")); - - Assert.assertEquals("35", driver.findElement(By.cssSelector("textarea#textareaWithAttributes")).getAttribute("cols")); - Assert.assertEquals("7", driver.findElement(By.cssSelector("textarea#textareaWithAttributes")).getAttribute("rows")); - Assert.assertEquals("10", driver.findElement(By.cssSelector("textarea#textareaWithAttributes")).getAttribute("maxlength")); - - Assert.assertEquals("5", driver.findElement(By.cssSelector("select#selectWithoutOptions")).getAttribute("size")); - - Assert.assertEquals(null, driver.findElement(By.cssSelector("select#selectWithOptionsWithoutLabels")).getAttribute("multiple")); - Assert.assertEquals("opt1", driver.findElement(By.cssSelector("select#selectWithOptionsWithoutLabels option[value=opt1]")).getText()); - Assert.assertEquals("opt2", driver.findElement(By.cssSelector("select#selectWithOptionsWithoutLabels option[value=opt2]")).getText()); - Assert.assertEquals("default empty option is missing in select","", driver.findElement(By.cssSelector("select#selectWithOptionsWithoutLabels option[value='']")).getText()); - - Assert.assertEquals("true", driver.findElement(By.cssSelector("select#multiselectWithOptionsAndSimpleI18nLabels")).getAttribute("multiple")); - Assert.assertEquals("Time-based", driver.findElement(By.cssSelector("select#multiselectWithOptionsAndSimpleI18nLabels option[value=totp]")).getText()); - Assert.assertEquals("loginTotp.opt2", driver.findElement(By.cssSelector("select#multiselectWithOptionsAndSimpleI18nLabels option[value=opt2]")).getText()); - - Assert.assertEquals("true", driver.findElement(By.cssSelector("select#multiselectWithOptionsAndLabels")).getAttribute("multiple")); - Assert.assertEquals("Option 1", driver.findElement(By.cssSelector("select#multiselectWithOptionsAndLabels option[value=opt1]")).getText()); - Assert.assertEquals("Username", driver.findElement(By.cssSelector("select#multiselectWithOptionsAndLabels option[value=opt2]")).getText()); - Assert.assertEquals("opt3", driver.findElement(By.cssSelector("select#multiselectWithOptionsAndLabels option[value=opt3]")).getText()); - - Assert.assertEquals(null, driver.findElement(By.cssSelector("select#selectWithOptionsFromCustomValidatorAndLabels")).getAttribute("multiple")); - Assert.assertEquals("Option 1", driver.findElement(By.cssSelector("select#selectWithOptionsFromCustomValidatorAndLabels option[value=vopt1]")).getText()); - Assert.assertEquals("Username", driver.findElement(By.cssSelector("select#selectWithOptionsFromCustomValidatorAndLabels option[value=vopt2]")).getText()); - Assert.assertEquals("vopt3", driver.findElement(By.cssSelector("select#selectWithOptionsFromCustomValidatorAndLabels option[value=vopt3]")).getText()); - - Assert.assertEquals("radio", driver.findElement(By.cssSelector("input#selectRadiobuttons-opt1")).getAttribute("type")); - Assert.assertEquals("Option 1", driver.findElement(By.cssSelector("label[for=selectRadiobuttons-opt1]")).getText()); - Assert.assertEquals("radio", driver.findElement(By.cssSelector("input#selectRadiobuttons-opt2")).getAttribute("type")); - Assert.assertEquals("Username", driver.findElement(By.cssSelector("label[for=selectRadiobuttons-opt2]")).getText()); - Assert.assertEquals("radio", driver.findElement(By.cssSelector("input#selectRadiobuttons-opt3")).getAttribute("type")); - Assert.assertEquals("opt3", driver.findElement(By.cssSelector("label[for=selectRadiobuttons-opt3]")).getText()); - - Assert.assertEquals("radio", driver.findElement(By.cssSelector("input#selectRadiobuttonsWithOptionsFromCustomValidatorAndLabels-vopt1")).getAttribute("type")); - Assert.assertEquals("Option 1", driver.findElement(By.cssSelector("label[for=selectRadiobuttonsWithOptionsFromCustomValidatorAndLabels-vopt1]")).getText()); - Assert.assertEquals("radio", driver.findElement(By.cssSelector("input#selectRadiobuttonsWithOptionsFromCustomValidatorAndLabels-vopt2")).getAttribute("type")); - Assert.assertEquals("Username", driver.findElement(By.cssSelector("label[for=selectRadiobuttonsWithOptionsFromCustomValidatorAndLabels-vopt2]")).getText()); - Assert.assertEquals("radio", driver.findElement(By.cssSelector("input#selectRadiobuttonsWithOptionsFromCustomValidatorAndLabels-vopt3")).getAttribute("type")); - Assert.assertEquals("vopt3", driver.findElement(By.cssSelector("label[for=selectRadiobuttonsWithOptionsFromCustomValidatorAndLabels-vopt3]")).getText()); - - Assert.assertEquals("checkbox", driver.findElement(By.cssSelector("input#multiselectCheckboxes-opt1")).getAttribute("type")); - Assert.assertEquals("Option 1", driver.findElement(By.cssSelector("label[for=multiselectCheckboxes-opt1]")).getText()); - Assert.assertEquals("checkbox", driver.findElement(By.cssSelector("input#multiselectCheckboxes-opt2")).getAttribute("type")); - Assert.assertEquals("Username", driver.findElement(By.cssSelector("label[for=multiselectCheckboxes-opt2]")).getText()); - Assert.assertEquals("checkbox", driver.findElement(By.cssSelector("input#multiselectCheckboxes-opt3")).getAttribute("type")); - Assert.assertEquals("opt3", driver.findElement(By.cssSelector("label[for=multiselectCheckboxes-opt3]")).getText()); + Assertions.assertEquals("text", driver.findElement(By.cssSelector("input#defaultType")).getAttribute("type")); + + Assertions.assertEquals("text", driver.findElement(By.cssSelector("input#placeholderAttribute")).getAttribute("type")); + Assertions.assertEquals("Example.", driver.findElement(By.cssSelector("input#placeholderAttribute")).getAttribute("placeholder")); + + Assertions.assertEquals("Example bold text before.", driver.findElement(By.cssSelector("div#form-help-text-before-helperTexts")).getText()); + Assertions.assertEquals("bold text", driver.findElement(By.cssSelector("div#form-help-text-before-helperTexts b")).getText()); + Assertions.assertEquals("Example i text after.", driver.findElement(By.cssSelector("div#form-help-text-after-helperTexts")).getText()); + Assertions.assertEquals("i text", driver.findElement(By.cssSelector("div#form-help-text-after-helperTexts i")).getText()); + + Assertions.assertEquals("text", driver.findElement(By.cssSelector("input#textWithBasicAttributes")).getAttribute("type")); + Assertions.assertEquals("35", driver.findElement(By.cssSelector("input#textWithBasicAttributes")).getAttribute("size")); + Assertions.assertEquals("1", driver.findElement(By.cssSelector("input#textWithBasicAttributes")).getAttribute("minlength")); + Assertions.assertEquals("10", driver.findElement(By.cssSelector("input#textWithBasicAttributes")).getAttribute("maxlength")); + Assertions.assertEquals(".*", driver.findElement(By.cssSelector("input#textWithBasicAttributes")).getAttribute("pattern")); + + Assertions.assertEquals("number", driver.findElement(By.cssSelector("input#html5NumberWithAttributes")).getAttribute("type")); + Assertions.assertEquals("10", driver.findElement(By.cssSelector("input#html5NumberWithAttributes")).getAttribute("min")); + Assertions.assertEquals("20", driver.findElement(By.cssSelector("input#html5NumberWithAttributes")).getAttribute("max")); + Assertions.assertEquals("1", driver.findElement(By.cssSelector("input#html5NumberWithAttributes")).getAttribute("step")); + + Assertions.assertEquals("35", driver.findElement(By.cssSelector("textarea#textareaWithAttributes")).getAttribute("cols")); + Assertions.assertEquals("7", driver.findElement(By.cssSelector("textarea#textareaWithAttributes")).getAttribute("rows")); + Assertions.assertEquals("10", driver.findElement(By.cssSelector("textarea#textareaWithAttributes")).getAttribute("maxlength")); + + Assertions.assertEquals("5", driver.findElement(By.cssSelector("select#selectWithoutOptions")).getAttribute("size")); + + Assertions.assertEquals(null, driver.findElement(By.cssSelector("select#selectWithOptionsWithoutLabels")).getAttribute("multiple")); + Assertions.assertEquals("opt1", driver.findElement(By.cssSelector("select#selectWithOptionsWithoutLabels option[value=opt1]")).getText()); + Assertions.assertEquals("opt2", driver.findElement(By.cssSelector("select#selectWithOptionsWithoutLabels option[value=opt2]")).getText()); + Assertions.assertEquals("", driver.findElement(By.cssSelector("select#selectWithOptionsWithoutLabels option[value='']")).getText(), "default empty option is missing in select"); + + Assertions.assertEquals("true", driver.findElement(By.cssSelector("select#multiselectWithOptionsAndSimpleI18nLabels")).getAttribute("multiple")); + Assertions.assertEquals("Time-based", driver.findElement(By.cssSelector("select#multiselectWithOptionsAndSimpleI18nLabels option[value=totp]")).getText()); + Assertions.assertEquals("loginTotp.opt2", driver.findElement(By.cssSelector("select#multiselectWithOptionsAndSimpleI18nLabels option[value=opt2]")).getText()); + + Assertions.assertEquals("true", driver.findElement(By.cssSelector("select#multiselectWithOptionsAndLabels")).getAttribute("multiple")); + Assertions.assertEquals("Option 1", driver.findElement(By.cssSelector("select#multiselectWithOptionsAndLabels option[value=opt1]")).getText()); + Assertions.assertEquals("Username", driver.findElement(By.cssSelector("select#multiselectWithOptionsAndLabels option[value=opt2]")).getText()); + Assertions.assertEquals("opt3", driver.findElement(By.cssSelector("select#multiselectWithOptionsAndLabels option[value=opt3]")).getText()); + + Assertions.assertEquals(null, driver.findElement(By.cssSelector("select#selectWithOptionsFromCustomValidatorAndLabels")).getAttribute("multiple")); + Assertions.assertEquals("Option 1", driver.findElement(By.cssSelector("select#selectWithOptionsFromCustomValidatorAndLabels option[value=vopt1]")).getText()); + Assertions.assertEquals("Username", driver.findElement(By.cssSelector("select#selectWithOptionsFromCustomValidatorAndLabels option[value=vopt2]")).getText()); + Assertions.assertEquals("vopt3", driver.findElement(By.cssSelector("select#selectWithOptionsFromCustomValidatorAndLabels option[value=vopt3]")).getText()); + + Assertions.assertEquals("radio", driver.findElement(By.cssSelector("input#selectRadiobuttons-opt1")).getAttribute("type")); + Assertions.assertEquals("Option 1", driver.findElement(By.cssSelector("label[for=selectRadiobuttons-opt1]")).getText()); + Assertions.assertEquals("radio", driver.findElement(By.cssSelector("input#selectRadiobuttons-opt2")).getAttribute("type")); + Assertions.assertEquals("Username", driver.findElement(By.cssSelector("label[for=selectRadiobuttons-opt2]")).getText()); + Assertions.assertEquals("radio", driver.findElement(By.cssSelector("input#selectRadiobuttons-opt3")).getAttribute("type")); + Assertions.assertEquals("opt3", driver.findElement(By.cssSelector("label[for=selectRadiobuttons-opt3]")).getText()); + + Assertions.assertEquals("radio", driver.findElement(By.cssSelector("input#selectRadiobuttonsWithOptionsFromCustomValidatorAndLabels-vopt1")).getAttribute("type")); + Assertions.assertEquals("Option 1", driver.findElement(By.cssSelector("label[for=selectRadiobuttonsWithOptionsFromCustomValidatorAndLabels-vopt1]")).getText()); + Assertions.assertEquals("radio", driver.findElement(By.cssSelector("input#selectRadiobuttonsWithOptionsFromCustomValidatorAndLabels-vopt2")).getAttribute("type")); + Assertions.assertEquals("Username", driver.findElement(By.cssSelector("label[for=selectRadiobuttonsWithOptionsFromCustomValidatorAndLabels-vopt2]")).getText()); + Assertions.assertEquals("radio", driver.findElement(By.cssSelector("input#selectRadiobuttonsWithOptionsFromCustomValidatorAndLabels-vopt3")).getAttribute("type")); + Assertions.assertEquals("vopt3", driver.findElement(By.cssSelector("label[for=selectRadiobuttonsWithOptionsFromCustomValidatorAndLabels-vopt3]")).getText()); + + Assertions.assertEquals("checkbox", driver.findElement(By.cssSelector("input#multiselectCheckboxes-opt1")).getAttribute("type")); + Assertions.assertEquals("Option 1", driver.findElement(By.cssSelector("label[for=multiselectCheckboxes-opt1]")).getText()); + Assertions.assertEquals("checkbox", driver.findElement(By.cssSelector("input#multiselectCheckboxes-opt2")).getAttribute("type")); + Assertions.assertEquals("Username", driver.findElement(By.cssSelector("label[for=multiselectCheckboxes-opt2]")).getText()); + Assertions.assertEquals("checkbox", driver.findElement(By.cssSelector("input#multiselectCheckboxes-opt3")).getAttribute("type")); + Assertions.assertEquals("opt3", driver.findElement(By.cssSelector("label[for=multiselectCheckboxes-opt3]")).getText()); } @Test @@ -449,7 +449,7 @@ public void testRegisterUserSuccess_requiredReadOnlyAttributeNotRenderedAndNotBl registerPage.assertCurrent(); - Assert.assertFalse(registerPage.isDepartmentPresent()); + Assertions.assertFalse(registerPage.isDepartmentPresent()); registerPage.register("FirstName", "LastName", "requiredReadOnlyAttributeNotRenderedAndNotBlockingRegistration@email", "requiredReadOnlyAttributeNotRenderedAndNotBlockingRegistration", generatePassword()); @@ -479,8 +479,8 @@ public void testRegisterUserSuccess_attributeRequiredAndSelectedByScopeMustBeSet registerPage.register("FirstAA", "LastAA", "attributeRequiredAndSelectedByScopeMustBeSet@email", "attributeRequiredAndSelectedByScopeMustBeSet", password, password, "DepartmentAA"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = VerifyProfileTest.getUserByUsername(testRealm(),"attributeRequiredAndSelectedByScopeMustBeSet"); assertEquals("FirstAA", user.getFirstName()); @@ -501,11 +501,11 @@ public void testRegisterUserSuccess_attributeNotRequiredAndSelectedByScopeCanBeI loginPage.clickRegister(); registerPage.assertCurrent(); - Assert.assertTrue(registerPage.isDepartmentPresent()); + Assertions.assertTrue(registerPage.isDepartmentPresent()); registerPage.register("FirstAA", "LastAA", "attributeNotRequiredAndSelectedByScopeCanBeIgnored@email", "attributeNotRequiredAndSelectedByScopeCanBeIgnored", generatePassword()); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); String userId = events.expectRegister("attributeNotRequiredAndSelectedByScopeCanBeIgnored", "attributeNotRequiredAndSelectedByScopeCanBeIgnored@email",client_scope_optional.getClientId()).assertEvent().getUserId(); UserRepresentation user = getUser(userId); @@ -527,12 +527,12 @@ public void testRegisterUserSuccess_attributeNotRequiredAndSelectedByScopeCanBeS loginPage.clickRegister(); registerPage.assertCurrent(); - Assert.assertTrue(registerPage.isDepartmentPresent()); + Assertions.assertTrue(registerPage.isDepartmentPresent()); final String password = generatePassword(); registerPage.register("FirstAA", "LastAA", "attributeNotRequiredAndSelectedByScopeCanBeSet@email", "attributeNotRequiredAndSelectedByScopeCanBeSet", password, password, "Department AA"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); String userId = events.expectRegister("attributeNotRequiredAndSelectedByScopeCanBeSet", "attributeNotRequiredAndSelectedByScopeCanBeSet@email",client_scope_default.getClientId()).assertEvent().getUserId(); UserRepresentation user = getUser(userId); @@ -554,11 +554,11 @@ public void testRegisterUserSuccess_attributeRequiredButNotSelectedByScopeIsNotR loginPage.clickRegister(); registerPage.assertCurrent(); - Assert.assertFalse(registerPage.isDepartmentPresent()); + Assertions.assertFalse(registerPage.isDepartmentPresent()); registerPage.register("FirstAA", "LastAA", "attributeRequiredButNotSelectedByScopeIsNotRendered@email", "attributeRequiredButNotSelectedByScopeIsNotRendered", generatePassword()); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); String userId = events.expectRegister("attributeRequiredButNotSelectedByScopeIsNotRendered", "attributeRequiredButNotSelectedByScopeIsNotRendered@email",client_scope_optional.getClientId()).assertEvent().getUserId(); UserRepresentation user = getUser(userId); @@ -699,10 +699,10 @@ private void assertUserRegistered(String userId, String username, String email, events.expectLogin().detail("username", username.toLowerCase()).user(userId).assertEvent(); UserRepresentation user = getUser(userId); - Assert.assertNotNull(user); - Assert.assertNotNull(user.getCreatedTimestamp()); + Assertions.assertNotNull(user); + Assertions.assertNotNull(user.getCreatedTimestamp()); // test that timestamp is current with 10s tollerance - Assert.assertTrue((System.currentTimeMillis() - user.getCreatedTimestamp()) < 10000); + Assertions.assertTrue((System.currentTimeMillis() - user.getCreatedTimestamp()) < 10000); // test user info is set from form assertThat(username, Matchers.equalToIgnoringCase(user.getUsername())); assertEquals(email.toLowerCase(), user.getEmail()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ResetCredentialsAlternativeFlowsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ResetCredentialsAlternativeFlowsTest.java index a6a343777258..7f39bef2febd 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ResetCredentialsAlternativeFlowsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ResetCredentialsAlternativeFlowsTest.java @@ -54,12 +54,12 @@ import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for the various alternatives of reset-credentials flow or browser flow (non-default setup of the flows) @@ -256,8 +256,8 @@ public void testResetCredentialsFlowWithUsernameProvidedFromBrowserFlow() throws updatePasswordPage.changePassword("resetPassword", "resetPassword"); // Assert user authenticated - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); } finally { revertFlows(); } @@ -276,7 +276,7 @@ private void provideUsernameAndClickResetPassword(String username) { // Assert switched to the "reset-credentials" flow, but button "back" not available resetPasswordPage.assertCurrent(); - Assert.assertTrue(URLUtils.currentUrlMatches("/login-actions/reset-credentials")); + Assertions.assertTrue(URLUtils.currentUrlMatches("/login-actions/reset-credentials")); } @@ -385,7 +385,7 @@ public void resetCredentialsVerifyCustomOtpLabelSetProperly() { // Open OTP Authenticator account page // Check if OTP credential is present - Assert.assertTrue(AccountHelper.totpUserLabelComparator(testRealm(), "login-test", customOtpLabel)); + Assertions.assertTrue(AccountHelper.totpUserLabelComparator(testRealm(), "login-test", customOtpLabel)); // Undo setup changes performed within the test } finally { @@ -428,7 +428,7 @@ public void deviceNameOptionalForFirstOTPCredentialButRequiredForEachNextOne() { totpPage.configure(totp.generateTOTP(totpPage.getTotpSecret()), emptyOtpLabel); assertKcActionStatus(SUCCESS); - Assert.assertTrue(AccountHelper.deleteTotpAuthentication(testRealm(), "login-test")); + Assertions.assertTrue(AccountHelper.deleteTotpAuthentication(testRealm(), "login-test")); // Logout oauth.openLogoutForm(); @@ -452,11 +452,11 @@ public void deviceNameOptionalForFirstOTPCredentialButRequiredForEachNextOne() { // Assert user authenticated appPage.assertCurrent(); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); - Assert.assertTrue(AccountHelper.isTotpPresent(testRealm(), "bwilson")); - Assert.assertTrue(AccountHelper.totpUserLabelComparator(testRealm(), "bwilson", "")); + Assertions.assertTrue(AccountHelper.isTotpPresent(testRealm(), "bwilson")); + Assertions.assertTrue(AccountHelper.totpUserLabelComparator(testRealm(), "bwilson", "")); // Logout oauth.openLogoutForm(); @@ -476,22 +476,22 @@ public void deviceNameOptionalForFirstOTPCredentialButRequiredForEachNextOne() { // Try to create another OTP credential with empty label again. This // should fail with error since OTP label is required in this case already totpPage.configure(totp.generateTOTP(totpPage.getTotpSecret()), ""); - Assert.assertTrue(AccountHelper.totpCountEquals(testRealm(), "bwilson", 1)); + Assertions.assertTrue(AccountHelper.totpCountEquals(testRealm(), "bwilson", 1)); // Create 2nd OTP credential with valid (non-empty) Device Name label. This should pass final String secondOtpLabel = "My 2nd OTP device"; totpPage.configure(totp.generateTOTP(totpPage.getTotpSecret()), secondOtpLabel); // Assert user authenticated appPage.assertCurrent(); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); // Verify 2nd OTP credential was successfully created too - Assert.assertTrue(AccountHelper.totpUserLabelComparator(testRealm(), "bwilson", secondOtpLabel)); + Assertions.assertTrue(AccountHelper.totpUserLabelComparator(testRealm(), "bwilson", secondOtpLabel)); // Remove both OTP credentials - Assert.assertTrue(AccountHelper.deleteTotpAuthentication(testRealm(), "bwilson")); - Assert.assertTrue(AccountHelper.deleteTotpAuthentication(testRealm(), "bwilson")); + Assertions.assertTrue(AccountHelper.deleteTotpAuthentication(testRealm(), "bwilson")); + Assertions.assertTrue(AccountHelper.deleteTotpAuthentication(testRealm(), "bwilson")); // Logout oauth.openLogoutForm(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ResetPasswordTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ResetPasswordTest.java index f1a26443b5d5..08f7597fdbdc 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ResetPasswordTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ResetPasswordTest.java @@ -93,10 +93,10 @@ import org.hamcrest.Matchers; import org.jboss.arquillian.drone.api.annotation.Drone; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; @@ -108,8 +108,8 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author Stian Thorgersen @@ -257,7 +257,7 @@ private void openResetPasswordUrlAndDoFlow(String resetUri, String expectedClien updatePasswordPage.assertCurrent(); if(userAuthenticated) { - assertFalse("Logout other sessions was ticked", updatePasswordPage.isLogoutSessionsChecked()); + assertFalse(updatePasswordPage.isLogoutSessionsChecked(), "Logout other sessions was ticked"); } else { updatePasswordPage.checkLogoutSessions(); } @@ -317,17 +317,17 @@ public void resetPasswordLinkErrorFlows() { // Client not found driver.navigate().to(oauth.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials?client_id=not_found"); errorPage.assertCurrent(); - Assert.assertEquals("Client not found.", errorPage.getError()); + Assertions.assertEquals("Client not found.", errorPage.getError()); // Redirect_uri without client driver.navigate().to(oauth.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials?redirect_uri=https://foo/bar/"); errorPage.assertCurrent(); - Assert.assertEquals("Missing parameters: client_id", errorPage.getError()); + Assertions.assertEquals("Missing parameters: client_id", errorPage.getError()); // Incorrect redirect_uri driver.navigate().to(oauth.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials?client_id=test-app&redirect_uri=https://foo/bar/"); errorPage.assertCurrent(); - Assert.assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); + Assertions.assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); // Client disabled ClientResource client = AdminApiUtil.findClientByClientId(testRealm(), "test-app"); @@ -336,7 +336,7 @@ public void resetPasswordLinkErrorFlows() { client.update(clientRep); try { driver.navigate().to(oauth.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials?client_id=test-app"); - Assert.assertEquals("Client disabled.", errorPage.getError()); + Assertions.assertEquals("Client disabled.", errorPage.getError()); } finally { clientRep.setEnabled(true); client.update(clientRep); @@ -414,7 +414,7 @@ public void resetPasswordForceLoginFederatedUser() throws IOException { user.setEmail("login@test.com"); user.setFederationLink(componentId); this.userId = ApiUtil.getCreatedId(testRealm().users().create(user)); - Assert.assertFalse(StorageId.isLocalStorage(userId)); + Assertions.assertFalse(StorageId.isLocalStorage(userId)); // by default federated users are force to re-login resetPassword("login-test", "resetPassword", true); @@ -569,10 +569,10 @@ private String resetPassword(String username, String password, boolean relogin) if (relogin) { // relogin is forced therefore the info page should be displayed - Assert.assertEquals("Your account has been updated.", infoPage.getInfo()); + Assertions.assertEquals("Your account has been updated.", infoPage.getInfo()); String backToAppLink = infoPage.getBackToApplicationLink(); ClientRepresentation client = AdminApiUtil.findClientByClientId(adminClient.realm("test"), "test-app").toRepresentation(); - Assert.assertEquals(backToAppLink, client.getBaseUrl()); + Assertions.assertEquals(backToAppLink, client.getBaseUrl()); oauth.openLoginForm(); loginPage.assertCurrent(); } else { @@ -850,9 +850,9 @@ public void resetPasswordExpiredCodeAndAuthSession() throws IOException { driver.navigate().to(changePasswordUrl.trim()); errorPage.assertCurrent(); - Assert.assertEquals("Action expired.", errorPage.getError()); + Assertions.assertEquals("Action expired.", errorPage.getError()); String backToAppLink = errorPage.getBackToApplicationLink(); - Assert.assertTrue(backToAppLink.endsWith("/app/auth")); + Assertions.assertTrue(backToAppLink.endsWith("/app/auth")); events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent(); } finally { @@ -893,9 +893,9 @@ public void resetPasswordExpiredCodeAndAuthSessionPerActionLifespan() throws IOE URLUtils.navigateToUri(changePasswordUrl.trim()); errorPage.assertCurrent(); - Assert.assertEquals("Action expired.", errorPage.getError()); + Assertions.assertEquals("Action expired.", errorPage.getError()); String backToAppLink = errorPage.getBackToApplicationLink(); - Assert.assertTrue(backToAppLink.endsWith("/app/auth")); + Assertions.assertTrue(backToAppLink.endsWith("/app/auth")); events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent(); } finally { @@ -937,9 +937,9 @@ public void resetPasswordExpiredCodeAndAuthSessionPerActionMultipleTimeouts() th driver.navigate().to(changePasswordUrl.trim()); errorPage.assertCurrent(); - Assert.assertEquals("Action expired.", errorPage.getError()); + Assertions.assertEquals("Action expired.", errorPage.getError()); String backToAppLink = errorPage.getBackToApplicationLink(); - Assert.assertTrue(backToAppLink.endsWith("/app/auth")); + Assertions.assertTrue(backToAppLink.endsWith("/app/auth")); events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent(); } finally { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/RestartCookieTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/RestartCookieTest.java index 0d31be393741..f0bd5a30a2e6 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/RestartCookieTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/RestartCookieTest.java @@ -49,7 +49,6 @@ import org.keycloak.representations.idm.ComponentRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.pages.LoginPage; import org.keycloak.testsuite.util.ClientBuilder; @@ -59,9 +58,10 @@ import org.jboss.arquillian.graphene.page.Page; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.Cookie; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Marek Posolda @@ -125,7 +125,7 @@ protected void afterAbstractKeycloakTestRealmImport() { rep.setConfig(config); try (Response res = testRealm().components().add(rep)) { - Assert.assertEquals(Response.Status.CREATED.getStatusCode(), res.getStatus()); + Assertions.assertEquals(Response.Status.CREATED.getStatusCode(), res.getStatus()); } } @@ -157,9 +157,9 @@ public void testRestartCookieParsedOldA128CBCHS256() throws IOException { SecretKey signKey = session.keys().getActiveKey(session.getContext().getRealm(), KeyUse.SIG, sigAlgorithm).getSecretKey(); String encodedJwt = session.tokens().encode(restartLoginCookie); String oldRestartCookie = TokenUtil.jweDirectEncode(encKey, signKey, encodedJwt.getBytes(StandardCharsets.UTF_8)); - Assert.assertNotNull(RestartLoginCookie.decryptAndDecode(session, oldRestartCookie)); + Assertions.assertNotNull(RestartLoginCookie.decryptAndDecode(session, oldRestartCookie)); } catch (Exception e) { - Assert.fail(); + Assertions.fail(); } }); } @@ -182,7 +182,7 @@ public void testRestartCookieWithPar() { requestUri = pResp.getRequestUri(); } catch (Exception e) { - Assert.fail(); + Assertions.fail(); } oauth.redirectUri(null); @@ -207,7 +207,7 @@ private void rotateAesKeys() { } String updatedActiveKid = realm.keys().getKeyMetadata().getActive().get(Algorithm.AES); - Assert.assertNotEquals(activeKid, updatedActiveKid); + Assertions.assertNotEquals(activeKid, updatedActiveKid); } private ComponentRepresentation createComponentRep(String algorithm, String providerId, String realmId, MultivaluedHashMap extra) { @@ -230,9 +230,9 @@ private void assertRestartCookie(String restartCookie) { { try { RestartLoginCookie restartLoginCookie = RestartLoginCookie.decryptAndDecode(session, restartCookie); - Assert.assertFalse(restartLoginCookie.getNotes().keySet().stream().anyMatch(sensitiveNotes::contains)); + Assertions.assertFalse(restartLoginCookie.getNotes().keySet().stream().anyMatch(sensitiveNotes::contains)); } catch (Exception e) { - Assert.fail(); + Assertions.fail(); } }); } @@ -261,7 +261,7 @@ public void testRestartCookieBackwardsCompatible_Keycloak25() throws IOException loginPage.login("foo", "bar"); loginPage.assertCurrent(); - Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); + Assertions.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); events.expectLogin().user((String) null).session((String) null).error(Errors.EXPIRED_CODE).clearDetails() .detail(Details.RESTART_AFTER_TIMEOUT, "true") @@ -294,7 +294,7 @@ public void testRestartCookieBackwardsCompatible_Keycloak19() throws IOException loginPage.login("foo", "bar"); loginPage.assertCurrent(); - Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); + Assertions.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError()); events.expectLogin().user((String) null).session((String) null).error(Errors.EXPIRED_CODE).clearDetails() .detail(Details.RESTART_AFTER_TIMEOUT, "true") diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/SSOTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/SSOTest.java index aab47421cfef..8de003cf9eff 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/SSOTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/SSOTest.java @@ -41,14 +41,14 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.jboss.arquillian.drone.api.annotation.Drone; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebDriver; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stian Thorgersen @@ -78,13 +78,13 @@ public void loginSuccess() { loginPage.login("test-user@localhost", getPassword("test-user@localhost")); assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); EventRepresentation loginEvent = events.expectLogin().assertEvent(); String sessionId = loginEvent.getSessionId(); IDToken idToken = sendTokenRequestAndGetIDToken(loginEvent); - Assert.assertEquals("1", idToken.getAcr()); + Assertions.assertEquals("1", idToken.getAcr()); Long authTime = idToken.getAuth_time(); appPage.open(); @@ -100,9 +100,9 @@ public void loginSuccess() { // acr is 0 as we authenticated through SSO cookie idToken = sendTokenRequestAndGetIDToken(loginEvent); - Assert.assertEquals("0", idToken.getAcr()); + Assertions.assertEquals("0", idToken.getAcr()); // auth time hasn't changed as we authenticated through SSO cookie - Assert.assertEquals(authTime, idToken.getAuth_time()); + Assertions.assertEquals(authTime, idToken.getAuth_time()); appPage.assertCurrent(); @@ -123,8 +123,8 @@ public void multipleSessions() { oauth.openLoginForm(); loginPage.login("test-user@localhost", getPassword("test-user@localhost")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); EventRepresentation login1 = events.expectLogin().assertEvent(); @@ -135,8 +135,8 @@ public void multipleSessions() { EventRepresentation login2 = events.expectLogin().assertEvent(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, RequestType.valueOf(driver2.getTitle())); - Assert.assertNotNull(oauth2.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, RequestType.valueOf(driver2.getTitle())); + Assertions.assertNotNull(oauth2.parseLoginResponse().getCode()); assertNotEquals(login1.getSessionId(), login2.getSessionId()); @@ -151,8 +151,8 @@ public void multipleSessions() { oauth2.openLoginForm(); events.expectLogin().session(login2.getSessionId()).removeDetail(Details.USERNAME).assertEvent(); - Assert.assertEquals(RequestType.AUTH_RESPONSE, RequestType.valueOf(driver2.getTitle())); - Assert.assertNotNull(oauth2.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, RequestType.valueOf(driver2.getTitle())); + Assertions.assertNotNull(oauth2.parseLoginResponse().getCode()); String code = oauth2.parseLoginResponse().getCode(); AccessTokenResponse response = oauth2.doAccessTokenRequest(code); @@ -173,7 +173,7 @@ public void loginWithRequiredActionAddedInTheMeantime() { loginPage.login("test-user@localhost", getPassword("test-user@localhost")); assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); EventRepresentation loginEvent = events.expectLogin().assertEvent(); String sessionId = loginEvent.getSessionId(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ScriptAuthenticatorTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ScriptAuthenticatorTest.java index 758fa28d7b7c..fbf83e64289b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ScriptAuthenticatorTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ScriptAuthenticatorTest.java @@ -40,11 +40,11 @@ import org.keycloak.testsuite.util.UserBuilder; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.common.Profile.Feature.AUTHORIZATION; @@ -122,7 +122,7 @@ public void configureFlows() throws Exception { .build(); Response createFlowResponse = testRealm().flows().createFlow(scriptBrowserFlow); - Assert.assertEquals(201, createFlowResponse.getStatus()); + Assertions.assertEquals(201, createFlowResponse.getStatus()); RealmRepresentation realm = testRealm().toRepresentation(); realm.setBrowserFlow(scriptFlow); @@ -146,11 +146,11 @@ public void configureFlows() throws Exception { .build(); Response addExecutionResponse = testRealm().flows().addExecution(usernamePasswordFormExecution); - Assert.assertEquals(201, addExecutionResponse.getStatus()); + Assertions.assertEquals(201, addExecutionResponse.getStatus()); addExecutionResponse.close(); addExecutionResponse = testRealm().flows().addExecution(authScriptExecution); - Assert.assertEquals(201, addExecutionResponse.getStatus()); + Assertions.assertEquals(201, addExecutionResponse.getStatus()); addExecutionResponse.close(); testContext.setInitialized(true); @@ -193,7 +193,7 @@ public void scriptWithClientSession() { .build(); Response addExecutionResponse = testRealm().flows().addExecution(authScriptExecution); - Assert.assertEquals(201, addExecutionResponse.getStatus()); + Assertions.assertEquals(201, addExecutionResponse.getStatus()); addExecutionResponse.close(); oauth.openLoginForm(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ThemeSelectorTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ThemeSelectorTest.java index 7f2248763793..3c4f11f82a55 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ThemeSelectorTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ThemeSelectorTest.java @@ -9,7 +9,7 @@ import org.jboss.arquillian.graphene.page.Page; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class ThemeSelectorTest extends AbstractTestRealmKeycloakTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/TransientSessionTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/TransientSessionTest.java index cccfb632b40a..fcffcd3f250a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/TransientSessionTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/TransientSessionTest.java @@ -24,18 +24,18 @@ import org.keycloak.representations.RefreshToken; import org.keycloak.services.managers.AuthenticationManager; import org.keycloak.testsuite.AbstractChangeImportedUserPasswordsTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.util.FlowUtil; import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.models.AuthenticationExecutionModel.Requirement.REQUIRED; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Test for transient user session @@ -69,9 +69,9 @@ public void loginSuccess() throws Exception { // Refresh will fail. There is no userSession on the server AccessTokenResponse refreshedResponse = oauth.doRefreshTokenRequest(response.getRefreshToken()); - Assert.assertNull(refreshedResponse.getAccessToken()); + Assertions.assertNull(refreshedResponse.getAccessToken()); assertNotNull(refreshedResponse.getError()); - Assert.assertEquals("Session not active", refreshedResponse.getErrorDescription()); + Assertions.assertEquals("Session not active", refreshedResponse.getErrorDescription()); } private void setUpDirectGrantFlowWithSetClientNoteAuthenticator() { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/VerifyProfileTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/VerifyProfileTest.java index 2dd0494385f8..8af821b7eebb 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/VerifyProfileTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/VerifyProfileTest.java @@ -57,9 +57,9 @@ import org.apache.commons.lang3.StringUtils; import org.jboss.arquillian.graphene.page.Page; import org.jboss.arquillian.test.api.ArquillianResource; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; @@ -73,9 +73,9 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Vlastimil Elias @@ -178,11 +178,11 @@ public void testDisplayName() { //assert field names // i18n replaced - Assert.assertEquals("First name",verifyProfilePage.getLabelForField("firstName")); + Assertions.assertEquals("First name",verifyProfilePage.getLabelForField("firstName")); // attribute name used if no display name set - Assert.assertEquals("lastName",verifyProfilePage.getLabelForField("lastName")); + Assertions.assertEquals("lastName",verifyProfilePage.getLabelForField("lastName")); // direct value in display name - Assert.assertEquals("Department",verifyProfilePage.getLabelForField("department")); + Assertions.assertEquals("Department",verifyProfilePage.getLabelForField("department")); } @Test @@ -319,17 +319,17 @@ public void testDefaultProfile() { //submit with error verifyProfilePage.assertCurrent(); - Assert.assertFalse(verifyProfilePage.isDepartmentPresent()); + Assertions.assertFalse(verifyProfilePage.isDepartmentPresent()); verifyProfilePage.update("First", " "); //submit OK verifyProfilePage.assertCurrent(); - Assert.assertFalse(verifyProfilePage.isDepartmentPresent()); + Assertions.assertFalse(verifyProfilePage.isDepartmentPresent()); verifyProfilePage.update("First", "Last"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUser(userId); assertEquals("First", user.getFirstName()); @@ -493,8 +493,8 @@ public void testOptionalAttribute() { verifyProfilePage.assertCurrent(); verifyProfilePage.update("First", ""); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUser(user2Id); assertEquals("First", user.getFirstName()); @@ -524,8 +524,8 @@ public void testCustomValidationLastName() { //submit OK verifyProfilePage.update("First", "Last"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUser(user5Id); assertEquals("First", user.getFirstName()); @@ -548,8 +548,8 @@ public void testNoActionIfNoValidationError() { oauth.openLoginForm(); loginPage.login("login-test5", getPassword("login-test5")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); } @Test @@ -573,8 +573,8 @@ public void testDoNotValidateUsernameWhenRegistrationAsEmailEnabled() { oauth.openLoginForm(); loginPage.login("login6@test.com", getPassword("login-test6")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); } finally { realm.setRegistrationEmailAsUsername(false); realmResource.update(realm); @@ -594,14 +594,14 @@ public void testRequiredReadOnlyAttribute() { loginPage.login("login-test3", getPassword("login-test3")); verifyProfilePage.assertCurrent(); - Assert.assertEquals("ExistingLast", verifyProfilePage.getLastName()); - Assert.assertFalse(verifyProfilePage.isDepartmentEnabled()); + Assertions.assertEquals("ExistingLast", verifyProfilePage.getLastName()); + Assertions.assertFalse(verifyProfilePage.isDepartmentEnabled()); //update of the other attributes must be successful in this case verifyProfilePage.update("First", "Last"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUser(user3Id); assertEquals("First", user.getFirstName()); @@ -622,8 +622,8 @@ public void testAdminOnlyAttributeNotVisibleToUser() { loginPage.login("login-test6", getPassword("login-test6")); verifyProfilePage.assertCurrent(); - Assert.assertEquals("ExistingLast", verifyProfilePage.getLastName()); - Assert.assertFalse("Admin-only attribute should not be visible for user", verifyProfilePage.isDepartmentPresent()); + Assertions.assertEquals("ExistingLast", verifyProfilePage.getLastName()); + Assertions.assertFalse(verifyProfilePage.isDepartmentPresent(), "Admin-only attribute should not be visible for user"); } @@ -641,9 +641,9 @@ public void testUsernameReadOnlyInProfile() { loginPage.login("login-test6", getPassword("login-test6")); verifyProfilePage.assertCurrent(); - Assert.assertEquals("ExistingLast", verifyProfilePage.getLastName()); + Assertions.assertEquals("ExistingLast", verifyProfilePage.getLastName()); - Assert.assertFalse("username should not be editable by user", verifyProfilePage.isUsernameEnabled()); + Assertions.assertFalse(verifyProfilePage.isUsernameEnabled(), "username should not be editable by user"); } @Test @@ -660,9 +660,9 @@ public void testUsernameReadNotVisibleInProfile() { loginPage.login("login-test6", getPassword("login-test6")); verifyProfilePage.assertCurrent(); - Assert.assertEquals("ExistingLast", verifyProfilePage.getLastName()); + Assertions.assertEquals("ExistingLast", verifyProfilePage.getLastName()); - Assert.assertFalse("username should not be shown to user", verifyProfilePage.isUsernamePresent()); + Assertions.assertFalse(verifyProfilePage.isUsernamePresent(), "username should not be shown to user"); } @Test @@ -688,8 +688,8 @@ public void testEMailRequiredInProfileWithLocalPartLength() { // set e-mail, update firstname/lastname and complete login verifyProfilePage.updateEmail("abcdef0123456789@bar.com", "HasNowMailFirst", "HasNowMailLast"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUser(userWithoutEmailId); assertEquals("HasNowMailFirst", user.getFirstName()); @@ -710,14 +710,14 @@ public void testAttributeNotVisible() { loginPage.login("login-test4", getPassword("login-test4")); verifyProfilePage.assertCurrent(); - Assert.assertEquals("ExistingLast", verifyProfilePage.getLastName()); - Assert.assertFalse("'department' field is visible" , verifyProfilePage.isDepartmentPresent()); + Assertions.assertEquals("ExistingLast", verifyProfilePage.getLastName()); + Assertions.assertFalse(verifyProfilePage.isDepartmentPresent(), "'department' field is visible" ); //update of the other attributes must be successful in this case verifyProfilePage.update("First", "Last"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUser(user4Id); assertEquals("First", user.getFirstName()); @@ -748,8 +748,8 @@ public void testRequiredAttribute() { //submit OK verifyProfilePage.update("FirstCC", "LastCC", "DepartmentCC"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUser(user5Id); assertEquals("FirstCC", user.getFirstName()); @@ -782,8 +782,8 @@ public void testRequiredOnlyIfUser() { verifyProfilePage.update("FirstCC", "LastCC", "DepartmentCC"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUser(user5Id); assertEquals("FirstCC", user.getFirstName()); @@ -806,8 +806,8 @@ public void testAttributeNotRequiredWhenMissingScope() { loginPage.login("login-test5", getPassword("login-test5")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUser(user5Id); assertEquals("ExistingFirst", user.getFirstName()); @@ -834,8 +834,8 @@ public void testAttributeRequiredForScope() { verifyProfilePage.update("FirstAA", "LastAA", "DepartmentAA"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUser(user5Id); assertEquals("FirstAA", user.getFirstName()); @@ -868,8 +868,8 @@ public void testAttributeRequiredForDefaultScope() { //submit OK verifyProfilePage.update("FirstBB", "LastBB", "DepartmentBB"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUser(user5Id); assertEquals("FirstBB", user.getFirstName()); @@ -893,8 +893,8 @@ public void testNoActionIfValidForScope() { loginPage.assertCurrent(); loginPage.login("login-test5", getPassword("login-test5")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUser(user5Id); assertEquals("ExistingFirst", user.getFirstName()); @@ -919,8 +919,8 @@ public void testAttributeRequiredButNotSelectedByScopeDoesntForceVerificationScr loginPage.assertCurrent(); loginPage.login("login-test5", getPassword("login-test5")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); } @Test @@ -944,8 +944,8 @@ public void testAttributeRequiredAndSelectedByScope() { verifyProfilePage.update("FirstAA", "LastAA", "DepartmentAA"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUser(user5Id); assertEquals("FirstAA", user.getFirstName()); @@ -972,11 +972,11 @@ public void testAttributeNotRequiredAndSelectedByScopeCanBeUpdatedFromVerificati verifyProfilePage.assertCurrent(); - Assert.assertTrue(verifyProfilePage.isDepartmentPresent()); + Assertions.assertTrue(verifyProfilePage.isDepartmentPresent()); verifyProfilePage.update("FirstAA", "LastAA", "Department AA"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUser(user5Id); assertEquals("FirstAA", user.getFirstName()); @@ -1003,11 +1003,11 @@ public void testAttributeRequiredButNotSelectedByScopeIsNotRenderedOnVerificatio verifyProfilePage.assertCurrent(); - Assert.assertFalse(verifyProfilePage.isDepartmentPresent()); + Assertions.assertFalse(verifyProfilePage.isDepartmentPresent()); verifyProfilePage.update("FirstAA", "LastAA"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUser(user5Id); assertEquals("FirstAA", user.getFirstName()); @@ -1040,8 +1040,8 @@ public void testCustomValidationInCustomAttribute() { verifyProfilePage.update("FirstCC", "LastCC", "DepartmentCC"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUser(user5Id); assertEquals("FirstCC", user.getFirstName()); @@ -1067,8 +1067,8 @@ public void testEmailChangeSetsEmailVerified() { //submit OK verifyProfilePage.updateEmail("newemail@test.org","FirstCC", "LastCC"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); UserRepresentation user = getUser(user5Id); assertEquals("newemail@test.org", user.getEmail()); @@ -1090,8 +1090,8 @@ public void testNoActionIfSuccessfulValidationForCustomAttribute() { oauth.openLoginForm(); loginPage.login("login-test5", getPassword("login-test5")); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); } @Test @@ -1128,9 +1128,9 @@ protected UPConfig setUserProfileConfiguration(String configuration) { UPConfig result = UserProfileUtil.setUserProfileConfiguration(testRealm(), configuration); AdminEventRepresentation adminEvent = assertAdminEvents.assertEvent(TEST_REALM_NAME, OperationType.UPDATE, AdminEventPaths.userProfilePath(), ResourceType.USER_PROFILE); - Assert.assertTrue("Incorrect representation in event", StringUtils.isBlank(configuration) + Assertions.assertTrue(StringUtils.isBlank(configuration) ? StringUtils.isBlank(adminEvent.getRepresentation()) - : StringUtils.isNotBlank(adminEvent.getRepresentation())); + : StringUtils.isNotBlank(adminEvent.getRepresentation()), "Incorrect representation in event"); return result; } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/login/ConditionalCredentialAuthenticatorTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/login/ConditionalCredentialAuthenticatorTest.java index f6f053cc480d..270bbee51e08 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/login/ConditionalCredentialAuthenticatorTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/login/ConditionalCredentialAuthenticatorTest.java @@ -39,9 +39,9 @@ import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @@ -209,10 +209,10 @@ private void configureConditionalCurrentCredentialFlow(Boolean included, String. private void checkLoginOk(String username) { String code = oauth.parseLoginResponse().getCode(); - Assert.assertNotNull(code); + Assertions.assertNotNull(code); AccessTokenResponse res = oauth.doAccessTokenRequest(code); - Assert.assertNull(res.getError()); - Assert.assertNotNull(res.getAccessToken()); + Assertions.assertNull(res.getError()); + Assertions.assertNotNull(res.getAccessToken()); events.expectLogin().user(AssertEvents.isUUID()).detail(Details.USERNAME, username).assertEvent(); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/login/ConditionalSubFlowExecutedAuthenticatorTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/login/ConditionalSubFlowExecutedAuthenticatorTest.java index f78877e3fdce..8bfaa46c80ef 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/login/ConditionalSubFlowExecutedAuthenticatorTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/login/ConditionalSubFlowExecutedAuthenticatorTest.java @@ -39,9 +39,9 @@ import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** *

Test for the ConditionalSubFlowExecutedAuthenticator. A test parent @@ -142,17 +142,17 @@ public void testWithInvalidFlowNotExecuted() { private void checkDenied() { errorPage.assertCurrent(); - Assert.assertEquals("Access denied", errorPage.getError()); + Assertions.assertEquals("Access denied", errorPage.getError()); events.expect(EventType.LOGIN_ERROR).user((String) null).error(Errors.ACCESS_DENIED).assertEvent(); } private void checkAllowed(String username) { String code = oauth.parseLoginResponse().getCode(); - Assert.assertNotNull(code); + Assertions.assertNotNull(code); AccessTokenResponse res = oauth.doAccessTokenRequest(code); - Assert.assertNull(res.getError()); - Assert.assertNotNull(res.getAccessToken()); + Assertions.assertNull(res.getError()); + Assertions.assertNotNull(res.getAccessToken()); events.expectLogin().user(AssertEvents.isUUID()).detail(Details.USERNAME, username).assertEvent(); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/AbstractMigrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/AbstractMigrationTest.java index 84526c7b23e2..7128ba224bfb 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/AbstractMigrationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/AbstractMigrationTest.java @@ -99,6 +99,7 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.apache.xml.security.encryption.XMLCipher; import org.hamcrest.Matchers; +import org.junit.jupiter.api.Assertions; import static org.keycloak.migration.migrators.MigrateTo24_0_0.REALM_USER_PROFILE_ENABLED; import static org.keycloak.models.AccountRoles.MANAGE_ACCOUNT; @@ -121,12 +122,12 @@ import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Bill Burke @@ -182,19 +183,19 @@ protected void testRhssoThemes(RealmResource realm) { // check themes are removed RealmRepresentation rep = realm.toRepresentation(); assertThat("Login theme modified for test purposes", rep.getLoginTheme(), anyOf(nullValue(), equalTo(PREFERRED_DEFAULT_LOGIN_THEME))); - Assert.assertNull("Email theme was not modified", rep.getEmailTheme()); + Assertions.assertNull(rep.getEmailTheme(), "Email theme was not modified"); // there should be either new default or left null if not set assertThat("Account theme was not modified", rep.getAccountTheme(), anyOf(equalTo("keycloak.v2"), nullValue())); // check the client theme is also removed List client = realm.clients().findByClientId("migration-saml-client"); - Assert.assertNotNull("migration-saml-client client is missing", client); - Assert.assertEquals("migration-saml-client client is missing", 1, client.size()); - Assert.assertNull("migration-saml-client login theme was not removed", client.get(0).getAttributes().get(DefaultThemeSelectorProvider.LOGIN_THEME_KEY)); + Assertions.assertNotNull(client, "migration-saml-client client is missing"); + Assertions.assertEquals(1, client.size(), "migration-saml-client client is missing"); + Assertions.assertNull(client.get(0).getAttributes().get(DefaultThemeSelectorProvider.LOGIN_THEME_KEY), "migration-saml-client login theme was not removed"); } protected void testHttpChallengeFlow(RealmResource realm) { log.info("testing 'http challenge' flow not present"); - Assert.assertFalse(realm.flows().getFlows() + Assertions.assertFalse(realm.flows().getFlows() .stream() .anyMatch(authFlow -> authFlow.getAlias().equalsIgnoreCase("http challenge"))); } @@ -215,7 +216,7 @@ protected void testRegistrationProfileFormActionRemoved(RealmResource realm) { .filter(flowRep -> DefaultAuthenticationFlows.REGISTRATION_FLOW.equals(flowRep.getAlias())) .findFirst().orElseThrow(() -> new NoSuchElementException("No registration flow in realm " + realm.toRepresentation().getRealm())); - Assert.assertFalse(realm.flows().getExecutions(registrationFlow.getAlias()) + Assertions.assertFalse(realm.flows().getExecutions(registrationFlow.getAlias()) .stream() .anyMatch(execution -> "registration-profile-action".equals(execution.getProviderId()))); } @@ -491,7 +492,7 @@ private void testClientContainsExpectedClientScopes() { assertThat(defaultClientScopes, Matchers.hasItems( SamlProtocolFactory.SCOPE_ROLE_LIST )); - Assert.assertTrue(optionalClientScopes.isEmpty()); + Assertions.assertTrue(optionalClientScopes.isEmpty()); } protected void testDeleteAccount(RealmResource realm) { @@ -616,11 +617,11 @@ private void testFirstBrokerLoginFlowMigrated(RealmResource realm, boolean impor private void testAuthenticationExecution(AuthenticationExecutionInfoRepresentation execution, Boolean expectedAuthenticationFlow, String expectedProviderId, AuthenticationExecutionModel.Requirement expectedRequirement, int expectedLevel, int expectedIndex) { - Assert.assertEquals(execution.getAuthenticationFlow(), expectedAuthenticationFlow); - Assert.assertEquals(execution.getProviderId(), expectedProviderId); - Assert.assertEquals(execution.getRequirement(), expectedRequirement.toString()); - Assert.assertEquals(execution.getLevel(), expectedLevel); - Assert.assertEquals(execution.getIndex(), expectedIndex); + Assertions.assertEquals(execution.getAuthenticationFlow(), expectedAuthenticationFlow); + Assertions.assertEquals(execution.getProviderId(), expectedProviderId); + Assertions.assertEquals(execution.getRequirement(), expectedRequirement.toString()); + Assertions.assertEquals(execution.getLevel(), expectedLevel); + Assertions.assertEquals(execution.getIndex(), expectedIndex); } private void testDecisionStrategySetOnResourceServer() { @@ -646,12 +647,12 @@ private void testCliConsoleScopeSize(RealmResource realm) { ClientRepresentation cli = realm.clients().findByClientId(Constants.ADMIN_CLI_CLIENT_ID).get(0); ClientRepresentation console = realm.clients().findByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID).get(0); MappingsRepresentation scopeMappings = realm.clients().get(console.getId()).getScopeMappings().getAll(); - Assert.assertNull(scopeMappings.getClientMappings()); - Assert.assertNull(scopeMappings.getRealmMappings()); + Assertions.assertNull(scopeMappings.getClientMappings()); + Assertions.assertNull(scopeMappings.getRealmMappings()); scopeMappings = realm.clients().get(cli.getId()).getScopeMappings().getAll(); - Assert.assertNull(scopeMappings.getClientMappings()); - Assert.assertNull(scopeMappings.getRealmMappings()); + Assertions.assertNull(scopeMappings.getClientMappings()); + Assertions.assertNull(scopeMappings.getRealmMappings()); } protected void testDockerAuthenticationFlow(RealmResource... realms) { @@ -807,7 +808,7 @@ protected void testAuthorizationServices(RealmResource... realms) { for (String roleName : Constants.AUTHZ_DEFAULT_AUTHORIZATION_ROLES) { RoleResource role = realm.roles().get(roleName); //throws javax.ws.rs.NotFoundException if not found - assertFalse("Role shouldn't be composite should be false.", role.toRepresentation().isComposite()); + assertFalse(role.toRepresentation().isComposite(), "Role shouldn't be composite should be false."); assertThat("role should be added to default roles for new users", realm.roles().get(Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + realm.toRepresentation().getRealm().toLowerCase()).getRoleComposites().stream() .map(RoleRepresentation::getName).collect(Collectors.toSet()), hasItem(roleName)); @@ -823,8 +824,8 @@ protected void testAuthorizationServices(RealmResource... realms) { for (RoleRepresentation role : realm.roles().get(AdminRoles.ADMIN).getRoleComposites()) { roleNames.add(role.getName()); } - assertTrue(AdminRoles.VIEW_AUTHORIZATION + " should be composite role of " + AdminRoles.ADMIN, roleNames.contains(AdminRoles.VIEW_AUTHORIZATION)); - assertTrue(AdminRoles.MANAGE_AUTHORIZATION + " should be composite role of " + AdminRoles.ADMIN, roleNames.contains(AdminRoles.MANAGE_AUTHORIZATION)); + assertTrue(roleNames.contains(AdminRoles.VIEW_AUTHORIZATION), AdminRoles.VIEW_AUTHORIZATION + " should be composite role of " + AdminRoles.ADMIN); + assertTrue(roleNames.contains(AdminRoles.MANAGE_AUTHORIZATION), AdminRoles.MANAGE_AUTHORIZATION + " should be composite role of " + AdminRoles.ADMIN); } } } @@ -834,7 +835,7 @@ protected void testNameOfOTPRequiredAction(RealmResource... realms) { for (RealmResource realm : realms) { RequiredActionProviderRepresentation otpAction = realm.flows().getRequiredAction(UserModel.RequiredAction.CONFIGURE_TOTP.name()); - assertEquals("The name of CONFIGURE_TOTP required action should be 'Configure OTP'.", "Configure OTP", otpAction.getName()); + assertEquals("Configure OTP", otpAction.getName(), "The name of CONFIGURE_TOTP required action should be 'Configure OTP'."); } } @@ -846,8 +847,8 @@ protected void testIdentityProviderAuthenticator(RealmResource... realms) { if (flow.getAlias().equals(DefaultAuthenticationFlows.BROWSER_FLOW)) { for (AuthenticationExecutionExportRepresentation execution : flow.getAuthenticationExecutions()) { if ("identity-provider-redirector".equals(execution.getAuthenticator())) { - assertEquals("Requirement should be ALTERNATIVE.", AuthenticationExecutionModel.Requirement.ALTERNATIVE.name(), execution.getRequirement()); - assertTrue("Priority should be 25.", execution.getPriority() == 25); + assertEquals(AuthenticationExecutionModel.Requirement.ALTERNATIVE.name(), execution.getRequirement(), "Requirement should be ALTERNATIVE."); + assertTrue(execution.getPriority() == 25, "Priority should be 25."); success = true; } } @@ -881,9 +882,8 @@ protected void testUpdateProtocolMappers(RealmResource... realms) { protected void testUpdateProtocolMapper(ProtocolMapperRepresentation protocolMapper, String clientId) { if (protocolMapper.getConfig().get("id.token.claim") != null) { - assertEquals("ProtocolMapper's config should contain key 'userinfo.token.claim'. But it doesn't for protocolMapper '" - + protocolMapper.getName() + "' of client/clientScope '" + clientId + "'", - protocolMapper.getConfig().get("id.token.claim"), protocolMapper.getConfig().get("userinfo.token.claim")); + assertEquals(protocolMapper.getConfig().get("id.token.claim"), protocolMapper.getConfig().get("userinfo.token.claim"), "ProtocolMapper's config should contain key 'userinfo.token.claim'. But it doesn't for protocolMapper '" + + protocolMapper.getName() + "' of client/clientScope '" + clientId + "'"); } } @@ -891,15 +891,15 @@ protected void testDuplicateEmailSupport(RealmResource... realms) { log.info("testing duplicate email"); for (RealmResource realm : realms) { RealmRepresentation rep = realm.toRepresentation(); - assertTrue("LoginWithEmailAllowed should be enabled.", rep.isLoginWithEmailAllowed()); - assertFalse("DuplicateEmailsAllowed should be disabled.", rep.isDuplicateEmailsAllowed()); + assertTrue(rep.isLoginWithEmailAllowed(), "LoginWithEmailAllowed should be enabled."); + assertFalse(rep.isDuplicateEmailsAllowed(), "DuplicateEmailsAllowed should be disabled."); } } protected void testOfflineTokenLogin() throws Exception { log.info("test login with old offline token"); String oldOfflineToken = suiteContext.getMigrationContext().loadOfflineToken(); - Assert.assertNotNull(oldOfflineToken); + Assertions.assertNotNull(oldOfflineToken); oauth.realm(MIGRATION); oauth.client("migration-test-client", "secret"); @@ -909,7 +909,7 @@ protected void testOfflineTokenLogin() throws Exception { String errorMessage = String.format("Error when refreshing offline token. Error: %s, Error details: %s, offline token from previous version: %s", response.getError(), response.getErrorDescription(), oldOfflineToken); log.error(errorMessage); - Assert.fail(errorMessage); + Assertions.fail(errorMessage); } AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); @@ -958,7 +958,7 @@ private void testOfflineScopeAddedToClient() { }).findFirst().isPresent(); if (!found) { - Assert.fail("Offline_access not found as optional scope of client migration-test-client"); + Assertions.fail("Offline_access not found as optional scope of client migration-test-client"); } } @@ -973,10 +973,10 @@ private void testRolesAndWebOriginsScopesAddedToClient() { .collect(Collectors.toSet()); if (!defaultClientScopeNames.contains(OIDCLoginProtocolFactory.ROLES_SCOPE)) { - Assert.fail("Client scope 'roles' not found as default scope of client migration-test-client"); + Assertions.fail("Client scope 'roles' not found as default scope of client migration-test-client"); } if (!defaultClientScopeNames.contains(OIDCLoginProtocolFactory.WEB_ORIGINS_SCOPE)) { - Assert.fail("Client scope 'web-origins' not found as default scope of client migration-test-client"); + Assertions.fail("Client scope 'web-origins' not found as default scope of client migration-test-client"); } } @@ -994,7 +994,7 @@ private void testMicroprofileJWTScopeAddedToClient() { .collect(Collectors.toSet()); if (!defaultClientScopeNames.contains(OIDCLoginProtocolFactory.MICROPROFILE_JWT_SCOPE)) { - Assert.fail("Client scope 'microprofile-jwt' not found as optional scope of client migration-test-client"); + Assertions.fail("Client scope 'microprofile-jwt' not found as optional scope of client migration-test-client"); } } @@ -1028,17 +1028,17 @@ protected void testCredentialsMigratedToNewFormat() { // Try invalid password first AccessTokenResponse response = oauth.passwordGrantRequest("migration-test-user", "password").otp(otp).send(); - Assert.assertNull(response.getAccessToken()); - Assert.assertNotNull(response.getError()); + Assertions.assertNull(response.getAccessToken()); + Assertions.assertNotNull(response.getError()); // Try invalid OTP then response = oauth.passwordGrantRequest("migration-test-user", "password2").otp("invalid").send(); - Assert.assertNull(response.getAccessToken()); - Assert.assertNotNull(response.getError()); + Assertions.assertNull(response.getAccessToken()); + Assertions.assertNotNull(response.getError()); // Try successful login now response = oauth.passwordGrantRequest("migration-test-user", "password2").otp(otp).send(); - Assert.assertNull(response.getError()); + Assertions.assertNull(response.getError()); AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); assertEquals("migration-test-user", accessToken.getPreferredUsername()); } catch (Exception e) { @@ -1073,19 +1073,19 @@ private void testOTPExecutionMigratedToConditionalFlow(String topFlowAlias, Stri throw new AssertionError("Not found subflow with displayName '" + expectedOTPSubflowAlias + "' in the flow " + topFlowAlias); } - Assert.assertEquals(AuthenticationExecutionModel.Requirement.CONDITIONAL.toString(), subflowExecution.getRequirement()); + Assertions.assertEquals(AuthenticationExecutionModel.Requirement.CONDITIONAL.toString(), subflowExecution.getRequirement()); AuthenticationExecutionInfoRepresentation childEx1 = authExecutions.get(counter + 1); - Assert.assertEquals("Condition - user configured", childEx1.getDisplayName()); - Assert.assertEquals(AuthenticationExecutionModel.Requirement.REQUIRED.toString(), childEx1.getRequirement()); - Assert.assertEquals(0, childEx1.getIndex()); - Assert.assertEquals(subflowExecution.getLevel() + 1, childEx1.getLevel()); + Assertions.assertEquals("Condition - user configured", childEx1.getDisplayName()); + Assertions.assertEquals(AuthenticationExecutionModel.Requirement.REQUIRED.toString(), childEx1.getRequirement()); + Assertions.assertEquals(0, childEx1.getIndex()); + Assertions.assertEquals(subflowExecution.getLevel() + 1, childEx1.getLevel()); AuthenticationExecutionInfoRepresentation childEx2 = authExecutions.get(counter + 2); - Assert.assertEquals(expectedOTPExecutionDisplayName, childEx2.getDisplayName()); - Assert.assertEquals(AuthenticationExecutionModel.Requirement.REQUIRED.toString(), childEx2.getRequirement()); - Assert.assertEquals(1, childEx2.getIndex()); - Assert.assertEquals(subflowExecution.getLevel() + 1, childEx2.getLevel()); + Assertions.assertEquals(expectedOTPExecutionDisplayName, childEx2.getDisplayName()); + Assertions.assertEquals(AuthenticationExecutionModel.Requirement.REQUIRED.toString(), childEx2.getRequirement()); + Assertions.assertEquals(1, childEx2.getIndex()); + Assertions.assertEquals(subflowExecution.getLevel() + 1, childEx2.getLevel()); } protected void testUserLocaleActionAdded(RealmResource realm) { @@ -1205,7 +1205,7 @@ protected void testResourceTag() { protected void testAlwaysDisplayInConsole() { for(ClientRepresentation clientRep : masterRealm.clients().findAll()) { - Assert.assertFalse(clientRep.isAlwaysDisplayInConsole()); + Assertions.assertFalse(clientRep.isAlwaysDisplayInConsole()); } } @@ -1322,31 +1322,31 @@ private void testLdapUseTruststoreSpiMigration(final RealmResource realm) { private void testHS512KeyCreated(RealmResource realm) { List keyProviders = realm.components().query(realm.toRepresentation().getId(), KeyProvider.class.getName()); - Assert.assertTrue("Old HS256 key provider does not exists", - keyProviders.stream().anyMatch(c -> "hmac-generated".equals(c.getProviderId()) - && c.getConfig().getFirst("algorithm").equals(Algorithm.HS256))); - Assert.assertTrue("New HS512 key provider does not exists", - keyProviders.stream().anyMatch(c -> "hmac-generated".equals(c.getProviderId()) - && c.getConfig().getFirst("algorithm").equals(Algorithm.HS512))); + Assertions.assertTrue(keyProviders.stream().anyMatch(c -> "hmac-generated".equals(c.getProviderId()) + && c.getConfig().getFirst("algorithm").equals(Algorithm.HS256)), + "Old HS256 key provider does not exists"); + Assertions.assertTrue(keyProviders.stream().anyMatch(c -> "hmac-generated".equals(c.getProviderId()) + && c.getConfig().getFirst("algorithm").equals(Algorithm.HS512)), + "New HS512 key provider does not exists"); KeysMetadataRepresentation keysMetadata = realm.keys().getKeyMetadata(); - Assert.assertNotNull("Old HS256 key does not exist", keysMetadata.getActive().get(Algorithm.HS256)); - Assert.assertNotNull("New HS256 key does not exist", keysMetadata.getActive().get(Algorithm.HS512)); + Assertions.assertNotNull(keysMetadata.getActive().get(Algorithm.HS256), "Old HS256 key does not exist"); + Assertions.assertNotNull(keysMetadata.getActive().get(Algorithm.HS512), "New HS256 key does not exist"); } private void testClientAttributes(RealmResource realm) { List clients = realm.clients().findByClientId("migration-saml-client"); - Assert.assertEquals(1, clients.size()); + Assertions.assertEquals(1, clients.size()); ClientRepresentation client = clients.get(0); - Assert.assertNotNull(client.getAttributes().get("saml.artifact.binding.identifier")); - Assert.assertNotNull(client.getAttributes().get("saml_idp_initiated_sso_url_name")); + Assertions.assertNotNull(client.getAttributes().get("saml.artifact.binding.identifier")); + Assertions.assertNotNull(client.getAttributes().get("saml_idp_initiated_sso_url_name")); List clientIds = realm.clients().query("saml.artifact.binding.identifier:\"" + client.getAttributes().get("saml.artifact.binding.identifier") + "\"") .stream().map(ClientRepresentation::getClientId) .collect(Collectors.toList()); - Assert.assertEquals(Collections.singletonList(client.getClientId()), clientIds); + Assertions.assertEquals(Collections.singletonList(client.getClientId()), clientIds); clientIds = realm.clients().query("saml_idp_initiated_sso_url_name:\"" + client.getAttributes().get("saml_idp_initiated_sso_url_name") + "\"") .stream().map(ClientRepresentation::getClientId) .collect(Collectors.toList()); - Assert.assertEquals(Collections.singletonList(client.getClientId()), clientIds); + Assertions.assertEquals(Collections.singletonList(client.getClientId()), clientIds); } private void testDeleteCredentialActionAvailable(RealmResource realm) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/JsonFileImport1301MigrationClientPoliciesTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/JsonFileImport1301MigrationClientPoliciesTest.java index 9a7a6bcf30df..e666d7aea20b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/JsonFileImport1301MigrationClientPoliciesTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/JsonFileImport1301MigrationClientPoliciesTest.java @@ -26,11 +26,11 @@ import org.keycloak.representations.idm.ClientPoliciesRepresentation; import org.keycloak.representations.idm.ClientProfilesRepresentation; import org.keycloak.representations.idm.RealmRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.utils.io.IOUtil; import org.keycloak.util.JsonSerialization; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * This is test only for migration of client policies from Keycloak 13. As the format JSON format of client policies changed between Keycloak 13 and 14 @@ -57,13 +57,13 @@ public void migration13_0_1_Test() throws Exception { RealmRepresentation testRealm = adminClient.realms().realm("test").toRepresentation(); // Stick to null for now. No support for proper migration from Keycloak 13 as client policies was preview and JSON format was changed significantly - Assert.assertTrue(testRealm.getParsedClientProfiles().getProfiles().isEmpty()); - Assert.assertTrue(testRealm.getParsedClientPolicies().getPolicies().isEmpty()); + Assertions.assertTrue(testRealm.getParsedClientProfiles().getProfiles().isEmpty()); + Assertions.assertTrue(testRealm.getParsedClientPolicies().getPolicies().isEmpty()); ClientProfilesRepresentation clientProfiles = adminClient.realms().realm("test").clientPoliciesProfilesResource().getProfiles(false); - Assert.assertTrue(clientProfiles.getProfiles().isEmpty()); + Assertions.assertTrue(clientProfiles.getProfiles().isEmpty()); ClientPoliciesRepresentation clientPolicies = adminClient.realms().realm("test").clientPoliciesPoliciesResource().getPolicies(); - Assert.assertTrue(clientPolicies.getPolicies().isEmpty()); + Assertions.assertTrue(clientPolicies.getPolicies().isEmpty()); testViewGroups(masterRealm); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/JsonFileImport1903MigrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/JsonFileImport1903MigrationTest.java index 448056d10cb6..1cc8df8970fb 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/JsonFileImport1903MigrationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/JsonFileImport1903MigrationTest.java @@ -38,7 +38,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests that we can import json file from previous version. MigrationTest only tests DB. diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/MigrationDeniedTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/MigrationDeniedTest.java index ccb41268b573..db18da58180a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/MigrationDeniedTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/migration/MigrationDeniedTest.java @@ -33,8 +33,8 @@ import org.keycloak.testsuite.AbstractKeycloakTest; import org.keycloak.testsuite.arquillian.annotation.ModelTest; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @author Marek Posolda @@ -55,7 +55,7 @@ public void testMigrationDeniedWithDBSnapshotAndServerNonSnapshot(KeycloakSessio KeycloakModelUtils.runJobInTransaction(s.getKeycloakSessionFactory(), (session) -> { MigrationModel model = session.getProvider(DeploymentStateProvider.class).getMigrationModel(); String databaseVersion = model.getStoredVersion(); - Assert.assertNotNull("Stored DB version was null", model.getStoredVersion()); + Assertions.assertNotNull(model.getStoredVersion(), "Stored DB version was null"); String currentVersion = Version.VERSION; try { @@ -64,9 +64,9 @@ public void testMigrationDeniedWithDBSnapshotAndServerNonSnapshot(KeycloakSessio model.setStoredVersion(Constants.SNAPSHOT_VERSION); new DefaultMigrationManager(session, false).migrate(); - Assert.fail("Not expected to successfully run migration. DB version was " + databaseVersion + ". Keycloak version was " + currentVersion); + Assertions.fail("Not expected to successfully run migration. DB version was " + databaseVersion + ". Keycloak version was " + currentVersion); } catch (ModelException expected) { - Assert.assertTrue(expected.getMessage().startsWith("Incorrect state of migration. You are trying to run server version")); + Assertions.assertTrue(expected.getMessage().startsWith("Incorrect state of migration. You are trying to run server version")); } finally { // Revert version to the state before the test Version.VERSION = currentVersion; @@ -84,7 +84,7 @@ public void testMigrationDeniedWithDBNonSnapshotAndServerSnapshot(KeycloakSessio KeycloakModelUtils.runJobInTransaction(s.getKeycloakSessionFactory(), (session) -> { MigrationModel model = session.getProvider(DeploymentStateProvider.class).getMigrationModel(); String databaseVersion = model.getStoredVersion(); - Assert.assertNotNull("Stored DB version was null", model.getStoredVersion()); + Assertions.assertNotNull(model.getStoredVersion(), "Stored DB version was null"); String currentVersion = Version.VERSION; try { @@ -93,9 +93,9 @@ public void testMigrationDeniedWithDBNonSnapshotAndServerSnapshot(KeycloakSessio model.setStoredVersion("23.0.0"); new DefaultMigrationManager(session, false).migrate(); - Assert.fail("Not expected to successfully run migration. DB version was " + databaseVersion + ". Keycloak version was " + currentVersion); + Assertions.fail("Not expected to successfully run migration. DB version was " + databaseVersion + ". Keycloak version was " + currentVersion); } catch (ModelException expected) { - Assert.assertTrue(expected.getMessage().startsWith("Incorrect state of migration. You are trying to run nightly server version")); + Assertions.assertTrue(expected.getMessage().startsWith("Incorrect state of migration. You are trying to run nightly server version")); } finally { // Revert version to the state before the test Version.VERSION = currentVersion; diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AbstractClientAuthSignedJWTTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AbstractClientAuthSignedJWTTest.java index 233c58c38e90..abc36413cf1c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AbstractClientAuthSignedJWTTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AbstractClientAuthSignedJWTTest.java @@ -91,7 +91,6 @@ import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.services.util.CertificateInfoHelper; import org.keycloak.testsuite.AbstractKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.auth.page.AuthRealm; @@ -128,11 +127,12 @@ import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; +import org.junit.jupiter.api.Assertions; import org.junit.rules.TemporaryFolder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; public abstract class AbstractClientAuthSignedJWTTest extends AbstractKeycloakTest { @@ -455,7 +455,7 @@ protected void testClientWithGeneratedKeys(String format, Integer keySize, Integ assertCertificate(client, certOld, KeycloakModelUtils.getPemFromCertificate(x509Cert)); MatcherAssert.assertThat(x509Cert.getPublicKey(), Matchers.instanceOf(RSAKey.class)); - Assert.assertEquals(keySize == null ? 4096 : keySize, ((RSAKey) x509Cert.getPublicKey()).getModulus().bitLength()); + Assertions.assertEquals(keySize == null ? 4096 : keySize, ((RSAKey) x509Cert.getPublicKey()).getModulus().bitLength()); Calendar afterCreateCalendar = Calendar.getInstance(); afterCreateCalendar.add(Calendar.YEAR, expectedValidity); @@ -543,17 +543,17 @@ protected void testUploadKeystore(String keystoreFormat, String filePath, String if (keystoreFormat.equals(CertificateInfoHelper.PUBLIC_KEY_PEM)) { String pem = new String(Files.readAllBytes(keystoreFile.toPath())); final String publicKeyNew = client.getAttributes().get(JWTClientAuthenticator.ATTR_PREFIX + "." + CertificateInfoHelper.PUBLIC_KEY); - assertEquals("Certificates don't match", pem, publicKeyNew); + assertEquals(pem, publicKeyNew, "Certificates don't match"); } else if (keystoreFormat.equals(CertificateInfoHelper.JSON_WEB_KEY_SET)) { - Assert.assertEquals("true", client.getAttributes().get(OIDCConfigAttributes.USE_JWKS_STRING)); + Assertions.assertEquals("true", client.getAttributes().get(OIDCConfigAttributes.USE_JWKS_STRING)); String jwks = new String(Files.readAllBytes(keystoreFile.toPath())); - Assert.assertEquals(jwks, client.getAttributes().get(OIDCConfigAttributes.JWKS_STRING)); + Assertions.assertEquals(jwks, client.getAttributes().get(OIDCConfigAttributes.JWKS_STRING)); CertificateRepresentation info = getClient(testRealm.getRealm(), client.getId()) .getCertficateResource(JWTClientAuthenticator.ATTR_PREFIX).getKeyInfo(); - Assert.assertNotNull(info.getPublicKey()); + Assertions.assertNotNull(info.getPublicKey()); // Just assert it's valid public key PublicKey pk = KeycloakModelUtils.getPublicKey(info.getPublicKey()); - Assert.assertNotNull(pk); + Assertions.assertNotNull(pk); } else if (keystoreFormat.equals(CertificateInfoHelper.CERTIFICATE_PEM)) { String pem = new String(Files.readAllBytes(keystoreFile.toPath())); assertCertificate(client, certOld, pem); @@ -664,8 +664,8 @@ protected void assertSuccess(AccessTokenResponse response, String clientId, Stri protected static void assertCertificate(ClientRepresentation client, String certOld, String pem) { pem = PemUtils.removeBeginEnd(pem); final String certNew = client.getAttributes().get(JWTClientAuthenticator.CERTIFICATE_ATTR); - assertNotEquals("The old and new certificates shouldn't match", certOld, certNew); - assertEquals("Certificates don't match", pem, certNew); + assertNotEquals(certOld, certNew, "The old and new certificates shouldn't match"); + assertEquals(pem, certNew, "Certificates don't match"); } protected void testCodeToTokenRequestFailure(String algorithm, String error, String description) throws Exception { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenDuplicateEmailsNotCleanedUpTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenDuplicateEmailsNotCleanedUpTest.java index 34303c199772..ebbef6445dab 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenDuplicateEmailsNotCleanedUpTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenDuplicateEmailsNotCleanedUpTest.java @@ -32,7 +32,7 @@ import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.admin.AdminApiUtil.findUserByUsername; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Slawomir Dabek diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenDuplicateEmailsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenDuplicateEmailsTest.java index 057c633d4226..5576b42ac540 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenDuplicateEmailsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenDuplicateEmailsTest.java @@ -33,7 +33,7 @@ import static org.keycloak.testsuite.admin.AdminApiUtil.findUserByUsername; import static org.keycloak.testsuite.util.ServerURLs.getAuthServerContextRoot; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Slawomir Dabek diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenNoEmailLoginTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenNoEmailLoginTest.java index d8893c9306bd..9d86875aba9b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenNoEmailLoginTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenNoEmailLoginTest.java @@ -30,7 +30,7 @@ import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.admin.AdminApiUtil.findUserByUsername; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Slawomir Dabek diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenResponseTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenResponseTest.java index df2d1e73c86e..c1439309a1d0 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenResponseTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenResponseTest.java @@ -23,7 +23,7 @@ import static org.keycloak.testsuite.AbstractAdminTest.loadJson; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class AccessTokenResponseTest extends AbstractKeycloakTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenTest.java index d765668a31f8..d303ea54e15f 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AccessTokenTest.java @@ -109,10 +109,10 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; @@ -129,11 +129,11 @@ import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.hasItemInArray; import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stian Thorgersen @@ -441,7 +441,7 @@ public void accessTokenCodeExpired() { setTimeOffset(2); AccessTokenResponse response = oauth.doAccessTokenRequest(code); - Assert.assertEquals(400, response.getStatusCode()); + Assertions.assertEquals(400, response.getStatusCode()); } finally { getTestingClient().testing().revertTestingInfinispanTimeService(); resetTimeOffset(); @@ -466,7 +466,7 @@ public void bearerAccessTokenAsDPoPOnUserInfoEndpoint() throws IOException { EventRepresentation loginEvent = events.expectLogin().assertEvent(); loginEvent.getSessionId(); AccessTokenResponse response = oauth.doAccessTokenRequest(oauth.parseLoginResponse().getCode()); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); get = new HttpGet(oauth.getEndpoints().getUserInfo()); get.addHeader("Accept", MediaType.APPLICATION_JSON); @@ -488,7 +488,7 @@ public void accessTokenCodeUsed() throws IOException { String code = oauth.parseLoginResponse().getCode(); AccessTokenResponse response = oauth.doAccessTokenRequest(code); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); String accessToken = response.getAccessToken(); Client jaxrsClient = AdminClientUtil.createResteasyClient(); @@ -499,14 +499,14 @@ public void accessTokenCodeUsed() throws IOException { // Check that tokenIntrospection can be invoked JsonNode jsonNode = oauth.doIntrospectionAccessTokenRequest(accessToken).asJsonNode(); - Assert.assertEquals(true, jsonNode.get("active").asBoolean()); - Assert.assertEquals("test-user@localhost", jsonNode.get("email").asText()); + Assertions.assertEquals(true, jsonNode.get("active").asBoolean()); + Assertions.assertEquals("test-user@localhost", jsonNode.get("email").asText()); events.clear(); // Repeating attempt to exchange code should be refused and invalidate previous clientSession response = oauth.doAccessTokenRequest(code); - Assert.assertEquals(400, response.getStatusCode()); + Assertions.assertEquals(400, response.getStatusCode()); AssertEvents.ExpectedEvent expectedEvent = events.expectCodeToToken(codeId, codeId); expectedEvent.error("invalid_code") @@ -523,8 +523,8 @@ public void accessTokenCodeUsed() throws IOException { // Check that tokenIntrospection can't be invoked with invalidated accessToken jsonNode = oauth.doIntrospectionAccessTokenRequest(accessToken).asJsonNode(); - Assert.assertEquals(false, jsonNode.get("active").asBoolean()); - Assert.assertNull(jsonNode.get("email")); + Assertions.assertEquals(false, jsonNode.get("active").asBoolean()); + Assertions.assertNull(jsonNode.get("email")); events.clear(); @@ -554,10 +554,10 @@ public void accessTokenCodeRoleMissing() { AccessTokenResponse response = oauth.doAccessTokenRequest(code); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); AccessToken token = oauth.verifyToken(response.getAccessToken()); - Assert.assertEquals(1, token.getRealmAccess().getRoles().size()); + Assertions.assertEquals(1, token.getRealmAccess().getRoles().size()); assertTrue(token.getRealmAccess().isUserInRole("user")); events.clear(); @@ -575,7 +575,7 @@ public void accessTokenCodeHasRequiredAction() { String code = ActionURIUtils.parseQueryParamsFromActionURI(actionURI).get("code"); AccessTokenResponse response = oauth.doAccessTokenRequest(code); - Assert.assertEquals(400, response.getStatusCode()); + Assertions.assertEquals(400, response.getStatusCode()); EventRepresentation event = events.poll(); assertNull(event.getDetails().get(Details.CODE_ID)); @@ -900,8 +900,8 @@ public void testClientScope() throws Exception { assertEquals("coded", accessToken.getOtherClaims().get("hard")); // check zero scope for client scope - Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole.getName())); - Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName())); + Assertions.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole.getName())); + Assertions.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName())); response.close(); @@ -926,7 +926,7 @@ public void testClientScope() throws Exception { // check single role in scope for client scope assertNotNull(accessToken.getRealmAccess()); assertTrue(accessToken.getRealmAccess().getRoles().contains(realmRole.getName())); - Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName())); + Assertions.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName())); response.close(); @@ -975,8 +975,8 @@ public void testClientScope() throws Exception { org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class); AccessToken accessToken = getAccessToken(tokenResponse); - Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole.getName())); - Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName())); + Assertions.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole.getName())); + Assertions.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName())); response.close(); @@ -999,8 +999,8 @@ public void testClientScope() throws Exception { org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class); AccessToken accessToken = getAccessToken(tokenResponse); - Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole.getName())); - Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName())); + Assertions.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole.getName())); + Assertions.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName())); assertNull(accessToken.getOtherClaims().get("hard")); IDToken idToken = getIdToken(tokenResponse); @@ -1073,7 +1073,7 @@ public void testAuthorizationNegotiateHeaderIgnored() throws Exception { post.setEntity(formEntity); AccessTokenResponse response = new AccessTokenResponse(client.execute(post)); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); AccessToken token = oauth.verifyToken(response.getAccessToken()); events.expectCodeToToken(codeId, sessionId).client("sample-public-client").assertEvent(); } @@ -1428,7 +1428,7 @@ private void validateTokenSignatureLength(int expectedLength) { String encodedSignature = token.split("\\.",3)[2]; byte[] signature = Base64Url.decode(encodedSignature); - Assert.assertEquals(expectedLength, signature.length); + Assertions.assertEquals(expectedLength, signature.length); oauth.logoutForm().idTokenHint(response.getIdToken()).open(); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AuthorizationCodeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AuthorizationCodeTest.java index b9c8579fe9e0..bf3fa979a33a 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AuthorizationCodeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/AuthorizationCodeTest.java @@ -51,6 +51,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; @@ -59,8 +60,8 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stian Thorgersen @@ -93,9 +94,9 @@ public void authorizationRequest() throws IOException { AuthorizationEndpointResponse response = oauth.loginForm().state("OpenIdConnect.AuthenticationProperties=2302984sdlk").doLogin("test-user@localhost", "password"); assertTrue(response.isRedirected()); - Assert.assertNotNull(response.getCode()); + Assertions.assertNotNull(response.getCode()); assertEquals("OpenIdConnect.AuthenticationProperties=2302984sdlk", response.getState()); - Assert.assertNull(response.getError()); + Assertions.assertNull(response.getError()); assertEquals(oauth.AUTH_SERVER_ROOT + "/realms/test", response.getIssuer()); String codeId = events.expectLogin().assertEvent().getDetails().get(Details.CODE_ID); @@ -122,14 +123,14 @@ public void authorizationRequestInstalledAppErrors() throws IOException { // Assert text escaped installedAppPage.assertLinkBackToApplicationNotPresent(); - Assert.assertEquals("Error code:

Back to application

", installedAppPage.getPageTitleText()); + Assertions.assertEquals("Error code:

Back to application

", installedAppPage.getPageTitleText()); error = "

Back to application

"; installedAppPage.open("test", null, error, null); // Assert text is escaped installedAppPage.assertLinkBackToApplicationNotPresent(); - Assert.assertEquals("Error code:

Back to application

", installedAppPage.getPageTitleText()); + Assertions.assertEquals("Error code:

Back to application

", installedAppPage.getPageTitleText()); } @Test @@ -139,7 +140,7 @@ public void authorizationValidRedirectUri() throws IOException { AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password"); assertTrue(response.isRedirected()); - Assert.assertNotNull(response.getCode()); + Assertions.assertNotNull(response.getCode()); String codeId = events.expectLogin().assertEvent().getDetails().get(Details.CODE_ID); } @@ -177,9 +178,9 @@ public void authorizationRequestNoState() throws IOException { AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password"); assertTrue(response.isRedirected()); - Assert.assertNotNull(response.getCode()); - Assert.assertNull(response.getState()); - Assert.assertNull(response.getError()); + Assertions.assertNotNull(response.getCode()); + Assertions.assertNull(response.getState()); + Assertions.assertNull(response.getError()); assertEquals(oauth.AUTH_SERVER_ROOT + "/realms/test", response.getIssuer()); String codeId = events.expectLogin().assertEvent().getDetails().get(Details.CODE_ID); @@ -192,8 +193,8 @@ public void authorizationRequestInvalidResponseType() throws IOException { AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); assertTrue(errorResponse.isRedirected()); - Assert.assertEquals(errorResponse.getError(), OAuthErrorException.UNSUPPORTED_RESPONSE_TYPE); - Assert.assertEquals(oauth.AUTH_SERVER_ROOT + "/realms/test", errorResponse.getIssuer()); + Assertions.assertEquals(errorResponse.getError(), OAuthErrorException.UNSUPPORTED_RESPONSE_TYPE); + Assertions.assertEquals(oauth.AUTH_SERVER_ROOT + "/realms/test", errorResponse.getIssuer()); events.expectLogin().error(Errors.INVALID_REQUEST).user((String) null).session((String) null).clearDetails().detail(Details.RESPONSE_TYPE, "tokenn").assertEvent(); } @@ -207,7 +208,7 @@ public void authorizationRequestInvalidResponseType_testHeaders() throws IOExcep assertThat(response.getStatus(), is(equalTo(302))); String cacheControl = response.getHeaderString(HttpHeaders.CACHE_CONTROL); - Assert.assertNotNull(cacheControl); + Assertions.assertNotNull(cacheControl); Assert.assertThat(cacheControl, containsString("no-store")); Assert.assertThat(cacheControl, containsString("must-revalidate")); } @@ -292,10 +293,10 @@ public void authorizationRequestFormPostResponseModeHTMLEntitiesRedirectUri() th WaitUtils.waitForPageToLoad(); // if not properly encoded %3E would be received instead of > - Assert.assertEquals("Redirect page was not encoded", redirectUri, oauth.getDriver().getCurrentUrl()); + Assertions.assertEquals(redirectUri, oauth.getDriver().getCurrentUrl(), "Redirect page was not encoded"); String state = driver.findElement(By.id("state")).getText(); - Assert.assertEquals(requestState, state); - Assert.assertNotNull(driver.findElement(By.id("code")).getText()); + Assertions.assertEquals(requestState, state); + Assertions.assertNotNull(driver.findElement(By.id("code")).getText()); events.expect(EventType.LOGIN) .user(AssertEvents.isUUID()) @@ -322,14 +323,14 @@ public void authorizationRequestFormPostJwtResponseModeHTMLEntitiesRedirectUri() WaitUtils.waitForPageToLoad(); // if not properly encoded %3E would be received instead of > - Assert.assertEquals("Redirect page was not encoded", redirectUri, oauth.getDriver().getCurrentUrl()); + Assertions.assertEquals(redirectUri, oauth.getDriver().getCurrentUrl(), "Redirect page was not encoded"); String responseTokenEncoded = driver.findElement(By.id("response")).getText(); AuthorizationResponseToken responseToken = oauth.verifyAuthorizationResponseToken(responseTokenEncoded); assertEquals("test-app", responseToken.getAudience()[0]); - Assert.assertNotNull(responseToken.getOtherClaims().get("code")); - Assert.assertNull(responseToken.getOtherClaims().get("error")); - Assert.assertEquals(requestState, responseToken.getOtherClaims().get("state")); - Assert.assertNotNull(responseToken.getOtherClaims().get("code")); + Assertions.assertNotNull(responseToken.getOtherClaims().get("code")); + Assertions.assertNull(responseToken.getOtherClaims().get("error")); + Assertions.assertEquals(requestState, responseToken.getOtherClaims().get("state")); + Assertions.assertNotNull(responseToken.getOtherClaims().get("code")); events.expect(EventType.LOGIN) .user(AssertEvents.isUUID()) @@ -364,25 +365,25 @@ public void authorizationRequestFragmentResponseModeNotKept() throws Exception { oauth.responseMode(OIDCResponseMode.FRAGMENT.value()); AuthorizationEndpointResponse response = oauth.loginForm().state("authorizationRequestFragmentResponseModeNotKept").doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response.getCode()); - Assert.assertNotNull(response.getState()); + Assertions.assertNotNull(response.getCode()); + Assertions.assertNotNull(response.getState()); URI currentUri = new URI(driver.getCurrentUrl()); - Assert.assertNull(currentUri.getRawQuery()); - Assert.assertNotNull(currentUri.getRawFragment()); + Assertions.assertNull(currentUri.getRawQuery()); + Assertions.assertNotNull(currentUri.getRawFragment()); // Unset response_mode. The initial OIDC AuthenticationRequest won't contain "response_mode" parameter now and hence it should fallback to "query". oauth.responseMode(null); oauth.loginForm().state("authorizationRequestFragmentResponseModeNotKept2").open(); response = oauth.parseLoginResponse(); - Assert.assertNotNull(response.getCode()); - Assert.assertNotNull(response.getState()); - Assert.assertEquals(oauth.AUTH_SERVER_ROOT + "/realms/test", response.getIssuer()); + Assertions.assertNotNull(response.getCode()); + Assertions.assertNotNull(response.getState()); + Assertions.assertEquals(oauth.AUTH_SERVER_ROOT + "/realms/test", response.getIssuer()); currentUri = new URI(driver.getCurrentUrl()); - Assert.assertNotNull(currentUri.getRawQuery()); - Assert.assertNull(currentUri.getRawFragment()); + Assertions.assertNotNull(currentUri.getRawQuery()); + Assertions.assertNull(currentUri.getRawFragment()); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/BackchannelLogoutTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/BackchannelLogoutTest.java index 0f5d5ad1c233..491cb0a7fd43 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/BackchannelLogoutTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/BackchannelLogoutTest.java @@ -55,9 +55,9 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class BackchannelLogoutTest extends AbstractNestedBrokerTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ClientAuthPostMethodTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ClientAuthPostMethodTest.java index 074f80e7789a..b703e6a0204e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ClientAuthPostMethodTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ClientAuthPostMethodTest.java @@ -50,8 +50,8 @@ import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Test for "client_secret_post" client authentication (clientID + clientSecret sent in the POST body instead of in "Authorization: Basic" header) diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ClientAuthSecretSignedJWTTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ClientAuthSecretSignedJWTTest.java index de36cc49ee57..a34490734624 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ClientAuthSecretSignedJWTTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ClientAuthSecretSignedJWTTest.java @@ -88,8 +88,8 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; @EnableFeature(value = Profile.Feature.CLIENT_SECRET_ROTATION) public class ClientAuthSecretSignedJWTTest extends AbstractKeycloakTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ClientAuthSignedJWTTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ClientAuthSignedJWTTest.java index 0255fe841f79..5ffd93856eda 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ClientAuthSignedJWTTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ClientAuthSignedJWTTest.java @@ -44,7 +44,6 @@ import org.keycloak.representations.RefreshToken; import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.services.util.CertificateInfoHelper; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.util.ClientManager; import org.keycloak.testsuite.util.KeyUtils; @@ -57,12 +56,13 @@ import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.message.BasicNameValuePair; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Marek Posolda @@ -204,7 +204,7 @@ public void testCodeToTokenRequestSuccessES256Enforced() throws Exception { testCodeToTokenRequestSuccess(Algorithm.ES256, true); } catch (Exception e) { - Assert.fail(); + Assertions.fail(); } finally { clientResource = AdminApiUtil.findClientByClientId(adminClient.realm("test"), "client2"); clientRep = clientResource.toRepresentation(); @@ -770,8 +770,8 @@ public void testAssertionReuse() throws Exception { assertEquals(200, response.getStatusCode()); AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); - Assert.assertNotNull(accessToken); - Assert.assertNull(response.getError()); + Assertions.assertNotNull(accessToken); + Assertions.assertNull(response.getError()); // 2nd attempt to reuse same JWT should fail response = doClientCredentialsGrantRequest(clientJwt); @@ -865,7 +865,7 @@ public void testCodeToTokenRequestFailureES256Enforced() throws Exception { testCodeToTokenRequestFailure(Algorithm.RS256, "invalid_client", Errors.INVALID_CLIENT_CREDENTIALS); } catch (Exception e) { - Assert.fail(); + Assertions.fail(); } finally { clientResource = AdminApiUtil.findClientByClientId(adminClient.realm("test"), "client2"); clientRep = clientResource.toRepresentation(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/DPoPTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/DPoPTest.java index 8a535204250f..589c43a495e9 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/DPoPTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/DPoPTest.java @@ -79,7 +79,6 @@ import org.keycloak.services.clientpolicy.executor.DPoPBindEnforcerExecutorFactory; import org.keycloak.services.cors.Cors; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.admin.ApiUtil; @@ -104,9 +103,11 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; +import org.hamcrest.MatcherAssert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.OAuth2Constants.DPOP_HTTP_HEADER; import static org.keycloak.OAuth2Constants.DPOP_JWT_HEADER_TYPE; @@ -124,11 +125,11 @@ import static org.hamcrest.Matchers.emptyOrNullString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class DPoPTest extends AbstractTestRealmKeycloakTest { @@ -330,14 +331,14 @@ public void testDPoPProofByConfidentialClient() throws Exception { assertNull(refreshToken.getConfirmation()); TokenMetadataRepresentation tokenMetadataRepresentation = oauth.doIntrospectionRequest(response.getAccessToken(), "access_token").asTokenMetadata(); - Assert.assertTrue(tokenMetadataRepresentation.isActive()); + Assertions.assertTrue(tokenMetadataRepresentation.isActive()); assertEquals(jktRsa, tokenMetadataRepresentation.getConfirmation().getKeyThumbprint()); assertEquals(TokenUtil.TOKEN_TYPE_DPOP, tokenMetadataRepresentation.getOtherClaims().get(OAuth2Constants.TOKEN_TYPE)); oauth.tokenRevocationRequest(response.getAccessToken()).accessToken().send(); tokenMetadataRepresentation = oauth.doIntrospectionRequest(response.getAccessToken(), "access_token").asTokenMetadata(); - Assert.assertFalse(tokenMetadataRepresentation.isActive()); + Assertions.assertFalse(tokenMetadataRepresentation.isActive()); // token refresh String dpopProofEcEncoded = generateSignedDPoPProof(UUID.randomUUID().toString(), HttpMethod.POST, oauth.getEndpoints().getToken(), (long) (Time.currentTime() + clockSkew), Algorithm.ES256, jwsEcHeader, ecKeyPair.getPrivate(), null); @@ -653,7 +654,7 @@ public void testDifferentKeyDPoPProofOnUserInfo() throws Exception { private void testWWWAuthenticateHeaderError(UserInfoResponse userInfoResponse) { String wwwAuthenticate = userInfoResponse.getHeaders().get("WWW-Authenticate"); - Assert.assertThat(wwwAuthenticate, startsWith(DPOP_SCHEME)); + MatcherAssert.assertThat(wwwAuthenticate, startsWith(DPOP_SCHEME)); String chunks1 = wwwAuthenticate.substring(DPOP_SCHEME.length() + 1); Map map = new HashMap<>(); for (String p : chunks1.split(", ")) { @@ -661,10 +662,10 @@ private void testWWWAuthenticateHeaderError(UserInfoResponse userInfoResponse) { map.put(chunks2[0], chunks2[1]); } - Assert.assertEquals(map.get(OAuth2Constants.ERROR), "\"" + INVALID_TOKEN + "\""); + Assertions.assertEquals(map.get(OAuth2Constants.ERROR), "\"" + INVALID_TOKEN + "\""); String algs = map.get(OAuth2Constants.ALGS_ATTRIBUTE); - Assert.assertTrue(algs.contains(Algorithm.EdDSA)); - Assert.assertTrue(algs.contains(Algorithm.RS256)); + Assertions.assertTrue(algs.contains(Algorithm.EdDSA)); + Assertions.assertTrue(algs.contains(Algorithm.RS256)); } @Test @@ -975,13 +976,13 @@ public void testDPoPAdminRequestSuccess() throws Exception { "test-admin@localhost", "password", TEST_CONFIDENTIAL_CLIENT_ID, TEST_CONFIDENTIAL_CLIENT_SECRET, null, true); ) { RealmRepresentation realm = adminClientDPoP.realm(REALM_NAME).toRepresentation(); - Assert.assertEquals(REALM_NAME, realm.getRealm()); + Assertions.assertEquals(REALM_NAME, realm.getRealm()); // To enforce token refresh by admin client in the next request setTimeOffset(700); realm = adminClientDPoP.realm(REALM_NAME).toRepresentation(); - Assert.assertEquals(REALM_NAME, realm.getRealm()); + Assertions.assertEquals(REALM_NAME, realm.getRealm()); } } @@ -996,9 +997,9 @@ public void testDPoPAdminRequestFailure() throws Exception { "test-admin@localhost", "password", TEST_CONFIDENTIAL_CLIENT_ID, TEST_CONFIDENTIAL_CLIENT_SECRET, null, false); ) { adminClientDPoP.realm(REALM_NAME).toRepresentation(); - Assert.fail("Expected exception when calling adminClient without DPoP for the client, which requires DPoP"); + Assertions.fail("Expected exception when calling adminClient without DPoP for the client, which requires DPoP"); } catch (ProcessingException pe) { - Assert.assertTrue(pe.getCause() instanceof BadRequestException); + Assertions.assertTrue(pe.getCause() instanceof BadRequestException); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/LoginStatusIframeEndpointTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/LoginStatusIframeEndpointTest.java index 819bd78bd37c..0230710b50ed 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/LoginStatusIframeEndpointTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/LoginStatusIframeEndpointTest.java @@ -57,12 +57,12 @@ import org.apache.http.message.BasicNameValuePair; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Stian Thorgersen diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/LogoutCorsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/LogoutCorsTest.java index ca6a908fb006..bca413fd8232 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/LogoutCorsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/LogoutCorsTest.java @@ -34,9 +34,9 @@ import static org.keycloak.testsuite.AbstractAdminTest.loadJson; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Marek Posolda diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/LogoutTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/LogoutTest.java index 426528116497..269cf634c6ff 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/LogoutTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/LogoutTest.java @@ -45,7 +45,6 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.testsuite.AbstractKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.pages.LoginPage; @@ -70,14 +69,15 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests mostly for backchannel logout scenarios with refresh token (Legacy Logout endpoint not compliant with OIDC specification) and admin logout scenarios @@ -157,7 +157,7 @@ public void postLogoutWithRefreshTokenAfterUserSessionLogoutAndLoginAgain() thro driver.navigate().refresh(); oauth.fillLoginForm("test-user@localhost", "password"); - Assert.assertFalse(loginPage.isCurrent()); + Assertions.assertFalse(loginPage.isCurrent()); String code = oauth.parseLoginResponse().getCode(); AccessTokenResponse tokenResponse2 = oauth.doAccessTokenRequest(code); @@ -200,14 +200,14 @@ public void logoutBackchannelTwoClientsSpecificConfigurationIsUsed() throws Exce oauth.doLogin("test-user@localhost", "password"); AccessTokenResponse tokenResponse = oauth.accessTokenRequest(oauth.parseLoginResponse().getCode()) .param(AdapterConstants.CLIENT_SESSION_STATE, "client-session").send(); - Assert.assertNull(tokenResponse.getError()); + Assertions.assertNull(tokenResponse.getError()); // login with test-app-scope oauth.client("test-app-scope", "password"); oauth.openLoginForm(); AccessTokenResponse tokenResponse2 = oauth.accessTokenRequest(oauth.parseLoginResponse().getCode()) .param(AdapterConstants.CLIENT_SESSION_STATE, "client-session").send(); - Assert.assertNull(tokenResponse2.getError()); + Assertions.assertNull(tokenResponse2.getError()); AccessToken accessToken = new JWSInput(tokenResponse2.getAccessToken()).readJsonContent(AccessToken.class); // logout from test-app-scope @@ -241,7 +241,7 @@ public void testRemoveAuthSessionWhenUserSessionFromIdTokenIsInvalid() throws IO .enabled(true) .build()).close(); UserRepresentation user = AdminApiUtil.findUserByUsername(realm, "user-0"); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); oauth.openLoginForm(); loginPage.login("user-0", "password"); @@ -275,7 +275,7 @@ public void testRemoveAuthSessionWhenUserSessionFromIdTokenIsInvalid() throws IO .postLogoutRedirectUri(oauth.APP_AUTH_ROOT) .open(); user = AdminApiUtil.findUserByUsername(realm, "user-1"); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); realm.users().get(user.getId()).remove(); } } @@ -287,13 +287,13 @@ public void logoutUserByAdmin() { String sessionId = events.expectLogin().assertEvent().getSessionId(); UserRepresentation user = AdminApiUtil.findUserByUsername(adminClient.realm("test"), "test-user@localhost"); - Assert.assertEquals((Object) 0, user.getNotBefore()); + Assertions.assertEquals((Object) 0, user.getNotBefore()); adminClient.realm("test").users().get(user.getId()).logout(); Retry.execute(() -> { UserRepresentation u = adminClient.realm("test").users().get(user.getId()).toRepresentation(); - Assert.assertTrue(u.getNotBefore() > 0); + Assertions.assertTrue(u.getNotBefore() > 0); oauth.openLoginForm(); loginPage.assertCurrent(); @@ -473,17 +473,17 @@ public void backChannelWithPairwiseLogout() throws Exception { * Validate the token matches the spec at OpenID Connect Back-Channel Logout 1.0 incorporating errata set 1 */ private void validateLogoutToken(LogoutToken backChannelLogoutToken) { - assertNotNull("token must be present", backChannelLogoutToken); - assertNotNull("iss must be present", backChannelLogoutToken.getIssuer()); - assertNotNull("aud must be present", backChannelLogoutToken.getAudience()); - assertNotNull("iat must be present", backChannelLogoutToken.getIat()); - assertNotNull("exp must be present", backChannelLogoutToken.getExp()); - assertNotNull("jti must be present", backChannelLogoutToken.getId()); + assertNotNull(backChannelLogoutToken, "token must be present"); + assertNotNull(backChannelLogoutToken.getIssuer(), "iss must be present"); + assertNotNull(backChannelLogoutToken.getAudience(), "aud must be present"); + assertNotNull(backChannelLogoutToken.getIat(), "iat must be present"); + assertNotNull(backChannelLogoutToken.getExp(), "exp must be present"); + assertNotNull(backChannelLogoutToken.getId(), "jti must be present"); Map events = backChannelLogoutToken.getEvents(); - assertNotNull("events must be present", events); + assertNotNull(events, "events must be present"); Object backchannelLogoutEvent = events.get("http://schemas.openid.net/event/backchannel-logout"); - assertNotNull("back-channel logout event must be present", backchannelLogoutEvent); - assertTrue("back-channel logout event must have a member object", backchannelLogoutEvent instanceof Map); + assertNotNull(backchannelLogoutEvent, "back-channel logout event must be present"); + assertTrue(backchannelLogoutEvent instanceof Map, "back-channel logout event must have a member object"); MatcherAssert.assertThat("map of back-channel logout event member object should be an empty object", (Map) backchannelLogoutEvent, org.hamcrest.Matchers.anEmptyMap()); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuth2DeviceAuthorizationGrantTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuth2DeviceAuthorizationGrantTest.java index 154340448aea..ffd4d317969b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuth2DeviceAuthorizationGrantTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuth2DeviceAuthorizationGrantTest.java @@ -40,7 +40,6 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.testsuite.AbstractKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.pages.ErrorPage; @@ -68,14 +67,15 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.Cookie; import static org.keycloak.models.OAuth2DeviceConfig.DEFAULT_OAUTH2_DEVICE_CODE_LIFESPAN; import static org.keycloak.models.OAuth2DeviceConfig.DEFAULT_OAUTH2_DEVICE_POLLING_INTERVAL; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Hiroyuki Wada @@ -167,13 +167,13 @@ public void testConfidentialClient() throws Exception { oauth.client(DEVICE_APP, DEVICE_APP_SECRET); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); assertNotNull(response.getVerificationUriComplete()); - Assert.assertEquals(60, response.getExpiresIn()); - Assert.assertEquals(5, response.getInterval()); + Assertions.assertEquals(60, response.getExpiresIn()); + Assertions.assertEquals(5, response.getInterval()); // Verify user code from verification page using browser openVerificationPage(response.getVerificationUri()); @@ -195,7 +195,7 @@ public void testConfidentialClient() throws Exception { // Token request from device AccessTokenResponse tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); - Assert.assertEquals(200, tokenResponse.getStatusCode()); + Assertions.assertEquals(200, tokenResponse.getStatusCode()); String tokenString = tokenResponse.getAccessToken(); assertNotNull(tokenString); @@ -211,13 +211,13 @@ public void testPublicClient() throws Exception { oauth.client(DEVICE_APP_PUBLIC); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); assertNotNull(response.getVerificationUriComplete()); - Assert.assertEquals(60, response.getExpiresIn()); - Assert.assertEquals(5, response.getInterval()); + Assertions.assertEquals(60, response.getExpiresIn()); + Assertions.assertEquals(5, response.getInterval()); openVerificationPage(response.getVerificationUriComplete()); @@ -230,7 +230,7 @@ public void testPublicClient() throws Exception { // Token request from device AccessTokenResponse tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); - Assert.assertEquals(200, tokenResponse.getStatusCode()); + Assertions.assertEquals(200, tokenResponse.getStatusCode()); String tokenString = tokenResponse.getAccessToken(); assertNotNull(tokenString); @@ -252,11 +252,11 @@ public void testCustomVerificationUri() throws Exception { oauth.client(DEVICE_APP_PUBLIC); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); - Assert.assertEquals(SHORT_DEVICE_FLOW_URL,response.getVerificationUri()); - Assert.assertEquals(SHORT_DEVICE_FLOW_URL + "?user_code=" + response.getUserCode(),response.getVerificationUriComplete()); + Assertions.assertEquals(SHORT_DEVICE_FLOW_URL,response.getVerificationUri()); + Assertions.assertEquals(SHORT_DEVICE_FLOW_URL + "?user_code=" + response.getUserCode(),response.getVerificationUriComplete()); } finally { RealmResource testRealm = adminClient.realm(REALM_NAME); RealmRepresentation realmRep = testRealm.toRepresentation(); @@ -321,7 +321,7 @@ public void testVerifyHolderOfDeviceCode() throws Exception { openVerificationPage(response.getVerificationUriComplete()); // Consent - Assert.assertTrue(grantPage.getDisplayedGrants().contains("This is the custom consent screen text.")); + Assertions.assertTrue(grantPage.getDisplayedGrants().contains("This is the custom consent screen text.")); grantPage.accept(); oauth.client(DEVICE_APP_PUBLIC); @@ -346,13 +346,13 @@ public void testPublicClientOptionalScope() throws Exception { oauth.scope(null); } - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); assertNotNull(response.getVerificationUriComplete()); - Assert.assertEquals(60, response.getExpiresIn()); - Assert.assertEquals(5, response.getInterval()); + Assertions.assertEquals(60, response.getExpiresIn()); + Assertions.assertEquals(5, response.getInterval()); openVerificationPage(response.getVerificationUriComplete()); @@ -367,7 +367,7 @@ public void testPublicClientOptionalScope() throws Exception { // Token request from device AccessTokenResponse tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); - Assert.assertEquals(200, tokenResponse.getStatusCode()); + Assertions.assertEquals(200, tokenResponse.getStatusCode()); String tokenString = tokenResponse.getAccessToken(); assertNotNull(tokenString); @@ -378,9 +378,9 @@ public void testPublicClientOptionalScope() throws Exception { UserInfo userInfo = oauth.doUserInfoRequest(tokenString).getUserInfo(); assertNotNull(userInfo); //UserInfo consists preferredUsername, email( required scopes) and phoneNumber(given optional scope) - Assert.assertEquals("device-login", userInfo.getPreferredUsername()); - Assert.assertEquals("device-login@localhost", userInfo.getEmail()); - Assert.assertEquals("211211211", userInfo.getPhoneNumber()); + Assertions.assertEquals("device-login", userInfo.getPreferredUsername()); + Assertions.assertEquals("device-login@localhost", userInfo.getEmail()); + Assertions.assertEquals("211211211", userInfo.getPhoneNumber()); } @Test @@ -391,13 +391,13 @@ public void testPublicClientWithPKCESuccess() throws Exception { PkceGenerator pkce = PkceGenerator.s256(); DeviceAuthorizationResponse response = oauth.device().deviceAuthorizationRequest().codeChallenge(pkce).send(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); assertNotNull(response.getVerificationUriComplete()); - Assert.assertEquals(60, response.getExpiresIn()); - Assert.assertEquals(5, response.getInterval()); + Assertions.assertEquals(60, response.getExpiresIn()); + Assertions.assertEquals(5, response.getInterval()); openVerificationPage(response.getVerificationUriComplete()); @@ -410,7 +410,7 @@ public void testPublicClientWithPKCESuccess() throws Exception { // Token request from device AccessTokenResponse tokenResponse = oauth.device().deviceTokenRequest(response.getDeviceCode()).codeVerifier(pkce.getCodeVerifier()).send(); - Assert.assertEquals(200, tokenResponse.getStatusCode()); + Assertions.assertEquals(200, tokenResponse.getStatusCode()); String tokenString = tokenResponse.getAccessToken(); assertNotNull(tokenString); @@ -427,13 +427,13 @@ public void testPublicClientWithPKCEFail() throws Exception { PkceGenerator pkce = PkceGenerator.s256(); DeviceAuthorizationResponse response = oauth.device().deviceAuthorizationRequest().codeChallenge(pkce).send(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); assertNotNull(response.getVerificationUriComplete()); - Assert.assertEquals(60, response.getExpiresIn()); - Assert.assertEquals(5, response.getInterval()); + Assertions.assertEquals(60, response.getExpiresIn()); + Assertions.assertEquals(5, response.getInterval()); openVerificationPage(response.getVerificationUriComplete()); @@ -446,9 +446,9 @@ public void testPublicClientWithPKCEFail() throws Exception { // Token request from device AccessTokenResponse tokenResponse = oauth.device().deviceTokenRequest(response.getDeviceCode()).codeVerifier(pkce.getCodeVerifier()+"a").send(); - Assert.assertEquals(400, tokenResponse.getStatusCode()); - Assert.assertEquals("invalid_grant", tokenResponse.getError()); - Assert.assertEquals("PKCE verification failed: Code mismatch", tokenResponse.getErrorDescription()); + Assertions.assertEquals(400, tokenResponse.getStatusCode()); + Assertions.assertEquals("invalid_grant", tokenResponse.getError()); + Assertions.assertEquals("PKCE verification failed: Code mismatch", tokenResponse.getErrorDescription()); } @@ -459,13 +459,13 @@ public void testPublicClientCustomConsent() throws Exception { oauth.client(DEVICE_APP_PUBLIC_CUSTOM_CONSENT); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); assertNotNull(response.getVerificationUriComplete()); - Assert.assertEquals(60, response.getExpiresIn()); - Assert.assertEquals(5, response.getInterval()); + Assertions.assertEquals(60, response.getExpiresIn()); + Assertions.assertEquals(5, response.getInterval()); openVerificationPage(response.getVerificationUriComplete()); @@ -473,13 +473,13 @@ public void testPublicClientCustomConsent() throws Exception { oauth.fillLoginForm("device-login", "password"); // Consent - Assert.assertTrue(grantPage.getDisplayedGrants().contains("This is the custom consent screen text.")); + Assertions.assertTrue(grantPage.getDisplayedGrants().contains("This is the custom consent screen text.")); grantPage.accept(); // Token request from device AccessTokenResponse tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); - Assert.assertEquals(200, tokenResponse.getStatusCode()); + Assertions.assertEquals(200, tokenResponse.getStatusCode()); String tokenString = tokenResponse.getAccessToken(); assertNotNull(tokenString); @@ -506,7 +506,7 @@ public void testPublicClientConsentWithoutScopes() throws Exception { oauth.client(DEVICE_APP_WITHOUT_SCOPES); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getVerificationUriComplete()); openVerificationPage(response.getVerificationUriComplete()); loginPage.assertCurrent(); @@ -541,7 +541,7 @@ public void testNoRefreshToken() throws Exception { // Token request from device AccessTokenResponse tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); - Assert.assertEquals(200, tokenResponse.getStatusCode()); + Assertions.assertEquals(200, tokenResponse.getStatusCode()); assertNotNull(tokenResponse.getAccessToken()); assertNull(tokenResponse.getRefreshToken()); @@ -557,13 +557,13 @@ public void testConsentCancel() throws Exception { oauth.client(DEVICE_APP, DEVICE_APP_SECRET); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); assertNotNull(response.getVerificationUriComplete()); - Assert.assertEquals(60, response.getExpiresIn()); - Assert.assertEquals(5, response.getInterval()); + Assertions.assertEquals(60, response.getExpiresIn()); + Assertions.assertEquals(5, response.getInterval()); openVerificationPage(response.getVerificationUriComplete()); loginPage.assertCurrent(); @@ -580,8 +580,8 @@ public void testConsentCancel() throws Exception { AccessTokenResponse tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); - Assert.assertEquals(400, tokenResponse.getStatusCode()); - Assert.assertEquals("access_denied", tokenResponse.getError()); + Assertions.assertEquals(400, tokenResponse.getStatusCode()); + Assertions.assertEquals("access_denied", tokenResponse.getError()); } @Test @@ -591,13 +591,13 @@ public void testInvalidUserCode() throws Exception { oauth.client(DEVICE_APP, DEVICE_APP_SECRET); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); assertNotNull(response.getVerificationUriComplete()); - Assert.assertEquals(60, response.getExpiresIn()); - Assert.assertEquals(5, response.getInterval()); + Assertions.assertEquals(60, response.getExpiresIn()); + Assertions.assertEquals(5, response.getInterval()); openVerificationPage(response.getVerificationUri()); verificationPage.submit("x"); @@ -613,13 +613,13 @@ public void testExpiredUserCodeTest() throws Exception { oauth.client(DEVICE_APP, DEVICE_APP_SECRET); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); assertNotNull(response.getVerificationUriComplete()); - Assert.assertEquals(60, response.getExpiresIn()); - Assert.assertEquals(5, response.getInterval()); + Assertions.assertEquals(60, response.getExpiresIn()); + Assertions.assertEquals(5, response.getInterval()); try { setTimeOffset(610); @@ -640,13 +640,13 @@ public void testInvalidDeviceCode() throws Exception { oauth.client(DEVICE_APP, DEVICE_APP_SECRET); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); assertNotNull(response.getVerificationUriComplete()); - Assert.assertEquals(60, response.getExpiresIn()); - Assert.assertEquals(5, response.getInterval()); + Assertions.assertEquals(60, response.getExpiresIn()); + Assertions.assertEquals(5, response.getInterval()); openVerificationPage(response.getVerificationUriComplete()); loginPage.assertCurrent(); @@ -662,8 +662,8 @@ public void testInvalidDeviceCode() throws Exception { // Token request from device AccessTokenResponse tokenResponse = oauth.device().doDeviceTokenRequest("x"); - Assert.assertEquals(400, tokenResponse.getStatusCode()); - Assert.assertEquals("invalid_grant", tokenResponse.getError()); + Assertions.assertEquals(400, tokenResponse.getStatusCode()); + Assertions.assertEquals("invalid_grant", tokenResponse.getError()); } @Test @@ -673,13 +673,13 @@ public void testSuccessVerificationUriComplete() throws Exception { oauth.client(DEVICE_APP, DEVICE_APP_SECRET); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); assertNotNull(response.getVerificationUriComplete()); - Assert.assertEquals(60, response.getExpiresIn()); - Assert.assertEquals(5, response.getInterval()); + Assertions.assertEquals(60, response.getExpiresIn()); + Assertions.assertEquals(5, response.getInterval()); openVerificationPage(response.getVerificationUriComplete()); loginPage.assertCurrent(); @@ -697,7 +697,7 @@ public void testSuccessVerificationUriComplete() throws Exception { // Token request from device AccessTokenResponse tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); - Assert.assertEquals(200, tokenResponse.getStatusCode()); + Assertions.assertEquals(200, tokenResponse.getStatusCode()); } @Test @@ -708,21 +708,21 @@ public void testExpiredDeviceCode() throws Exception { oauth.client(DEVICE_APP, DEVICE_APP_SECRET); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); assertNotNull(response.getVerificationUriComplete()); - Assert.assertEquals(60, response.getExpiresIn()); - Assert.assertEquals(5, response.getInterval()); + Assertions.assertEquals(60, response.getExpiresIn()); + Assertions.assertEquals(5, response.getInterval()); try { setTimeOffset(610); // Token request from device AccessTokenResponse tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); - Assert.assertEquals(400, tokenResponse.getStatusCode()); - Assert.assertEquals("invalid_grant", tokenResponse.getError()); + Assertions.assertEquals(400, tokenResponse.getStatusCode()); + Assertions.assertEquals("invalid_grant", tokenResponse.getError()); } finally { getTestingClient().testing().revertTestingInfinispanTimeService(); resetTimeOffset(); @@ -735,9 +735,9 @@ public void testDuplicatedRequestParams() throws Exception { oauth.client(DEVICE_APP_PUBLIC); DeviceAuthorizationResponse response = doDeviceAuthorizationWithDuplicatedParams(DEVICE_APP_PUBLIC, null); - Assert.assertEquals(400, response.getStatusCode()); - Assert.assertEquals("invalid_grant", response.getError()); - Assert.assertEquals("duplicated parameter", response.getErrorDescription()); + Assertions.assertEquals(400, response.getStatusCode()); + Assertions.assertEquals("invalid_grant", response.getError()); + Assertions.assertEquals("duplicated parameter", response.getErrorDescription()); } @Test @@ -750,20 +750,20 @@ public void testDeviceCodeLifespanPerClient() throws Exception { oauth.client(DEVICE_APP, DEVICE_APP_SECRET); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); assertNotNull(response.getVerificationUriComplete()); - Assert.assertEquals(60, response.getExpiresIn()); - Assert.assertEquals(5, response.getInterval()); + Assertions.assertEquals(60, response.getExpiresIn()); + Assertions.assertEquals(5, response.getInterval()); clientRepresentation.getAttributes().put(OAuth2DeviceConfig.OAUTH2_DEVICE_CODE_LIFESPAN_PER_CLIENT, "120"); clientRepresentation.getAttributes().put(OAuth2DeviceConfig.OAUTH2_DEVICE_POLLING_INTERVAL_PER_CLIENT, "600000"); client.update(clientRepresentation); response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(120, response.getExpiresIn()); + Assertions.assertEquals(120, response.getExpiresIn()); AccessTokenResponse tokenResponse; try { @@ -771,15 +771,15 @@ public void testDeviceCodeLifespanPerClient() throws Exception { // Token request from device tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); - Assert.assertEquals(400, tokenResponse.getStatusCode()); - Assert.assertEquals("authorization_pending", tokenResponse.getError()); + Assertions.assertEquals(400, tokenResponse.getStatusCode()); + Assertions.assertEquals("authorization_pending", tokenResponse.getError()); setTimeOffset(125); // Token request from device tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); - Assert.assertEquals(400, tokenResponse.getStatusCode()); - Assert.assertEquals("expired_token", tokenResponse.getError()); + Assertions.assertEquals(400, tokenResponse.getStatusCode()); + Assertions.assertEquals("expired_token", tokenResponse.getError()); } finally { getTestingClient().testing().revertTestingInfinispanTimeService(); resetTimeOffset(); @@ -800,48 +800,48 @@ public void testDevicePollingIntervalPerClient() throws Exception { oauth.client(DEVICE_APP, DEVICE_APP_SECRET); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); assertNotNull(response.getVerificationUriComplete()); - Assert.assertEquals(60, response.getExpiresIn()); - Assert.assertEquals(5, response.getInterval()); + Assertions.assertEquals(60, response.getExpiresIn()); + Assertions.assertEquals(5, response.getInterval()); clientRepresentation.getAttributes().put(OAuth2DeviceConfig.OAUTH2_DEVICE_POLLING_INTERVAL_PER_CLIENT, "10"); client.update(clientRepresentation); response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(10, response.getInterval()); + Assertions.assertEquals(10, response.getInterval()); try { // Token request from device AccessTokenResponse tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); - Assert.assertEquals(400, tokenResponse.getStatusCode()); - Assert.assertEquals("authorization_pending", tokenResponse.getError()); + Assertions.assertEquals(400, tokenResponse.getStatusCode()); + Assertions.assertEquals("authorization_pending", tokenResponse.getError()); // Token request from device tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); - Assert.assertEquals(400, tokenResponse.getStatusCode()); - Assert.assertEquals("slow_down", tokenResponse.getError()); + Assertions.assertEquals(400, tokenResponse.getStatusCode()); + Assertions.assertEquals("slow_down", tokenResponse.getError()); setTimeOffset(7); // Token request from device tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); - Assert.assertEquals(400, tokenResponse.getStatusCode()); - Assert.assertEquals("slow_down", tokenResponse.getError()); + Assertions.assertEquals(400, tokenResponse.getStatusCode()); + Assertions.assertEquals("slow_down", tokenResponse.getError()); setTimeOffset(10); // Token request from device tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); - Assert.assertEquals(400, tokenResponse.getStatusCode()); - Assert.assertEquals("authorization_pending", tokenResponse.getError()); + Assertions.assertEquals(400, tokenResponse.getStatusCode()); + Assertions.assertEquals("authorization_pending", tokenResponse.getError()); } finally { getTestingClient().testing().revertTestingInfinispanTimeService(); clientRepresentation.getAttributes().put(OAuth2DeviceConfig.OAUTH2_DEVICE_POLLING_INTERVAL_PER_CLIENT, ""); @@ -862,22 +862,22 @@ public void testPolling() throws Exception { oauth.client(DEVICE_APP, DEVICE_APP_SECRET); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(600, response.getExpiresIn()); - Assert.assertEquals(5, response.getInterval()); + Assertions.assertEquals(600, response.getExpiresIn()); + Assertions.assertEquals(5, response.getInterval()); // Polling token request from device AccessTokenResponse tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); // Not approved yet - Assert.assertEquals(400, tokenResponse.getStatusCode()); - Assert.assertEquals("authorization_pending", tokenResponse.getError()); + Assertions.assertEquals(400, tokenResponse.getStatusCode()); + Assertions.assertEquals("authorization_pending", tokenResponse.getError()); // Polling again without waiting tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); // Slow down - Assert.assertEquals(400, tokenResponse.getStatusCode()); - Assert.assertEquals("slow_down", tokenResponse.getError()); + Assertions.assertEquals(400, tokenResponse.getStatusCode()); + Assertions.assertEquals("slow_down", tokenResponse.getError()); // Wait the interval setTimeOffset(5); @@ -886,8 +886,8 @@ public void testPolling() throws Exception { tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); // Not approved yet - Assert.assertEquals(400, tokenResponse.getStatusCode()); - Assert.assertEquals("authorization_pending", tokenResponse.getError()); + Assertions.assertEquals(400, tokenResponse.getStatusCode()); + Assertions.assertEquals("authorization_pending", tokenResponse.getError()); // Change the interval setting of the realm from 5 seconds to 10 seconds. realm.setOAuth2DevicePollingInterval(10); @@ -896,15 +896,15 @@ public void testPolling() throws Exception { // Checking the new interval is applied response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(600, response.getExpiresIn()); - Assert.assertEquals(10, response.getInterval()); + Assertions.assertEquals(600, response.getExpiresIn()); + Assertions.assertEquals(10, response.getInterval()); // Polling token request from device tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); // Not approved yet - Assert.assertEquals(400, tokenResponse.getStatusCode()); - Assert.assertEquals("authorization_pending", tokenResponse.getError()); + Assertions.assertEquals(400, tokenResponse.getStatusCode()); + Assertions.assertEquals("authorization_pending", tokenResponse.getError()); // Wait setTimeOffset(10); @@ -913,8 +913,8 @@ public void testPolling() throws Exception { tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); // Slow down - Assert.assertEquals(400, tokenResponse.getStatusCode()); - Assert.assertEquals("slow_down", tokenResponse.getError()); + Assertions.assertEquals(400, tokenResponse.getStatusCode()); + Assertions.assertEquals("slow_down", tokenResponse.getError()); // Wait setTimeOffset(15); @@ -923,8 +923,8 @@ public void testPolling() throws Exception { tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); // Not approved yet - Assert.assertEquals(400, tokenResponse.getStatusCode()); - Assert.assertEquals("authorization_pending", tokenResponse.getError()); + Assertions.assertEquals(400, tokenResponse.getStatusCode()); + Assertions.assertEquals("authorization_pending", tokenResponse.getError()); } finally { getTestingClient().testing().revertTestingInfinispanTimeService(); } @@ -941,8 +941,8 @@ public void testUpdateConfig() { realm.update(rep); rep = realm.toRepresentation(); - Assert.assertEquals(DEFAULT_OAUTH2_DEVICE_POLLING_INTERVAL, rep.getOAuth2DevicePollingInterval().intValue()); - Assert.assertEquals(DEFAULT_OAUTH2_DEVICE_CODE_LIFESPAN, rep.getOAuth2DeviceCodeLifespan().intValue()); + Assertions.assertEquals(DEFAULT_OAUTH2_DEVICE_POLLING_INTERVAL, rep.getOAuth2DevicePollingInterval().intValue()); + Assertions.assertEquals(DEFAULT_OAUTH2_DEVICE_CODE_LIFESPAN, rep.getOAuth2DeviceCodeLifespan().intValue()); rep.setOAuth2DevicePollingInterval(10); rep.setOAuth2DeviceCodeLifespan(15); @@ -950,8 +950,8 @@ public void testUpdateConfig() { realm.update(rep); rep = realm.toRepresentation(); - Assert.assertEquals(10, rep.getOAuth2DevicePollingInterval().intValue()); - Assert.assertEquals(15, rep.getOAuth2DeviceCodeLifespan().intValue()); + Assertions.assertEquals(10, rep.getOAuth2DevicePollingInterval().intValue()); + Assertions.assertEquals(15, rep.getOAuth2DeviceCodeLifespan().intValue()); } // KEYCLOAK-19700 @@ -962,13 +962,13 @@ public void testConsentCancelCannotBeReused() throws Exception { oauth.client(DEVICE_APP, DEVICE_APP_SECRET); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); assertNotNull(response.getVerificationUriComplete()); - Assert.assertEquals(60, response.getExpiresIn()); - Assert.assertEquals(5, response.getInterval()); + Assertions.assertEquals(60, response.getExpiresIn()); + Assertions.assertEquals(5, response.getInterval()); openVerificationPage(response.getVerificationUriComplete()); loginPage.assertCurrent(); @@ -994,13 +994,13 @@ public void testConsentCancelCannotBeReusedAfterBackClicked() throws Exception { oauth.client(DEVICE_APP, DEVICE_APP_SECRET); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); assertNotNull(response.getDeviceCode()); assertNotNull(response.getUserCode()); assertNotNull(response.getVerificationUri()); assertNotNull(response.getVerificationUriComplete()); - Assert.assertEquals(60, response.getExpiresIn()); - Assert.assertEquals(5, response.getInterval()); + Assertions.assertEquals(60, response.getExpiresIn()); + Assertions.assertEquals(5, response.getInterval()); openVerificationPage(response.getVerificationUriComplete()); loginPage.assertCurrent(); @@ -1024,8 +1024,8 @@ public void testConsentCancelCannotBeReusedAfterBackClicked() throws Exception { AccessTokenResponse tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode()); - Assert.assertEquals(400, tokenResponse.getStatusCode()); - Assert.assertEquals("access_denied", tokenResponse.getError()); + Assertions.assertEquals(400, tokenResponse.getStatusCode()); + Assertions.assertEquals("access_denied", tokenResponse.getError()); } @Test @@ -1034,9 +1034,9 @@ public void testNotFoundClient() throws Exception { oauth.client("test-device-public2"); DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(401, response.getStatusCode()); - Assert.assertEquals(Errors.INVALID_CLIENT, response.getError()); - Assert.assertEquals("Invalid client or Invalid client credentials", response.getErrorDescription()); + Assertions.assertEquals(401, response.getStatusCode()); + Assertions.assertEquals(Errors.INVALID_CLIENT, response.getError()); + Assertions.assertEquals("Invalid client or Invalid client credentials", response.getErrorDescription()); } @Test public void testClientWithErrors() throws Exception { @@ -1050,9 +1050,9 @@ public void testClientWithErrors() throws Exception { //DeviceAuthorizationGrant not enabled DeviceAuthorizationResponse response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(400, response.getStatusCode()); - Assert.assertEquals(Errors.UNAUTHORIZED_CLIENT, response.getError()); - Assert.assertEquals("Client is not allowed to initiate OAuth 2.0 Device Authorization Grant. The flow is disabled for the client.", response.getErrorDescription()); + Assertions.assertEquals(400, response.getStatusCode()); + Assertions.assertEquals(Errors.UNAUTHORIZED_CLIENT, response.getError()); + Assertions.assertEquals("Client is not allowed to initiate OAuth 2.0 Device Authorization Grant. The flow is disabled for the client.", response.getErrorDescription()); clientRepresentation.getAttributes().put(OAuth2DeviceConfig.OAUTH2_DEVICE_AUTHORIZATION_GRANT_ENABLED, "true"); clientRepresentation.setBearerOnly(true); @@ -1060,9 +1060,9 @@ public void testClientWithErrors() throws Exception { //BearerOnly client response = oauth.device().doDeviceAuthorizationRequest(); - Assert.assertEquals(403, response.getStatusCode()); - Assert.assertEquals(Errors.UNAUTHORIZED_CLIENT, response.getError()); - Assert.assertEquals("Bearer-only applications are not allowed to initiate browser login.", response.getErrorDescription()); + Assertions.assertEquals(403, response.getStatusCode()); + Assertions.assertEquals(Errors.UNAUTHORIZED_CLIENT, response.getError()); + Assertions.assertEquals("Bearer-only applications are not allowed to initiate browser login.", response.getErrorDescription()); } finally { ClientResource client = AdminApiUtil.findClientByClientId(adminClient.realm(REALM_NAME), DEVICE_APP_PUBLIC); @@ -1077,8 +1077,8 @@ public void testClientWithErrors() throws Exception { public void ensureDeviceFlowConfigPresentWhenDeviceFlowIsEnabled() { OIDCConfigurationRepresentation oidcConfigRep = oauth.doWellKnownRequest(); - Assert.assertNotNull("deviceAuthorizationEndpoint should be not null", oidcConfigRep.getDeviceAuthorizationEndpoint()); - Assert.assertNotNull("mtlsEndpointAliases.deviceAuthorizationEndpoint should be not null", oidcConfigRep.getMtlsEndpointAliases().getDeviceAuthorizationEndpoint()); + Assertions.assertNotNull(oidcConfigRep.getDeviceAuthorizationEndpoint(), "deviceAuthorizationEndpoint should be not null"); + Assertions.assertNotNull(oidcConfigRep.getMtlsEndpointAliases().getDeviceAuthorizationEndpoint(), "mtlsEndpointAliases.deviceAuthorizationEndpoint should be not null"); } @Test @@ -1092,17 +1092,17 @@ public void ensureDeviceFlowConfigNotPresentWhenDeviceFlowIsDisabled() throws Ex try { OIDCConfigurationRepresentation oidcConfigRep = oauth.doWellKnownRequest(); - Assert.assertNull("deviceAuthorizationEndpoint should be null", oidcConfigRep.getDeviceAuthorizationEndpoint()); - Assert.assertNull("mtlsEndpointAliases.deviceAuthorizationEndpoint should be null", oidcConfigRep.getMtlsEndpointAliases().getDeviceAuthorizationEndpoint()); + Assertions.assertNull(oidcConfigRep.getDeviceAuthorizationEndpoint(), "deviceAuthorizationEndpoint should be null"); + Assertions.assertNull(oidcConfigRep.getMtlsEndpointAliases().getDeviceAuthorizationEndpoint(), "mtlsEndpointAliases.deviceAuthorizationEndpoint should be null"); try (CloseableHttpResponse response = oauth.httpClient().get().execute(new HttpGet(oauth.getEndpoints().getDeviceAuthorization()))) { - Assert.assertEquals("Should return not found for device auth endpoint", 404, response.getStatusLine().getStatusCode()); + Assertions.assertEquals(404, response.getStatusLine().getStatusCode(), "Should return not found for device auth endpoint"); } oauth.realm(REALM_NAME); oauth.client(DEVICE_APP_PUBLIC); AccessTokenResponse tokenResponse = oauth.device().doDeviceTokenRequest("dummy"); - Assert.assertEquals(OAuthErrorException.UNSUPPORTED_GRANT_TYPE, tokenResponse.getError()); + Assertions.assertEquals(OAuthErrorException.UNSUPPORTED_GRANT_TYPE, tokenResponse.getError()); } finally { testingClient.resetFeature(Profile.Feature.DEVICE_FLOW); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuth2OnlyTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuth2OnlyTest.java index 7eb637324b3b..5dfd54e2ea70 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuth2OnlyTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuth2OnlyTest.java @@ -29,7 +29,6 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; import org.keycloak.testsuite.ActionURIUtils; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.pages.ErrorPage; import org.keycloak.testsuite.util.ClientManager; @@ -41,10 +40,11 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.util.ServerURLs.AUTH_SERVER_SSL_REQUIRED; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for scenarios when 'scope=openid' is missing. Which means we have pure OAuth2 request (not OpenID Connect) @@ -107,20 +107,20 @@ public void testMissingIDToken() { AccessTokenResponse response = oauth.doAccessTokenRequest(code); // IDToken is not there - Assert.assertEquals(200, response.getStatusCode()); - Assert.assertNull(response.getIdToken()); - Assert.assertNotNull(response.getRefreshToken()); + Assertions.assertEquals(200, response.getStatusCode()); + Assertions.assertNull(response.getIdToken()); + Assertions.assertNotNull(response.getRefreshToken()); AccessToken token = oauth.verifyToken(response.getAccessToken()); - Assert.assertEquals(token.getSubject(), loginEvent.getUserId()); + Assertions.assertEquals(token.getSubject(), loginEvent.getUserId()); // Refresh and assert idToken still not present response = oauth.doRefreshTokenRequest(response.getRefreshToken()); - Assert.assertEquals(200, response.getStatusCode()); - Assert.assertNull(response.getIdToken()); + Assertions.assertEquals(200, response.getStatusCode()); + Assertions.assertNull(response.getIdToken()); token = oauth.verifyToken(response.getAccessToken()); - Assert.assertEquals(token.getSubject(), loginEvent.getUserId()); + Assertions.assertEquals(token.getSubject(), loginEvent.getUserId()); } @@ -132,11 +132,11 @@ public void testMissingScopeOpenidInResourceOwnerPasswordCredentialRequest() thr assertEquals(200, response.getStatusCode()); // idToken not present - Assert.assertNull(response.getIdToken()); + Assertions.assertNull(response.getIdToken()); - Assert.assertNotNull(response.getRefreshToken()); + Assertions.assertNotNull(response.getRefreshToken()); AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); - Assert.assertEquals(accessToken.getPreferredUsername(), "test-user@localhost"); + Assertions.assertEquals(accessToken.getPreferredUsername(), "test-user@localhost"); } @@ -162,7 +162,7 @@ public void testMissingRedirectUri() throws Exception { driver.navigate().to(loginFormUrl); errorPage.assertCurrent(); - Assert.assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); + Assertions.assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); events.expectLogin() .error(Errors.INVALID_REDIRECT_URI) .client("more-uris-client") @@ -188,10 +188,10 @@ public void testMissingNonceInOAuth2ImplicitFlow() throws Exception { events.expectLogin().assertEvent(); AuthorizationEndpointResponse response = oauth.parseLoginResponse(); - Assert.assertNull(response.getError()); - Assert.assertNull(response.getCode()); - Assert.assertNull(response.getIdToken()); - Assert.assertNotNull(response.getAccessToken()); + Assertions.assertNull(response.getError()); + Assertions.assertNull(response.getCode()); + Assertions.assertNull(response.getIdToken()); + Assertions.assertNotNull(response.getAccessToken()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthGrantTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthGrantTest.java index ba9347492a5c..4849b8e09e48 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthGrantTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthGrantTest.java @@ -52,16 +52,16 @@ import org.hamcrest.Matchers; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.admin.AdminApiUtil.findClientByClientId; import static org.keycloak.testsuite.auth.page.AuthRealm.TEST; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Viliam Rockai @@ -107,7 +107,7 @@ public void oauthGrantAcceptTest() { grantPage.accept(); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); EventRepresentation loginEvent = events.expectLogin() .client(THIRD_PARTY_APP) @@ -119,25 +119,25 @@ public void oauthGrantAcceptTest() { AccessTokenResponse accessToken = oauth.doAccessTokenRequest(oauth.parseLoginResponse().getCode()); String tokenString = accessToken.getAccessToken(); - Assert.assertNotNull(tokenString); + Assertions.assertNotNull(tokenString); AccessToken token = oauth.verifyToken(tokenString); assertEquals(sessionId, token.getSessionState()); AccessToken.Access realmAccess = token.getRealmAccess(); assertEquals(1, realmAccess.getRoles().size()); - Assert.assertTrue(realmAccess.isUserInRole("user")); + Assertions.assertTrue(realmAccess.isUserInRole("user")); Map resourceAccess = token.getResourceAccess(); assertEquals(1, resourceAccess.size()); assertEquals(1, resourceAccess.get("test-app").getRoles().size()); - Assert.assertTrue(resourceAccess.get("test-app").isUserInRole("customer-user")); + Assertions.assertTrue(resourceAccess.get("test-app").isUserInRole("customer-user")); events.expectCodeToToken(codeId, loginEvent.getSessionId()).client(THIRD_PARTY_APP).assertEvent(); AccountHelper.revokeConsents(adminClient.realm(TEST), DEFAULT_USERNAME, THIRD_PARTY_APP); List> userConsents = AccountHelper.getUserConsents(adminClient.realm(TEST), DEFAULT_USERNAME); - Assert.assertEquals(userConsents.size(), 0); + Assertions.assertEquals(userConsents.size(), 0); assertEquals(0, driver.findElements(By.id("revoke-third-party")).size()); } @@ -179,8 +179,8 @@ public void oauthGrantNotShownWhenAlreadyGranted() throws IOException { // Assert permissions granted on Account mgmt. List> userConsents = AccountHelper.getUserConsents(adminClient.realm(TEST), DEFAULT_USERNAME); - Assert.assertTrue(((List) userConsents.get(0).get("grantedClientScopes")).stream().anyMatch(p -> p.equals("profile"))); - Assert.assertTrue(((List) userConsents.get(0).get("grantedClientScopes")).stream().anyMatch(p -> p.equals("email"))); + Assertions.assertTrue(((List) userConsents.get(0).get("grantedClientScopes")).stream().anyMatch(p -> p.equals("profile"))); + Assertions.assertTrue(((List) userConsents.get(0).get("grantedClientScopes")).stream().anyMatch(p -> p.equals("email"))); // Open login form and assert grantPage not shown oauth.openLoginForm(); @@ -195,7 +195,7 @@ public void oauthGrantNotShownWhenAlreadyGranted() throws IOException { AccountHelper.revokeConsents(adminClient.realm(TEST), DEFAULT_USERNAME, THIRD_PARTY_APP); userConsents = AccountHelper.getUserConsents(adminClient.realm(TEST), DEFAULT_USERNAME); - Assert.assertEquals(userConsents.size(), 0); + Assertions.assertEquals(userConsents.size(), 0); // Open login form again and assert grant Page is shown oauth.openLoginForm(); @@ -233,7 +233,7 @@ public void oauthGrantAddAnotherScope() throws IOException { // Assert new clientScope not yet in account mgmt List> userConsents = AccountHelper.getUserConsents(adminClient.realm(TEST), DEFAULT_USERNAME); - Assert.assertFalse(((List) userConsents.get(0).get("grantedClientScopes")).stream().anyMatch(p -> p.equals("foo-scope"))); + Assertions.assertFalse(((List) userConsents.get(0).get("grantedClientScopes")).stream().anyMatch(p -> p.equals("foo-scope"))); // Show grant page another time. Just new clientScope is on the page oauth.openLoginForm(); @@ -248,13 +248,13 @@ public void oauthGrantAddAnotherScope() throws IOException { // Go to account mgmt. Everything is granted now userConsents = AccountHelper.getUserConsents(adminClient.realm(TEST), DEFAULT_USERNAME); - Assert.assertTrue(((List) userConsents.get(0).get("grantedClientScopes")).stream().anyMatch(p -> p.equals("foo-scope"))); + Assertions.assertTrue(((List) userConsents.get(0).get("grantedClientScopes")).stream().anyMatch(p -> p.equals("foo-scope"))); // Revoke AccountHelper.revokeConsents(adminClient.realm(TEST), DEFAULT_USERNAME, THIRD_PARTY_APP); userConsents = AccountHelper.getUserConsents(adminClient.realm(TEST), DEFAULT_USERNAME); - Assert.assertEquals(userConsents.size(), 0); + Assertions.assertEquals(userConsents.size(), 0); // Cleanup thirdParty.removeDefaultClientScope(fooScopeId); @@ -282,7 +282,7 @@ public void oauthGrantScopeParamRequired() throws Exception { oauth.doLogin(DEFAULT_USERNAME, DEFAULT_PASSWORD); grantPage.assertCurrent(); List grants = grantPage.getDisplayedGrants(); - Assert.assertFalse(grants.contains("foo-scope")); + Assertions.assertFalse(grants.contains("foo-scope")); grantPage.cancel(); events.expectLogin() @@ -296,7 +296,7 @@ public void oauthGrantScopeParamRequired() throws Exception { oauth.doLogin(DEFAULT_USERNAME, DEFAULT_PASSWORD); grantPage.assertCurrent(); grants = grantPage.getDisplayedGrants(); - Assert.assertTrue(grants.contains("foo-scope")); + Assertions.assertTrue(grants.contains("foo-scope")); grantPage.accept(); events.expectLogin() @@ -308,7 +308,7 @@ public void oauthGrantScopeParamRequired() throws Exception { AccountHelper.revokeConsents(adminClient.realm(TEST), DEFAULT_USERNAME, THIRD_PARTY_APP); List> userConsents = AccountHelper.getUserConsents(adminClient.realm(TEST), DEFAULT_USERNAME); - Assert.assertEquals(userConsents.size(), 0); + Assertions.assertEquals(userConsents.size(), 0); // cleanup oauth.scope(null); @@ -343,7 +343,7 @@ public void oauthGrantDynamicScopeParamRequired() throws IOException { oauth.doLogin(DEFAULT_USERNAME, DEFAULT_PASSWORD); grantPage.assertCurrent(); List grants = grantPage.getDisplayedGrants(); - Assert.assertTrue(grants.contains("foo-dynamic-scope: withparam")); + Assertions.assertTrue(grants.contains("foo-dynamic-scope: withparam")); grantPage.accept(); EventRepresentation loginEvent = events.expectLogin() @@ -367,8 +367,8 @@ public void oauthGrantDynamicScopeParamRequired() throws IOException { oauth.doLogin(DEFAULT_USERNAME, DEFAULT_PASSWORD); grantPage.assertCurrent(); grants = grantPage.getDisplayedGrants(); - Assert.assertEquals(1, grants.size()); - Assert.assertTrue(grants.contains("foo-dynamic-scope: withparam")); + Assertions.assertEquals(1, grants.size()); + Assertions.assertTrue(grants.contains("foo-dynamic-scope: withparam")); grantPage.accept(); events.expectLogin() @@ -380,7 +380,7 @@ public void oauthGrantDynamicScopeParamRequired() throws IOException { AccountHelper.revokeConsents(adminClient.realm(TEST), DEFAULT_USERNAME, THIRD_PARTY_APP); List> userConsents = AccountHelper.getUserConsents(adminClient.realm(TEST), DEFAULT_USERNAME); - Assert.assertEquals(userConsents.size(), 0); + Assertions.assertEquals(userConsents.size(), 0); // cleanup oauth.scope(null); @@ -425,13 +425,13 @@ public void oauthGrantClientScopeMappers() throws Exception { // Go to user's application screen List> userConsents = AccountHelper.getUserConsents(adminClient.realm(TEST), DEFAULT_USERNAME); - Assert.assertEquals("third-party", userConsents.get(0).get("clientId")); - Assert.assertTrue(((List) userConsents.get(0).get("grantedClientScopes")).stream().anyMatch(p -> p.equals("foo-addr"))); + Assertions.assertEquals("third-party", userConsents.get(0).get("clientId")); + Assertions.assertTrue(((List) userConsents.get(0).get("grantedClientScopes")).stream().anyMatch(p -> p.equals("foo-addr"))); // Login as admin and see the consent screen of particular user UserResource user = AdminApiUtil.findUserByUsernameId(appRealm, "test-user@localhost"); List> consents = user.getConsents(); - Assert.assertEquals(1, consents.size()); + Assertions.assertEquals(1, consents.size()); // Assert automatically logged another time oauth.openLoginForm(); @@ -446,7 +446,7 @@ public void oauthGrantClientScopeMappers() throws Exception { AccountHelper.revokeConsents(adminClient.realm(TEST), DEFAULT_USERNAME, THIRD_PARTY_APP); userConsents = AccountHelper.getUserConsents(adminClient.realm(TEST), DEFAULT_USERNAME); - Assert.assertEquals(userConsents.size(), 0); + Assertions.assertEquals(userConsents.size(), 0); // Cleanup thirdParty.removeDefaultClientScope(fooScopeId); @@ -468,7 +468,7 @@ public void oauthGrantExpiredAuthSession() throws Exception { errorPage.assertCurrent(); String backToAppLink = errorPage.getBackToApplicationLink(); ClientRepresentation thirdParty = findClientByClientId(adminClient.realm(REALM_NAME), THIRD_PARTY_APP).toRepresentation(); - Assert.assertEquals(backToAppLink, thirdParty.getBaseUrl()); + Assertions.assertEquals(backToAppLink, thirdParty.getBaseUrl()); } // KEYCLOAK-7470 @@ -481,13 +481,13 @@ public void oauthGrantOrderedClientScopes() throws Exception { ClientScopeRepresentation emailRep = emailScope.toRepresentation(); emailRep.getAttributes().put(ClientScopeModel.GUI_ORDER, "1"); emailScope.update(emailRep); - Assert.assertEquals("1", emailRep.getAttributes().get(ClientScopeModel.GUI_ORDER)); + Assertions.assertEquals("1", emailRep.getAttributes().get(ClientScopeModel.GUI_ORDER)); ClientScopeResource profileScope = AdminApiUtil.findClientScopeByName(appRealm, "profile"); ClientScopeRepresentation profileRep = profileScope.toRepresentation(); profileRep.getAttributes().put(ClientScopeModel.GUI_ORDER, "2"); profileScope.update(profileRep); - Assert.assertEquals("2", profileRep.getAttributes().get(ClientScopeModel.GUI_ORDER)); + Assertions.assertEquals("2", profileRep.getAttributes().get(ClientScopeModel.GUI_ORDER)); // Display consent screen --- assert email, then profile oauth.clientId(THIRD_PARTY_APP); @@ -495,15 +495,15 @@ public void oauthGrantOrderedClientScopes() throws Exception { grantPage.assertCurrent(); List displayedScopes = grantPage.getDisplayedGrants(); - Assert.assertEquals("Email address", displayedScopes.get(0)); - Assert.assertEquals("User profile", displayedScopes.get(1)); + Assertions.assertEquals("Email address", displayedScopes.get(0)); + Assertions.assertEquals("User profile", displayedScopes.get(1)); grantPage.accept(); // Update GUI Order --- email=3 emailRep = emailScope.toRepresentation(); emailRep.getAttributes().put(ClientScopeModel.GUI_ORDER, "3"); emailScope.update(emailRep); - Assert.assertEquals("3", emailRep.getAttributes().get(ClientScopeModel.GUI_ORDER)); + Assertions.assertEquals("3", emailRep.getAttributes().get(ClientScopeModel.GUI_ORDER)); // Revoke grant and display consent screen --- assert profile, then email AccountHelper.revokeConsents(adminClient.realm(TEST), DEFAULT_USERNAME, THIRD_PARTY_APP); @@ -511,8 +511,8 @@ public void oauthGrantOrderedClientScopes() throws Exception { oauth.openLoginForm(); grantPage.assertCurrent(); displayedScopes = grantPage.getDisplayedGrants(); - Assert.assertEquals("User profile", displayedScopes.get(0)); - Assert.assertEquals("Email address", displayedScopes.get(1)); + Assertions.assertEquals("User profile", displayedScopes.get(0)); + Assertions.assertEquals("Email address", displayedScopes.get(1)); } @@ -528,7 +528,7 @@ public void oauthGrantUserNotLoggedOutAfterConsentRevoke() throws Exception { grantPage.assertGrants(OAuthGrantPage.PROFILE_CONSENT_TEXT, OAuthGrantPage.EMAIL_CONSENT_TEXT, OAuthGrantPage.ROLES_CONSENT_TEXT); grantPage.accept(); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); EventRepresentation loginEvent = events.expectLogin() .client(THIRD_PARTY_APP) @@ -553,7 +553,7 @@ public void oauthGrantUserNotLoggedOutAfterConsentRevoke() throws Exception { //String codeId = loginEvent.getDetails().get(Details.CODE_ID); String sessionId2 = loginEvent.getSessionId(); - Assert.assertEquals(sessionId, sessionId2); + Assertions.assertEquals(sessionId, sessionId2); // Revert consent adminClient.realm(REALM_NAME).users().get(loginEvent.getUserId()).revokeConsent(THIRD_PARTY_APP); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthProofKeyForCodeExchangeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthProofKeyForCodeExchangeTest.java index 56c1b205487d..16feee9d14bf 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthProofKeyForCodeExchangeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthProofKeyForCodeExchangeTest.java @@ -30,10 +30,10 @@ import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.keycloak.testsuite.util.oauth.AuthorizationEndpointResponse; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.admin.AdminApiUtil.findUserByUsername; @@ -42,9 +42,9 @@ import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; //https://tools.ietf.org/html/rfc7636 @@ -210,9 +210,9 @@ public void accessTokenRequestInPKCEWithoutCodeChallengeWithValidCodeChallengeMe AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); - Assert.assertTrue(errorResponse.isRedirected()); - Assert.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); - Assert.assertEquals(errorResponse.getErrorDescription(), "Missing parameter: code_challenge"); + Assertions.assertTrue(errorResponse.isRedirected()); + Assertions.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); + Assertions.assertEquals(errorResponse.getErrorDescription(), "Missing parameter: code_challenge"); events.expectLogin().error(Errors.INVALID_REQUEST).user((String) null).session((String) null).clearDetails().assertEvent(); } @@ -224,9 +224,9 @@ public void accessTokenRequestInPKCEInvalidUnderCodeChallengeWithS256CodeChallen AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); - Assert.assertTrue(errorResponse.isRedirected()); - Assert.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); - Assert.assertEquals(errorResponse.getErrorDescription(), "Invalid parameter: code_challenge"); + Assertions.assertTrue(errorResponse.isRedirected()); + Assertions.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); + Assertions.assertEquals(errorResponse.getErrorDescription(), "Invalid parameter: code_challenge"); events.expectLogin().error(Errors.INVALID_REQUEST).user((String) null).session((String) null).clearDetails().assertEvent(); } @@ -238,9 +238,9 @@ public void accessTokenRequestInPKCEInvalidOverCodeChallengeWithPlainCodeChallen AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); - Assert.assertTrue(errorResponse.isRedirected()); - Assert.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); - Assert.assertEquals(errorResponse.getErrorDescription(), "Invalid parameter: code_challenge"); + Assertions.assertTrue(errorResponse.isRedirected()); + Assertions.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); + Assertions.assertEquals(errorResponse.getErrorDescription(), "Invalid parameter: code_challenge"); events.expectLogin().error(Errors.INVALID_REQUEST).user((String) null).session((String) null).clearDetails().assertEvent(); } @@ -321,9 +321,9 @@ public void accessTokenRequestInPKCEInvalidCodeChallengeWithS256CodeChallengeMet AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); - Assert.assertTrue(errorResponse.isRedirected()); - Assert.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); - Assert.assertEquals(errorResponse.getErrorDescription(), "Invalid parameter: code_challenge"); + Assertions.assertTrue(errorResponse.isRedirected()); + Assertions.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); + Assertions.assertEquals(errorResponse.getErrorDescription(), "Invalid parameter: code_challenge"); events.expectLogin().error(Errors.INVALID_REQUEST).user((String) null).session((String) null).clearDetails().assertEvent(); } @@ -435,7 +435,7 @@ private void expectSuccessfulResponseFromTokenEndpoint(String codeId, String ses String refreshTokenString = response.getRefreshToken(); RefreshToken refreshToken = oauth.parseRefreshToken(refreshTokenString); - Assert.assertNotNull(refreshTokenString); + Assertions.assertNotNull(refreshTokenString); assertThat(token.getExp() - getCurrentTime(), allOf(greaterThanOrEqualTo(200L), lessThanOrEqualTo(350L))); long actual = refreshToken.getExp() - getCurrentTime(); assertThat(actual, allOf(greaterThanOrEqualTo(1799L - ALLOWED_CLOCK_SKEW), lessThanOrEqualTo(1800L + ALLOWED_CLOCK_SKEW))); @@ -458,8 +458,8 @@ private void expectSuccessfulResponseFromTokenEndpoint(String codeId, String ses assertThat(refreshedToken.getExp() - token.getExp(), allOf(greaterThanOrEqualTo(1L), lessThanOrEqualTo(10L))); assertThat(refreshedRefreshToken.getExp() - refreshToken.getExp(), allOf(greaterThanOrEqualTo(1L), lessThanOrEqualTo(10L))); - Assert.assertNotEquals(token.getId(), refreshedToken.getId()); - Assert.assertNotEquals(refreshToken.getId(), refreshedRefreshToken.getId()); + Assertions.assertNotEquals(token.getId(), refreshedToken.getId()); + Assertions.assertNotEquals(refreshToken.getId(), refreshedRefreshToken.getId()); assertEquals("Bearer", refreshResponse.getTokenType()); @@ -468,14 +468,14 @@ private void expectSuccessfulResponseFromTokenEndpoint(String codeId, String ses // Assert.assertNotEquals("test-user@localhost", refreshedToken.getSubject()); assertEquals(2, refreshedToken.getRealmAccess().getRoles().size()); - Assert.assertTrue(refreshedToken.getRealmAccess().isUserInRole("user")); + Assertions.assertTrue(refreshedToken.getRealmAccess().isUserInRole("user")); assertEquals(1, refreshedToken.getResourceAccess(oauth.getClientId()).getRoles().size()); - Assert.assertTrue(refreshedToken.getResourceAccess(oauth.getClientId()).isUserInRole("customer-user")); + Assertions.assertTrue(refreshedToken.getResourceAccess(oauth.getClientId()).isUserInRole("customer-user")); EventRepresentation refreshEvent = events.expectRefresh(event.getDetails().get(Details.REFRESH_TOKEN_ID), sessionId).assertEvent(); - Assert.assertNotEquals(event.getDetails().get(Details.TOKEN_ID), refreshEvent.getDetails().get(Details.TOKEN_ID)); - Assert.assertNotEquals(event.getDetails().get(Details.REFRESH_TOKEN_ID), refreshEvent.getDetails().get(Details.UPDATED_REFRESH_TOKEN_ID)); + Assertions.assertNotEquals(event.getDetails().get(Details.TOKEN_ID), refreshEvent.getDetails().get(Details.TOKEN_ID)); + Assertions.assertNotEquals(event.getDetails().get(Details.REFRESH_TOKEN_ID), refreshEvent.getDetails().get(Details.UPDATED_REFRESH_TOKEN_ID)); setTimeOffset(0); } @@ -548,9 +548,9 @@ public void accessTokenRequestCodeChallengeMethodMismatchPkceEnforced() throws E AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); - Assert.assertTrue(errorResponse.isRedirected()); - Assert.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); - Assert.assertEquals(errorResponse.getErrorDescription(), "Invalid parameter: code challenge method is not matching the configured one"); + Assertions.assertTrue(errorResponse.isRedirected()); + Assertions.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); + Assertions.assertEquals(errorResponse.getErrorDescription(), "Invalid parameter: code challenge method is not matching the configured one"); events.expectLogin().error(Errors.INVALID_REQUEST).user((String) null).session((String) null).clearDetails().assertEvent(); } finally { @@ -569,9 +569,9 @@ public void accessTokenRequestCodeChallengeMethodMissingPkceEnforced() throws Ex AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); - Assert.assertTrue(errorResponse.isRedirected()); - Assert.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); - Assert.assertEquals(errorResponse.getErrorDescription(), "Missing parameter: code_challenge_method"); + Assertions.assertTrue(errorResponse.isRedirected()); + Assertions.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); + Assertions.assertEquals(errorResponse.getErrorDescription(), "Missing parameter: code_challenge_method"); events.expectLogin().error(Errors.INVALID_REQUEST).user((String) null).session((String) null).clearDetails().assertEvent(); @@ -589,9 +589,9 @@ public void accessTokenRequestCodeChallengeMissingPkceEnforced() throws Exceptio AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); - Assert.assertTrue(errorResponse.isRedirected()); - Assert.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); - Assert.assertEquals(errorResponse.getErrorDescription(), "Missing parameter: code_challenge"); + Assertions.assertTrue(errorResponse.isRedirected()); + Assertions.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); + Assertions.assertEquals(errorResponse.getErrorDescription(), "Missing parameter: code_challenge"); events.expectLogin().error(Errors.INVALID_REQUEST).user((String) null).session((String) null).clearDetails().assertEvent(); @@ -609,9 +609,9 @@ public void accessTokenRequestInvalidCodeChallengePkceEnforced() throws Exceptio AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); - Assert.assertTrue(errorResponse.isRedirected()); - Assert.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); - Assert.assertEquals(errorResponse.getErrorDescription(), "Invalid parameter: code_challenge"); + Assertions.assertTrue(errorResponse.isRedirected()); + Assertions.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); + Assertions.assertEquals(errorResponse.getErrorDescription(), "Invalid parameter: code_challenge"); events.expectLogin().error(Errors.INVALID_REQUEST).user((String) null).session((String) null).clearDetails().assertEvent(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthRedirectUriStateTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthRedirectUriStateTest.java index cec9010b9bda..ec319d73a90a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthRedirectUriStateTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthRedirectUriStateTest.java @@ -23,11 +23,11 @@ import org.keycloak.protocol.oidc.utils.OIDCResponseType; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.oauth.AuthorizationEndpointResponse; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; public class OAuthRedirectUriStateTest extends AbstractTestRealmKeycloakTest { @@ -43,7 +43,7 @@ public void clientConfiguration() { void assertStateReflected(String state) { AuthorizationEndpointResponse response = oauth.loginForm().state(state).doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response.getCode()); + Assertions.assertNotNull(response.getCode()); URL url; try { @@ -51,7 +51,7 @@ void assertStateReflected(String state) { } catch (MalformedURLException e) { throw new RuntimeException(e); } - Assert.assertTrue(url.getQuery().contains("state=" + state)); + Assertions.assertTrue(url.getQuery().contains("state=" + state)); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthRedirectUriTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthRedirectUriTest.java index 52210cb4a7ff..1d3b86466a1f 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthRedirectUriTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthRedirectUriTest.java @@ -52,15 +52,15 @@ import org.apache.http.impl.client.HttpClients; import org.hamcrest.Matchers; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.util.oauth.OAuthClient.APP_ROOT; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Viliam Rockai @@ -178,24 +178,24 @@ public void addTestRealms(List testRealms) { public void testNoParam() throws IOException { oauth.redirectUri(null); oauth.openLoginForm(); - Assert.assertTrue(errorPage.isCurrent()); - Assert.assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); + Assertions.assertTrue(errorPage.isCurrent()); + Assertions.assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); } @Test public void testRelativeUri() throws IOException { oauth.redirectUri("/foo/../bar"); oauth.openLoginForm(); - Assert.assertTrue(errorPage.isCurrent()); - Assert.assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); + Assertions.assertTrue(errorPage.isCurrent()); + Assertions.assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); } @Test public void testFileUri() throws IOException { oauth.redirectUri("file://test"); oauth.openLoginForm(); - Assert.assertTrue(errorPage.isCurrent()); - Assert.assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); + Assertions.assertTrue(errorPage.isCurrent()); + Assertions.assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); } @Test @@ -204,8 +204,8 @@ public void testNoParamMultipleValidUris() throws IOException { try { oauth.redirectUri(null); oauth.openLoginForm(); - Assert.assertTrue(errorPage.isCurrent()); - Assert.assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); + Assertions.assertTrue(errorPage.isCurrent()); + Assertions.assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); } finally { ClientManager.realm(adminClient.realm("test")).clientId("test-app").removeRedirectUris("http://localhost:8180/app2"); } @@ -219,7 +219,7 @@ public void testNoParamNoValidUris() throws IOException { oauth.redirectUri(null); oauth.openLoginForm(); - Assert.assertTrue(errorPage.isCurrent()); + Assertions.assertTrue(errorPage.isCurrent()); assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); } finally { ClientManager.realm(adminClient.realm("test")).clientId("test-app").addRedirectUris("http://localhost:8180/auth/realms/master/app/auth/*"); @@ -234,7 +234,7 @@ public void testNoValidUris() throws IOException { oauth.redirectUri(null); oauth.openLoginForm(); - Assert.assertTrue(errorPage.isCurrent()); + Assertions.assertTrue(errorPage.isCurrent()); assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); } finally { ClientManager.realm(adminClient.realm("test")).clientId("test-app").addRedirectUris("http://localhost:8180/auth/realms/master/app/auth/*"); @@ -246,11 +246,11 @@ public void testValid() throws IOException { oauth.redirectUri(APP_ROOT + "/auth"); AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response.getCode()); + Assertions.assertNotNull(response.getCode()); URL url = new URL(driver.getCurrentUrl()); - Assert.assertTrue(url.toString().startsWith(APP_ROOT)); - Assert.assertTrue(url.getQuery().contains("code=")); - Assert.assertTrue(url.getQuery().contains("state=")); + Assertions.assertTrue(url.toString().startsWith(APP_ROOT)); + Assertions.assertTrue(url.getQuery().contains("code=")); + Assertions.assertTrue(url.getQuery().contains("state=")); } @Test @@ -258,7 +258,7 @@ public void testInvalid() throws IOException { oauth.redirectUri("http://localhost:8180/app2"); oauth.openLoginForm(); - Assert.assertTrue(errorPage.isCurrent()); + Assertions.assertTrue(errorPage.isCurrent()); assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); } @@ -267,12 +267,12 @@ public void testWithParams() throws IOException { oauth.redirectUri(APP_ROOT + "/auth?key=value"); AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response.getCode()); + Assertions.assertNotNull(response.getCode()); URL url = new URL(driver.getCurrentUrl()); - Assert.assertTrue(url.toString().startsWith(APP_ROOT)); - Assert.assertTrue(url.getQuery().contains("key=value")); - Assert.assertTrue(url.getQuery().contains("state=")); - Assert.assertTrue(url.getQuery().contains("code=")); + Assertions.assertTrue(url.toString().startsWith(APP_ROOT)); + Assertions.assertTrue(url.getQuery().contains("key=value")); + Assertions.assertTrue(url.getQuery().contains("state=")); + Assertions.assertTrue(url.getQuery().contains("code=")); } @Test @@ -283,10 +283,10 @@ public void testWithFragment() throws IOException { oauth.redirectUri(APP_ROOT + "/auth#key=value"); AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response.getCode()); + Assertions.assertNotNull(response.getCode()); URL url = new URL(driver.getCurrentUrl()); - Assert.assertTrue(url.toString().startsWith(APP_ROOT)); - Assert.assertTrue(url.toString().contains("key=value")); + Assertions.assertTrue(url.toString().startsWith(APP_ROOT)); + Assertions.assertTrue(url.toString().contains("key=value")); } @Test @@ -469,12 +469,12 @@ public void okThenNull() throws IOException { oauth.doLogin("test-user@localhost", "password"); String code = oauth.parseLoginResponse().getCode(); - Assert.assertNotNull(code); + Assertions.assertNotNull(code); oauth.redirectUri(null); AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code); - Assert.assertEquals("Expected 400, but got something else", 400, tokenResponse.getStatusCode()); + Assertions.assertEquals(400, tokenResponse.getStatusCode(), "Expected 400, but got something else"); } private void checkRedirectUri(String redirectUri, boolean expectValid) throws IOException { @@ -489,18 +489,18 @@ private void checkRedirectUri(String redirectUri, boolean expectValid, boolean c if (!expectValid) { oauth.openLoginForm(); - Assert.assertTrue(errorPage.isCurrent()); - Assert.assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); + Assertions.assertTrue(errorPage.isCurrent()); + Assertions.assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); } else { if (!checkCodeToToken) { oauth.openLoginForm(); - Assert.assertTrue(loginPage.isCurrent()); - Assert.assertFalse(errorPage.isCurrent()); + Assertions.assertTrue(loginPage.isCurrent()); + Assertions.assertFalse(errorPage.isCurrent()); } else { oauth.doLogin("test-user@localhost", "password"); String code = oauth.parseLoginResponse().getCode(); - Assert.assertNotNull(code); + Assertions.assertNotNull(code); // Test that browser URL where Keycloak redirected user matches with the used redirectUri String browserUrlAfterRedirectFromKeycloak = KeycloakUriBuilder.fromUri(driver.getCurrentUrl()) @@ -513,13 +513,13 @@ private void checkRedirectUri(String redirectUri, boolean expectValid, boolean c if (Constants.INSTALLED_APP_URN.equals(redirectUri)) { assertThat(browserUrlAfterRedirectFromKeycloak, Matchers.endsWith("oauth/oob")); } else { - Assert.assertEquals(redirectUri, browserUrlAfterRedirectFromKeycloak); + Assertions.assertEquals(redirectUri, browserUrlAfterRedirectFromKeycloak); } oauth.redirectUri(redirectUri); AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code); - Assert.assertEquals("Expected success, but got error: " + tokenResponse.getError(), 200, tokenResponse.getStatusCode()); + Assertions.assertEquals(200, tokenResponse.getStatusCode(), "Expected success, but got error: " + tokenResponse.getError()); oauth.doLogout(tokenResponse.getRefreshToken()); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthScopeInTokenResponseTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthScopeInTokenResponseTest.java index fb27be029a73..c949fa86fbe8 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthScopeInTokenResponseTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OAuthScopeInTokenResponseTest.java @@ -21,14 +21,14 @@ import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.util.oauth.AccessTokenResponse; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; //OIDC Financial API Read Only Profile : scope MUST be returned in the response from Token Endpoint public class OAuthScopeInTokenResponseTest extends AbstractKeycloakTest { @@ -228,7 +228,7 @@ private void expectSuccessfulResponseFromTokenEndpoint(String code, String expec log.info("receivedScopes = " + response.getScope()); Collection expectedScopes = Arrays.asList(expectedScope.split(" ")); Collection receivedScopes = Arrays.asList(response.getScope().split(" ")); - Assert.assertTrue(expectedScopes.containsAll(receivedScopes) && receivedScopes.containsAll(expectedScopes)); + Assertions.assertTrue(expectedScopes.containsAll(receivedScopes) && receivedScopes.containsAll(expectedScopes)); oauth.doLogout(response.getRefreshToken()); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OIDCProtocolMappersTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OIDCProtocolMappersTest.java index 8036c1cc8a3c..364aa9b2a22f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OIDCProtocolMappersTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OIDCProtocolMappersTest.java @@ -81,6 +81,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.OAuth2Constants.SCOPE_PROFILE; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; @@ -106,11 +107,11 @@ import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Marek Posolda @@ -191,7 +192,7 @@ public void testTokenScriptMapping() throws Exception { assertEquals("hello_test-user@localhost", accessToken.getOtherClaims().get("computed-via-script")); assertEquals(Arrays.asList("A","B"), accessToken.getOtherClaims().get("multiValued-via-script")); Object o = accessToken.getOtherClaims().get("computed-json-via-script"); - assertTrue("Computed json object should be a map", o instanceof Map); + assertTrue(o instanceof Map, "Computed json object should be a map"); Map map = (Map)o; assertEquals(map.get("int"), 42); assertEquals(map.get("bool"), true); @@ -491,7 +492,7 @@ public void testTokenMapping() { assertTrue(departments.contains("finance") && departments.contains("development")); assertTrue(accessToken.getRealmAccess().getRoles().contains("hardcoded")); assertTrue(accessToken.getRealmAccess().getRoles().contains("realm-user")); - Assert.assertNull(accessToken.getResourceAccess("test-app")); + Assertions.assertNull(accessToken.getResourceAccess("test-app")); assertTrue(accessToken.getResourceAccess("app").getRoles().contains("hardcoded")); // Assert audiences added through AudienceResolve mapper @@ -842,13 +843,13 @@ public void testUserRolesMovedFromAccessTokenProperties() throws Exception { AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); // Assert roles are not on their original positions - Assert.assertNull(accessToken.getRealmAccess()); - Assert.assertTrue(accessToken.getResourceAccess().isEmpty()); + Assertions.assertNull(accessToken.getRealmAccess()); + Assertions.assertTrue(accessToken.getResourceAccess().isEmpty()); // KEYCLOAK-8481 Assert that accessToken JSON doesn't have "realm_access" or "resource_access" fields in it String accessTokenJson = new String(new JWSInput(response.getAccessToken()).getContent(), StandardCharsets.UTF_8); - Assert.assertFalse(accessTokenJson.contains("realm_access")); - Assert.assertFalse(accessTokenJson.contains("resource_access")); + Assertions.assertFalse(accessTokenJson.contains("realm_access")); + Assertions.assertFalse(accessTokenJson.contains("resource_access")); // Assert both realm and client roles on the new position. Hardcoded role should be here as well Map cst1 = (Map) accessToken.getOtherClaims().get("custom"); @@ -885,20 +886,20 @@ public void testRolesAndAllowedOriginsRemovedFromAccessToken() throws Exception AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); // Assert web origins are not in the token - Assert.assertNull(accessToken.getAllowedOrigins()); + Assertions.assertNull(accessToken.getAllowedOrigins()); // Assert roles are not in the token - Assert.assertNull(accessToken.getRealmAccess()); - Assert.assertTrue(accessToken.getResourceAccess().isEmpty()); + Assertions.assertNull(accessToken.getRealmAccess()); + Assertions.assertTrue(accessToken.getResourceAccess().isEmpty()); // Assert client not in the token audience. Just in "issuedFor" - Assert.assertEquals("test-app", accessToken.getIssuedFor()); - Assert.assertFalse(accessToken.hasAudience("test-app")); + Assertions.assertEquals("test-app", accessToken.getIssuedFor()); + Assertions.assertFalse(accessToken.hasAudience("test-app")); // Assert IDToken still has "test-app" as an audience IDToken idToken = oauth.verifyIDToken(response.getIdToken()); - Assert.assertEquals("test-app", idToken.getIssuedFor()); - Assert.assertTrue(idToken.hasAudience("test-app")); + Assertions.assertEquals("test-app", idToken.getIssuedFor()); + Assertions.assertTrue(idToken.hasAudience("test-app")); } finally { // Revert testApp.addDefaultClientScope(allowedOriginsScope.getId()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OfflineTokenMigrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OfflineTokenMigrationTest.java index 9fa94aa8089a..b2c2d6a7cee6 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OfflineTokenMigrationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OfflineTokenMigrationTest.java @@ -41,8 +41,8 @@ import org.keycloak.util.JsonSerialization; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * Test for simulating token refresh with the offline tokens created in older Keycloak versions. @@ -97,7 +97,7 @@ private void testOfflineTokenMigration(OfflineTokenConverter offlineTokenConvert oauth.client("direct-grant", "password"); AccessTokenResponse tokenResponse = oauth.doPasswordGrantRequest("test-user@localhost", "password"); - Assert.assertNull(tokenResponse.getErrorDescription()); + Assertions.assertNull(tokenResponse.getErrorDescription()); String offlineTokenString = tokenResponse.getRefreshToken(); // Convert offline token to the format of some old Keycloak version @@ -120,7 +120,7 @@ public Class getResultClass() { // Check it is possible to successfully refresh with the modified offline token AccessTokenResponse response = oauth.doRefreshTokenRequest(modifiedOfflineToken); AccessToken refreshedToken = oauth.verifyToken(response.getAccessToken()); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); } public interface OfflineTokenConverter extends Serializable, BiFunction { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/PreAuthorizedGrantTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/PreAuthorizedGrantTest.java index fdee035abde2..c1a68b5b4f1d 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/PreAuthorizedGrantTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/PreAuthorizedGrantTest.java @@ -46,7 +46,7 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; @EnableFeature(value = Profile.Feature.OID4VC_VCI, skipRestart = true) @EnableFeature(value = Profile.Feature.OID4VC_VCI_PREAUTH_CODE, skipRestart = true) @@ -65,7 +65,7 @@ public void testPreAuthorizedGrant() throws Exception { String preAuthorizedCode = getTestingClient().testing(TEST_REALM_NAME).getPreAuthorizedCode(TEST_REALM_NAME, userSessionId, "test-app", Time.currentTime() + 30); AccessTokenResponse accessTokenResponse = postCode(preAuthorizedCode); - assertEquals("An access token should have successfully been returned.", HttpStatus.SC_OK, accessTokenResponse.getStatusCode()); + assertEquals(HttpStatus.SC_OK, accessTokenResponse.getStatusCode(), "An access token should have successfully been returned."); } @Test @@ -73,7 +73,7 @@ public void testPreAuthorizedGrantExpired() throws Exception { String userSessionId = getUserSession(); String preAuthorizedCode = getTestingClient().testing(TEST_REALM_NAME).getPreAuthorizedCode(TEST_REALM_NAME, userSessionId, "test-app", Time.currentTime() - 30); AccessTokenResponse accessTokenResponse = postCode(preAuthorizedCode); - assertEquals("An expired code should not get an access token.", HttpStatus.SC_BAD_REQUEST, accessTokenResponse.getStatusCode()); + assertEquals(HttpStatus.SC_BAD_REQUEST, accessTokenResponse.getStatusCode(), "An expired code should not get an access token."); } @Test @@ -81,7 +81,7 @@ public void testPreAuthorizedGrantInvalidCode() throws Exception { // assure that a session exists. getUserSession(); AccessTokenResponse accessTokenResponse = postCode("invalid-code"); - assertEquals("An invalid code should not get an access token.", HttpStatus.SC_BAD_REQUEST, accessTokenResponse.getStatusCode()); + assertEquals(HttpStatus.SC_BAD_REQUEST, accessTokenResponse.getStatusCode(), "An invalid code should not get an access token."); } @Test @@ -95,7 +95,7 @@ public void testPreAuthorizedGrantNoCode() throws Exception { post.setEntity(formEntity); AccessTokenResponse accessTokenResponse = new AccessTokenResponse(httpClient.execute(post)); - assertEquals("If no code is provided, no access token should be returned.", HttpStatus.SC_BAD_REQUEST, accessTokenResponse.getStatusCode()); + assertEquals(HttpStatus.SC_BAD_REQUEST, accessTokenResponse.getStatusCode(), "If no code is provided, no access token should be returned."); } /** @@ -115,8 +115,7 @@ public void testPreAuthorizedGrantRealmDisabled() throws Exception { .getPreAuthorizedCode(TEST_REALM_NAME, userSessionId, "test-app", Time.currentTime() + 30); AccessTokenResponse accessTokenResponse = postCode(preAuthorizedCode); - assertEquals("Pre-authorized grant should be forbidden when verifiable credentials are disabled.", - HttpStatus.SC_FORBIDDEN, accessTokenResponse.getStatusCode()); + assertEquals(HttpStatus.SC_FORBIDDEN, accessTokenResponse.getStatusCode(), "Pre-authorized grant should be forbidden when verifiable credentials are disabled."); } finally { // Re-enable verifiable credentials so other tests see the default behavior RealmRepresentation realmRepReset = adminClient.realm(TEST_REALM_NAME).toRepresentation(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/RPInitiatedLogoutTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/RPInitiatedLogoutTest.java index e9d7f833f657..a6d290dddf31 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/RPInitiatedLogoutTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/RPInitiatedLogoutTest.java @@ -42,7 +42,6 @@ import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.admin.ApiUtil; @@ -73,6 +72,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.NoSuchElementException; import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlEquals; @@ -80,11 +80,11 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Test for OIDC RP-Initiated Logout - https://openid.net/specs/openid-connect-rpinitiated-1_0.html @@ -182,7 +182,7 @@ public void logoutRedirectWithLogoutConfirmationEnabled() throws Exception { // With logout confirmation enabled, an info page should be shown instead of an immediate redirect infoPage.assertCurrent(); - Assert.assertEquals("You are logged out", infoPage.getInfo()); + Assertions.assertEquals("You are logged out", infoPage.getInfo()); // The info page should contain a link back to application (redirectUri). Use the link to finish. infoPage.clickBackToApplicationLink(); @@ -501,7 +501,7 @@ public void logoutWithoutIdTokenHintWithoutPostLogoutRedirectUri() { // Info page present. No link "back to the application" infoPage.assertCurrent(); - Assert.assertEquals("You are logged out", infoPage.getInfo()); + Assertions.assertEquals("You are logged out", infoPage.getInfo()); try { logoutConfirmPage.clickBackToApplicationLink(); fail(); @@ -523,7 +523,7 @@ public void logoutWithIdTokenHintWithoutPostLogoutRedirectUri() { // Info page present. Link "back to the application" present infoPage.assertCurrent(); - Assert.assertEquals("You are logged out", infoPage.getInfo()); + Assertions.assertEquals("You are logged out", infoPage.getInfo()); events.expectLogout(tokenResponse.getSessionState()).removeDetail(Details.REDIRECT_URI).assertEvent(); MatcherAssert.assertThat(false, is(isSessionActive(tokenResponse.getSessionState()))); @@ -551,7 +551,7 @@ public void logoutExpiredConfirmationAction() { logoutConfirmPage.confirmLogout(); errorPage.assertCurrent(); - Assert.assertEquals("Logout failed", errorPage.getError()); + Assertions.assertEquals("Logout failed", errorPage.getError()); events.expectLogoutError(Errors.EXPIRED_CODE).assertEvent(); MatcherAssert.assertThat(true, is(isSessionActive(tokenResponse.getSessionState()))); @@ -582,7 +582,7 @@ public void logoutExpiredConfirmationAuthSession() { logoutConfirmPage.confirmLogout(); errorPage.assertCurrent(); - Assert.assertEquals("Logout failed", errorPage.getError()); + Assertions.assertEquals("Logout failed", errorPage.getError()); events.expectLogoutError(Errors.SESSION_EXPIRED).assertEvent(); @@ -612,7 +612,7 @@ public void logoutExpiredConfirmationAuthSessionWithClient() { logoutConfirmPage.confirmLogout(); errorPage.assertCurrent(); - Assert.assertEquals("Logout failed", errorPage.getError()); + Assertions.assertEquals("Logout failed", errorPage.getError()); events.expectLogoutError(Errors.SESSION_EXPIRED).assertEvent(); @@ -650,8 +650,8 @@ public void logoutWithUiLocalesAndClientIdParameter() throws IOException { oauth.logoutForm().withClientId().uiLocales("cs").open(); // Assert logout confirmation page. Session still exists. Assert czech language on logout page - Assert.assertEquals("Odhlašování", PageUtils.getPageTitle(driver)); // Logging out - Assert.assertEquals("Čeština", logoutConfirmPage.getLanguageDropdownText()); + Assertions.assertEquals("Odhlašování", PageUtils.getPageTitle(driver)); // Logging out + Assertions.assertEquals("Čeština", logoutConfirmPage.getLanguageDropdownText()); MatcherAssert.assertThat(true, is(isSessionActive(tokenResponse.getSessionState()))); events.assertEmpty(); logoutConfirmPage.confirmLogout(); @@ -661,7 +661,7 @@ public void logoutWithUiLocalesAndClientIdParameter() throws IOException { MatcherAssert.assertThat(false, is(isSessionActive(tokenResponse.getSessionState()))); infoPage.assertCurrent(); - Assert.assertEquals("Odhlášení bylo úspěšné", infoPage.getInfo()); // Logout success message + Assertions.assertEquals("Odhlášení bylo úspěšné", infoPage.getInfo()); // Logout success message infoPage.clickBackToApplicationLinkCs(); WaitUtils.waitForPageToLoad(); MatcherAssert.assertThat(driver.getCurrentUrl(), endsWith("/app/auth")); @@ -685,7 +685,7 @@ public void logoutWithClientIdAndExpiredCode() throws IOException { logoutConfirmPage.confirmLogout(); errorPage.assertCurrent(); - Assert.assertEquals("Logout failed", errorPage.getError()); + Assertions.assertEquals("Logout failed", errorPage.getError()); events.expectLogoutError(Errors.EXPIRED_CODE).assertEvent(); MatcherAssert.assertThat(true, is(isSessionActive(tokenResponse.getSessionState()))); @@ -709,7 +709,7 @@ public void logoutWithClientIdAndWithoutIdTokenHint() { // Assert logout confirmation page as id_token_hint was not sent. Session still exists. Assert default language on logout page (English) logoutConfirmPage.assertCurrent(); - Assert.assertEquals("English", logoutConfirmPage.getLanguageDropdownText()); + Assertions.assertEquals("English", logoutConfirmPage.getLanguageDropdownText()); MatcherAssert.assertThat(true, is(isSessionActive(tokenResponse.getSessionState()))); events.assertEmpty(); logoutConfirmPage.confirmLogout(); @@ -803,7 +803,7 @@ public void logoutWithBadClientId() { .idTokenHint(tokenResponse.getIdToken()).open(); errorPage.assertCurrent(); - Assert.assertEquals("Invalid parameter: id_token_hint", errorPage.getError()); + Assertions.assertEquals("Invalid parameter: id_token_hint", errorPage.getError()); events.expectLogoutError(Errors.INVALID_TOKEN).client("third-party").assertEvent(); MatcherAssert.assertThat(true, is(isSessionActive(tokenResponse.getSessionState()))); @@ -815,7 +815,7 @@ public void logoutWithBadClientId() { .open(); errorPage.assertCurrent(); - Assert.assertEquals("Invalid redirect uri", errorPage.getError()); + Assertions.assertEquals("Invalid redirect uri", errorPage.getError()); events.expectLogoutError(Errors.INVALID_REDIRECT_URI).assertEvent(); MatcherAssert.assertThat(true, is(isSessionActive(tokenResponse.getSessionState()))); @@ -828,7 +828,7 @@ public void logoutWithBadClientId() { // Info page present. No link "back to the application" infoPage.assertCurrent(); - Assert.assertEquals("You are logged out", infoPage.getInfo()); + Assertions.assertEquals("You are logged out", infoPage.getInfo()); try { logoutConfirmPage.clickBackToApplicationLink(); fail(); @@ -874,8 +874,8 @@ public void logoutWithPostRequest() throws IOException { postParams.put(OIDCLoginProtocol.UI_LOCALES_PARAM, "cs"); URLUtils.sendPOSTRequestWithWebDriver(oauth.getEndpoints().getLogout(), postParams); - Assert.assertEquals("Odhlašování", PageUtils.getPageTitle(driver)); // Logging out - Assert.assertEquals("Čeština", logoutConfirmPage.getLanguageDropdownText()); + Assertions.assertEquals("Odhlašování", PageUtils.getPageTitle(driver)); // Logging out + Assertions.assertEquals("Čeština", logoutConfirmPage.getLanguageDropdownText()); logoutConfirmPage.confirmLogout(); WaitUtils.waitForPageToLoad(); @@ -894,21 +894,21 @@ public void testLocalizationPreferenceDuringLogout() throws IOException { // Set localization to the user account to "cs". Ensure that it is shown try (UserAttributeUpdater userUpdater = UserAttributeUpdater.forUserByUsername(testRealm(), "test-user@localhost").setAttribute(UserModel.LOCALE, "cs").update()) { oauth.openLogoutForm(); - Assert.assertEquals("Odhlašování", PageUtils.getPageTitle(driver)); // Logging out - Assert.assertEquals("Čeština", logoutConfirmPage.getLanguageDropdownText()); + Assertions.assertEquals("Odhlašování", PageUtils.getPageTitle(driver)); // Logging out + Assertions.assertEquals("Čeština", logoutConfirmPage.getLanguageDropdownText()); // Set localization together with ui_locales param. User localization should have preference oauth.logoutForm().uiLocales("de").open(); - Assert.assertEquals("Odhlašování", PageUtils.getPageTitle(driver)); // Logging out - Assert.assertEquals("Čeština", logoutConfirmPage.getLanguageDropdownText()); + Assertions.assertEquals("Odhlašování", PageUtils.getPageTitle(driver)); // Logging out + Assertions.assertEquals("Čeština", logoutConfirmPage.getLanguageDropdownText()); } UserAttributeUpdater.forUserByUsername(testRealm(), "test-user@localhost").removeAttribute(UserModel.LOCALE).update(); // Removed localization from user account. Now localization set by ui_locales parameter should be used oauth.logoutForm().uiLocales("de").open(); - Assert.assertEquals("Abmelden", PageUtils.getPageTitle(driver)); // Logging out - Assert.assertEquals("Deutsch", logoutConfirmPage.getLanguageDropdownText()); + Assertions.assertEquals("Abmelden", PageUtils.getPageTitle(driver)); // Logging out + Assertions.assertEquals("Deutsch", logoutConfirmPage.getLanguageDropdownText()); logoutConfirmPage.confirmLogout(); WaitUtils.waitForPageToLoad(); events.expectLogout(tokenResponse.getSessionState()).client("account").removeDetail(Details.REDIRECT_URI).assertEvent(); @@ -916,8 +916,8 @@ public void testLocalizationPreferenceDuringLogout() throws IOException { // Remove ui_locales from logout request. Default locale should be set tokenResponse = loginUser(); oauth.logoutForm().open(); - Assert.assertEquals("Logging out", PageUtils.getPageTitle(driver)); - Assert.assertEquals("English", logoutConfirmPage.getLanguageDropdownText()); + Assertions.assertEquals("Logging out", PageUtils.getPageTitle(driver)); + Assertions.assertEquals("English", logoutConfirmPage.getLanguageDropdownText()); logoutConfirmPage.confirmLogout(); WaitUtils.waitForPageToLoad(); events.expectLogout(tokenResponse.getSessionState()).client("account").removeDetail(Details.REDIRECT_URI).assertEvent(); @@ -936,18 +936,18 @@ public void testLocalizationDuringLogout() throws IOException { logoutConfirmPage.assertCurrent(); logoutConfirmPage.openLanguage("Čeština"); - Assert.assertEquals("Odhlašování", PageUtils.getPageTitle(driver)); // Logging out - Assert.assertEquals("Čeština", logoutConfirmPage.getLanguageDropdownText()); + Assertions.assertEquals("Odhlašování", PageUtils.getPageTitle(driver)); // Logging out + Assertions.assertEquals("Čeština", logoutConfirmPage.getLanguageDropdownText()); logoutConfirmPage.openLanguage("English"); - Assert.assertEquals("Logging out", PageUtils.getPageTitle(driver)); - Assert.assertEquals("English", logoutConfirmPage.getLanguageDropdownText()); + Assertions.assertEquals("Logging out", PageUtils.getPageTitle(driver)); + Assertions.assertEquals("English", logoutConfirmPage.getLanguageDropdownText()); // Logout logoutConfirmPage.confirmLogout(); infoPage.assertCurrent(); - Assert.assertEquals("You are logged out", infoPage.getInfo()); + Assertions.assertEquals("You are logged out", infoPage.getInfo()); try { logoutConfirmPage.clickBackToApplicationLink(); fail(); @@ -962,31 +962,31 @@ public void testLocalizationDuringLogout() throws IOException { .uiLocales("de") .open(); - Assert.assertEquals("Abmelden", PageUtils.getPageTitle(driver)); // Logging out - Assert.assertEquals("Deutsch", logoutConfirmPage.getLanguageDropdownText()); + Assertions.assertEquals("Abmelden", PageUtils.getPageTitle(driver)); // Logging out + Assertions.assertEquals("Deutsch", logoutConfirmPage.getLanguageDropdownText()); // Change locale. It should have preference over the "de" set by ui_locales logoutConfirmPage.openLanguage("Čeština"); - Assert.assertEquals("Odhlašování", PageUtils.getPageTitle(driver)); // Logging out - Assert.assertEquals("Čeština", logoutConfirmPage.getLanguageDropdownText()); + Assertions.assertEquals("Odhlašování", PageUtils.getPageTitle(driver)); // Logging out + Assertions.assertEquals("Čeština", logoutConfirmPage.getLanguageDropdownText()); // Logout logoutConfirmPage.confirmLogout(); infoPage.assertCurrent(); - Assert.assertEquals("Odhlášení bylo úspěšné", infoPage.getInfo()); // Logout success message + Assertions.assertEquals("Odhlášení bylo úspěšné", infoPage.getInfo()); // Logout success message // Change locale on the info page (AuthenticationSession does not exists on server at this point) infoPage.openLanguage("English"); - Assert.assertEquals("You are logged out", infoPage.getInfo()); // Logout success message + Assertions.assertEquals("You are logged out", infoPage.getInfo()); // Logout success message // Change locale again infoPage.openLanguage("Čeština"); - Assert.assertEquals("Odhlášení bylo úspěšné", infoPage.getInfo()); // Logout success message + Assertions.assertEquals("Odhlášení bylo úspěšné", infoPage.getInfo()); // Logout success message // Refresh page driver.navigate().refresh(); - Assert.assertEquals("Odhlášení bylo úspěšné", infoPage.getInfo()); // Logout success message + Assertions.assertEquals("Odhlášení bylo úspěšné", infoPage.getInfo()); // Logout success message infoPage.clickBackToApplicationLinkCs(); WaitUtils.waitForPageToLoad(); @@ -1002,7 +1002,7 @@ public void testIncorrectChangingParameters() throws IOException { // Display the logout page. Then change the localization to Czech and logout oauth.logoutForm().uiLocales("de").open(); - Assert.assertEquals("Abmelden", PageUtils.getPageTitle(driver)); // Logging out + Assertions.assertEquals("Abmelden", PageUtils.getPageTitle(driver)); // Logging out logoutConfirmPage.openLanguage("English"); // Try to manually change value of parameter tab_id to some incorrect value. Error should be shown in this case @@ -1015,7 +1015,7 @@ public void testIncorrectChangingParameters() throws IOException { WaitUtils.waitForPageToLoad(); errorPage.assertCurrent(); - Assert.assertEquals("Logout failed", errorPage.getError()); + Assertions.assertEquals("Logout failed", errorPage.getError()); events.expectLogoutError(Errors.SESSION_EXPIRED).assertEvent(); } @@ -1125,7 +1125,7 @@ private void doLogoutTestWithPostLogoutRedirectAttributeAndSpecifiedPostLogoutRe // Assert logout confirmation page as id_token_hint was not sent. Session still exists. Assert default language on logout page (English) logoutConfirmPage.assertCurrent(); - Assert.assertEquals("English", logoutConfirmPage.getLanguageDropdownText()); + Assertions.assertEquals("English", logoutConfirmPage.getLanguageDropdownText()); MatcherAssert.assertThat(true, is(isSessionActive(tokenResponse.getSessionState()))); events.assertEmpty(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ResourceOwnerPasswordCredentialsGrantTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ResourceOwnerPasswordCredentialsGrantTest.java index 0e73b09c24bb..6c6998044f27 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ResourceOwnerPasswordCredentialsGrantTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ResourceOwnerPasswordCredentialsGrantTest.java @@ -52,7 +52,6 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.testsuite.AbstractKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.admin.ApiUtil; @@ -75,11 +74,12 @@ import org.apache.http.message.BasicNameValuePair; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stian Thorgersen @@ -176,7 +176,7 @@ public void grantAccessTokenUsername() throws Exception { grantAccessToken("direct-login", "resource-owner"); // Check that count of authSessions is same as before authentication (as authentication session was removed) - Assert.assertEquals(authSessionsBefore, getAuthenticationSessionsCount()); + Assertions.assertEquals(authSessionsBefore, getAuthenticationSessionsCount()); } @Test @@ -306,7 +306,7 @@ public void grantAccessTokenInvalidTotp() throws Exception { .assertEvent(); // Check that count of authSessions is same as before authentication (as authentication session was removed) - Assert.assertEquals(authSessionsBefore, getAuthenticationSessionsCount()); + Assertions.assertEquals(authSessionsBefore, getAuthenticationSessionsCount()); } private void grantAccessToken(String login, String clientId) throws Exception { @@ -336,7 +336,7 @@ private void grantAccessToken(String userId, String login, String clientId, Stri .removeDetail(Details.CONSENT) .assertEvent(); - Assert.assertTrue(login.equals(accessToken.getPreferredUsername()) || login.equals(accessToken.getEmail())); + Assertions.assertTrue(login.equals(accessToken.getPreferredUsername()) || login.equals(accessToken.getEmail())); assertEquals(accessToken.getSessionState(), refreshToken.getSessionState()); @@ -409,7 +409,7 @@ private void grantRequest(String expectedRefreshAlg, String expectedAccessAlg) t .removeDetail(Details.CONSENT) .assertEvent(); - Assert.assertTrue(login.equals(accessToken.getPreferredUsername()) || login.equals(accessToken.getEmail())); + Assertions.assertTrue(login.equals(accessToken.getPreferredUsername()) || login.equals(accessToken.getEmail())); assertEquals(accessToken.getSessionState(), refreshToken.getSessionState()); @@ -554,7 +554,7 @@ public void grantAccessTokenVerifyEmail() throws Exception { UserManager.realm(realmResource).username("test-user@localhost").removeRequiredAction(UserModel.RequiredAction.VERIFY_EMAIL.toString()); // Check that count of authSessions is same as before authentication (as authentication session was removed) - Assert.assertEquals(authSessionsBefore, getAuthenticationSessionsCount()); + Assertions.assertEquals(authSessionsBefore, getAuthenticationSessionsCount()); } @Test @@ -668,7 +668,7 @@ public void grantAccessTokenInvalidUserCredentialsPerf() throws Exception { String errorMessage = String.format("Times in ms of %d attempts: For invalid password: %d. For invalid username: %d", count, sumInvalidPasswordMs, sumInvalidUsernameMs); // The times should be very similar. Using the bigger difference just to avoid flakiness (Before the fix, the difference was like 3 times shorter time for invalid-username, which allowed quite accurate username enumeration) - Assert.assertTrue(errorMessage, sumInvalidUsernameMs * 2 > sumInvalidPasswordMs); + Assertions.assertTrue(sumInvalidUsernameMs * 2 > sumInvalidPasswordMs, errorMessage); } private long perfTest(int actionsCount, String actionMessage, RunnableWithException action) throws Exception { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ServiceAccountTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ServiceAccountTest.java index e689406bfbc8..caeb2d1a42c9 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ServiceAccountTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ServiceAccountTest.java @@ -60,9 +60,9 @@ import com.fasterxml.jackson.databind.JsonNode; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.rules.ExpectedException; import static org.hamcrest.MatcherAssert.assertThat; @@ -70,10 +70,10 @@ import static org.hamcrest.Matchers.emptyOrNullString; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Marek Posolda @@ -190,9 +190,9 @@ public void clientCredentialsAuthSuccess() throws Exception { assertEquals(accessToken.getSessionState(), refreshToken.getSessionState()); System.out.println("Access token other claims: " + accessToken.getOtherClaims()); - Assert.assertEquals("service-account-cl-refresh-on", accessToken.getOtherClaims().get(ServiceAccountConstants.CLIENT_ID)); - Assert.assertTrue(accessToken.getOtherClaims().containsKey(ServiceAccountConstants.CLIENT_ADDRESS)); - Assert.assertTrue(accessToken.getOtherClaims().containsKey(ServiceAccountConstants.CLIENT_HOST)); + Assertions.assertEquals("service-account-cl-refresh-on", accessToken.getOtherClaims().get(ServiceAccountConstants.CLIENT_ID)); + Assertions.assertTrue(accessToken.getOtherClaims().containsKey(ServiceAccountConstants.CLIENT_ADDRESS)); + Assertions.assertTrue(accessToken.getOtherClaims().containsKey(ServiceAccountConstants.CLIENT_HOST)); AccessTokenResponse refreshedResponse = oauth.doRefreshTokenRequest(response.getRefreshToken()); @@ -300,7 +300,7 @@ public void changeClientIdTest() throws Exception { assertEquals(200, response.getStatusCode()); AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); - Assert.assertEquals("updated-client", accessToken.getOtherClaims().get(ServiceAccountConstants.CLIENT_ID)); + Assertions.assertEquals("updated-client", accessToken.getOtherClaims().get(ServiceAccountConstants.CLIENT_ID)); // Username updated after client ID changed events.expectClientLogin() @@ -379,7 +379,7 @@ public void clientCredentialsAuthSuccessWithoutRefreshToken_revokeToken() throws .assertEvent(); // Check that it is not possible to introspect token anymore - Assert.assertFalse(getIntrospectionResponse(tokenString)); + Assertions.assertFalse(getIntrospectionResponse(tokenString)); events.expect(EventType.INTROSPECT_TOKEN_ERROR) .client("service-account-cl") @@ -411,15 +411,15 @@ private String clientCredentialsAuthSuccessWithoutRefreshTokenImpl() throws Exce assertEquals(200, response.getStatusCode()); String tokenString = response.getAccessToken(); - Assert.assertNotNull("Access-Token should be present", tokenString); + Assertions.assertNotNull(tokenString, "Access-Token should be present"); AccessToken accessToken = oauth.verifyToken(tokenString); - Assert.assertNull(accessToken.getSessionState()); - Assert.assertNull("Refresh-Token should not be present", response.getRefreshToken()); + Assertions.assertNull(accessToken.getSessionState()); + Assertions.assertNull(response.getRefreshToken(), "Refresh-Token should not be present"); AccessTokenContext ctx = testingClient.testing("test").getTokenContext(accessToken.getId()); - Assert.assertEquals(ctx.getSessionType(), AccessTokenContext.SessionType.TRANSIENT); - Assert.assertEquals(ctx.getTokenType(), AccessTokenContext.TokenType.REGULAR); - Assert.assertEquals(ctx.getGrantType(), OAuth2Constants.CLIENT_CREDENTIALS); + Assertions.assertEquals(ctx.getSessionType(), AccessTokenContext.SessionType.TRANSIENT); + Assertions.assertEquals(ctx.getTokenType(), AccessTokenContext.TokenType.REGULAR); + Assertions.assertEquals(ctx.getGrantType(), OAuth2Constants.CLIENT_CREDENTIALS); events.expectClientLogin() .client("service-account-cl") @@ -434,7 +434,7 @@ private String clientCredentialsAuthSuccessWithoutRefreshTokenImpl() throws Exce assertThat(clientSessionStats, empty()); // Check that token is possible to introspect - Assert.assertTrue(getIntrospectionResponse(tokenString)); + Assertions.assertTrue(getIntrospectionResponse(tokenString)); events.expect(EventType.INTROSPECT_TOKEN) .client("service-account-cl") .user(AssertEvents.isUUID()) @@ -494,9 +494,9 @@ private void clientCredentialsAuthSuccessWithRefreshToken(String expectedRefresh assertEquals(accessToken.getSessionState(), refreshToken.getSessionState()); System.out.println("Access token other claims: " + accessToken.getOtherClaims()); - Assert.assertEquals("service-account-cl-refresh-on", accessToken.getOtherClaims().get(ServiceAccountConstants.CLIENT_ID)); - Assert.assertTrue(accessToken.getOtherClaims().containsKey(ServiceAccountConstants.CLIENT_ADDRESS)); - Assert.assertTrue(accessToken.getOtherClaims().containsKey(ServiceAccountConstants.CLIENT_HOST)); + Assertions.assertEquals("service-account-cl-refresh-on", accessToken.getOtherClaims().get(ServiceAccountConstants.CLIENT_ID)); + Assertions.assertTrue(accessToken.getOtherClaims().containsKey(ServiceAccountConstants.CLIENT_ADDRESS)); + Assertions.assertTrue(accessToken.getOtherClaims().containsKey(ServiceAccountConstants.CLIENT_HOST)); AccessTokenResponse refreshedResponse = oauth.doRefreshTokenRequest(response.getRefreshToken()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ServiceAccountUserProfileTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ServiceAccountUserProfileTest.java index b7cfe561d1bd..2da6c1c9f887 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ServiceAccountUserProfileTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/ServiceAccountUserProfileTest.java @@ -46,11 +46,11 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Marek Posolda @@ -183,7 +183,7 @@ public void testAttributesAreNotRequired() { final RealmResource realm = adminClient.realm("test"); UPConfig config = realm.users().userProfile().getConfiguration(); UPAttribute lastName = config.getAttribute(UserModel.LAST_NAME); - assertNotNull("The attribute lastName is not defined in User Profile", lastName); + assertNotNull(lastName, "The attribute lastName is not defined in User Profile"); UPAttributeRequired upRequired = new UPAttributeRequired(Set.of( UserProfileConstants.ROLE_ADMIN, UserProfileConstants.ROLE_USER), null); lastName.setRequired(upRequired); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenEndpointCorsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenEndpointCorsTest.java index c9859b568004..3e86324867f7 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenEndpointCorsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenEndpointCorsTest.java @@ -23,9 +23,9 @@ import static org.keycloak.testsuite.AbstractAdminTest.loadJson; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Martin Kanis diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenIntrospectionTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenIntrospectionTest.java index fbb498a19dad..a71b607e88f2 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenIntrospectionTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenIntrospectionTest.java @@ -70,12 +70,13 @@ import org.jboss.arquillian.graphene.page.Page; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Pedro Igor @@ -205,8 +206,8 @@ public void testInvalidClientCredentials() throws Exception { oauth.client("confidential-cli", "bad_credential"); IntrospectionResponse tokenResponse = oauth.doIntrospectionAccessTokenRequest(accessTokenResponse.getAccessToken()); - Assert.assertEquals("Authentication failed.", tokenResponse.getErrorDescription()); - Assert.assertEquals(OAuthErrorException.INVALID_REQUEST, tokenResponse.getError()); + Assertions.assertEquals("Authentication failed.", tokenResponse.getErrorDescription()); + Assertions.assertEquals(OAuthErrorException.INVALID_REQUEST, tokenResponse.getError()); } @Test @@ -252,7 +253,7 @@ public void testIntrospectRefreshTokenAfterUserSessionLogoutAndLoginAgain() thro oauth.fillLoginForm("test-user@localhost", "password"); events.expectLogin().assertEvent(); - Assert.assertFalse(loginPage.isCurrent()); + Assertions.assertFalse(loginPage.isCurrent()); String code = oauth.parseLoginResponse().getCode(); AccessTokenResponse tokenResponse2 = oauth.doAccessTokenRequest(code); @@ -275,8 +276,8 @@ public void testPublicClientCredentialsNotAllowed() throws Exception { oauth.client("public-cli"); IntrospectionResponse tokenResponse = oauth.doIntrospectionAccessTokenRequest(accessTokenResponse.getAccessToken()); - Assert.assertEquals("Client not allowed.", tokenResponse.getErrorDescription()); - Assert.assertEquals(OAuthErrorException.INVALID_REQUEST, tokenResponse.getError()); + Assertions.assertEquals("Client not allowed.", tokenResponse.getErrorDescription()); + Assertions.assertEquals(OAuthErrorException.INVALID_REQUEST, tokenResponse.getError()); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenRevocationCorsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenRevocationCorsTest.java index b06289a415bd..7ddb32962fc5 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenRevocationCorsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenRevocationCorsTest.java @@ -33,10 +33,10 @@ import static org.keycloak.testsuite.AbstractAdminTest.loadJson; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Yoshiyuki Tabata diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenRevocationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenRevocationTest.java index 31fc7456f618..3d4657570029 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenRevocationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/TokenRevocationTest.java @@ -41,7 +41,6 @@ import org.keycloak.representations.idm.UserSessionRepresentation; import org.keycloak.representations.oidc.TokenMetadataRepresentation; import org.keycloak.testsuite.AbstractKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.broker.util.SimpleHttpDefault; import org.keycloak.testsuite.pages.LoginPage; @@ -67,14 +66,15 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.AssertEvents.isTokenId; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Yoshiyuki Tabata @@ -214,7 +214,7 @@ public void testRevokeOfflineTokenWithOnlineSSOSession() throws Exception { AccessTokenResponse tokenResponse2 = login("test-app", "test-user@localhost", "password"); // Session IDs of "offline" and online session are same for now. This may change in the future - Assert.assertEquals(tokenResponse1.getSessionState(), tokenResponse2.getSessionState()); + Assertions.assertEquals(tokenResponse1.getSessionState(), tokenResponse2.getSessionState()); isTokenEnabled(tokenResponse2, "test-app"); @@ -377,7 +377,7 @@ private void isAccessTokenDisabled(String accessTokenString, String clientId) th try (Keycloak adminClient = Keycloak.getInstance(OAuthClient.AUTH_SERVER_ROOT, "test", "test-app", accessTokenString, AdminClientUtil.getSSLContextWithTruststore())) { try { adminClient.realms().realm("test").toRepresentation(); - Assert.fail("Not expected to obtain realm"); + Assertions.fail("Not expected to obtain realm"); } catch (NotAuthorizedException nae) { // Expected } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/UserInfoEndpointCorsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/UserInfoEndpointCorsTest.java index e324ae3b0809..0d5c7662ee6c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/UserInfoEndpointCorsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/UserInfoEndpointCorsTest.java @@ -21,8 +21,8 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; public class UserInfoEndpointCorsTest extends AbstractKeycloakTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/hok/HoKTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/hok/HoKTest.java index d56bb797c6e9..09f78ba4f9d2 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/hok/HoKTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/hok/HoKTest.java @@ -18,6 +18,7 @@ import org.keycloak.OAuthErrorException; import org.keycloak.admin.client.resource.ClientResource; import org.keycloak.common.util.KeystoreUtil; +import org.keycloak.constants.AdapterConstants; import org.keycloak.crypto.Algorithm; import org.keycloak.crypto.KeyUse; import org.keycloak.events.Details; @@ -41,7 +42,6 @@ import org.keycloak.representations.oidc.TokenMetadataRepresentation; import org.keycloak.testsuite.AbstractKeycloakTest; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.client.KeycloakTestingClient; @@ -64,6 +64,7 @@ import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebDriver; import static org.keycloak.testsuite.admin.AdminApiUtil.findUserByUsername; @@ -73,10 +74,10 @@ import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public class HoKTest extends AbstractTestRealmKeycloakTest { @@ -354,7 +355,7 @@ public void refreshTokenRequestByHoKRefreshTokenWithClientCertificate() throws E RefreshToken refreshToken = oauth.parseRefreshToken(refreshTokenString); EventRepresentation tokenEvent = events.expectCodeToToken(codeId, sessionId).assertEvent(); - Assert.assertNotNull(refreshTokenString); + Assertions.assertNotNull(refreshTokenString); assertEquals("Bearer", tokenResponse.getTokenType()); assertThat(token.getExp() - getCurrentTime(), allOf(greaterThanOrEqualTo(200L), lessThanOrEqualTo(350L))); long actual = refreshToken.getExp() - getCurrentTime(); @@ -394,7 +395,7 @@ public void refreshTokenRequestByRefreshTokenWithoutClientCertificate() throws E String refreshTokenString = tokenResponse.getRefreshToken(); RefreshToken refreshToken = oauth.parseRefreshToken(refreshTokenString); - Assert.assertNotNull(refreshTokenString); + Assertions.assertNotNull(refreshTokenString); assertEquals("Bearer", tokenResponse.getTokenType()); assertThat(token.getExp() - getCurrentTime(), allOf(greaterThanOrEqualTo(200L), lessThanOrEqualTo(350L))); long actual = refreshToken.getExp() - getCurrentTime(); @@ -442,8 +443,8 @@ private void expectSuccessfulResponseFromTokenEndpoint(OAuthClient oauth, String assertThat(refreshedToken.getExp() - token.getExp(), allOf(greaterThanOrEqualTo(1L), lessThanOrEqualTo(10L))); assertThat(refreshedRefreshToken.getExp() - refreshToken.getExp(), allOf(greaterThanOrEqualTo(1L), lessThanOrEqualTo(10L))); - Assert.assertNotEquals(token.getId(), refreshedToken.getId()); - Assert.assertNotEquals(refreshToken.getId(), refreshedRefreshToken.getId()); + Assertions.assertNotEquals(token.getId(), refreshedToken.getId()); + Assertions.assertNotEquals(refreshToken.getId(), refreshedRefreshToken.getId()); assertEquals("Bearer", response.getTokenType()); @@ -452,14 +453,14 @@ private void expectSuccessfulResponseFromTokenEndpoint(OAuthClient oauth, String // Assert.assertNotEquals("test-user@localhost", token.getSubject()); assertEquals(2, refreshedToken.getRealmAccess().getRoles().size()); - Assert.assertTrue(refreshedToken.getRealmAccess().isUserInRole("user")); + Assertions.assertTrue(refreshedToken.getRealmAccess().isUserInRole("user")); assertEquals(1, refreshedToken.getResourceAccess(oauth.getClientId()).getRoles().size()); - Assert.assertTrue(refreshedToken.getResourceAccess(oauth.getClientId()).isUserInRole("customer-user")); + Assertions.assertTrue(refreshedToken.getResourceAccess(oauth.getClientId()).isUserInRole("customer-user")); EventRepresentation refreshEvent = events.expectRefresh(tokenEvent.getDetails().get(Details.REFRESH_TOKEN_ID), sessionId).user(refreshToken.getSubject()).assertEvent(); - Assert.assertNotEquals(tokenEvent.getDetails().get(Details.TOKEN_ID), refreshEvent.getDetails().get(Details.TOKEN_ID)); - Assert.assertNotEquals(tokenEvent.getDetails().get(Details.REFRESH_TOKEN_ID), refreshEvent.getDetails().get(Details.UPDATED_REFRESH_TOKEN_ID)); + Assertions.assertNotEquals(tokenEvent.getDetails().get(Details.TOKEN_ID), refreshEvent.getDetails().get(Details.TOKEN_ID)); + Assertions.assertNotEquals(tokenEvent.getDetails().get(Details.REFRESH_TOKEN_ID), refreshEvent.getDetails().get(Details.UPDATED_REFRESH_TOKEN_ID)); setTimeOffset(0); } @@ -596,7 +597,8 @@ private String execPreProcessPostLogout() throws Exception { oauth.doLogin("test-user@localhost", "password"); String code = oauth.parseLoginResponse().getCode(); - AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code); + AccessTokenResponse tokenResponse = oauth.accessTokenRequest(code) + .param(AdapterConstants.CLIENT_SESSION_STATE, "client-session").send(); verifyHoKTokenDefaultCertThumbPrint(tokenResponse); return tokenResponse.getRefreshToken(); @@ -616,26 +618,26 @@ public void accessTokenRequestWithClientCertificateInHybridFlowWithCodeIDToken() EventRepresentation loginEvent = events.expectLogin().assertEvent(); AuthorizationEndpointResponse authzResponse = oauth.parseLoginResponse(); - Assert.assertNotNull(authzResponse.getSessionState()); + Assertions.assertNotNull(authzResponse.getSessionState()); List idTokens = testAuthzResponseAndRetrieveIDTokens(authzResponse, loginEvent); for (IDToken idToken : idTokens) { - Assert.assertEquals(nonce, idToken.getNonce()); - Assert.assertEquals(authzResponse.getSessionState(), idToken.getSessionState()); + Assertions.assertEquals(nonce, idToken.getNonce()); + Assertions.assertEquals(authzResponse.getSessionState(), idToken.getSessionState()); } } protected List testAuthzResponseAndRetrieveIDTokens(AuthorizationEndpointResponse authzResponse, EventRepresentation loginEvent) { - Assert.assertEquals(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); + Assertions.assertEquals(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); // IDToken from the authorization response - Assert.assertNull(authzResponse.getAccessToken()); + Assertions.assertNull(authzResponse.getAccessToken()); String idTokenStr = authzResponse.getIdToken(); IDToken idToken = oauth.verifyIDToken(idTokenStr); // Validate "c_hash" - Assert.assertNull(idToken.getAccessTokenHash()); - Assert.assertNotNull(idToken.getCodeHash()); - Assert.assertEquals(idToken.getCodeHash(), HashUtils.accessTokenHash(Algorithm.RS256, authzResponse.getCode())); + Assertions.assertNull(idToken.getAccessTokenHash()); + Assertions.assertNotNull(idToken.getCodeHash()); + Assertions.assertEquals(idToken.getCodeHash(), HashUtils.accessTokenHash(Algorithm.RS256, authzResponse.getCode())); // IDToken exchanged for the code IDToken idToken2 = sendTokenRequestAndGetIDToken(loginEvent); @@ -770,7 +772,7 @@ private void verifyHoKTokenCertThumbPrint(AccessTokenResponse response, String c jws = new JWSInput(response.getAccessToken()); at = jws.readJsonContent(AccessToken.class); } catch (JWSInputException e) { - Assert.fail(e.toString()); + Assertions.fail(e.toString()); } assertTrue(MessageDigest.isEqual(certThumbPrint.getBytes(), at.getConfirmation().getCertThumbprint().getBytes())); @@ -780,7 +782,7 @@ private void verifyHoKTokenCertThumbPrint(AccessTokenResponse response, String c jws = new JWSInput(response.getRefreshToken()); rt = jws.readJsonContent(RefreshToken.class); } catch (JWSInputException e) { - Assert.fail(e.toString()); + Assertions.fail(e.toString()); } assertTrue(MessageDigest.isEqual(certThumbPrint.getBytes(), rt.getConfirmation().getCertThumbprint().getBytes())); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/par/ParEndpointTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/par/ParEndpointTest.java index 1552b1562a3a..5ff57c083f0e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/par/ParEndpointTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/par/ParEndpointTest.java @@ -24,8 +24,8 @@ import org.keycloak.protocol.oidc.par.endpoints.ParEndpoint; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.OAuth2Constants.AUTHORIZATION_DETAILS; @@ -40,7 +40,7 @@ public void testFlattenDecodedFormParametersRetainAuthorizationDetails() { ParEndpoint.flattenDecodedFormParametersToParamsMap(decodedFormParameters, params); - Assert.assertEquals(authorizationDetails, params.get(AUTHORIZATION_DETAILS)); + Assertions.assertEquals(authorizationDetails, params.get(AUTHORIZATION_DETAILS)); } @Test @@ -51,7 +51,7 @@ public void testFlattenDecodedFormParametersMultipleValues() { ParEndpoint.flattenDecodedFormParametersToParamsMap(decodedFormParameters, params); - Assert.assertEquals("paramValue1", params.get("param")); + Assertions.assertEquals("paramValue1", params.get("param")); } @Test @@ -62,7 +62,7 @@ public void testFlattenDecodedFormParametersSingleValue() { ParEndpoint.flattenDecodedFormParametersToParamsMap(decodedFormParameters, params); - Assert.assertEquals("single", params.get("param")); + Assertions.assertEquals("single", params.get("param")); } @Test @@ -73,7 +73,7 @@ public void testFlattenDecodedFormParametersNullValue() { ParEndpoint.flattenDecodedFormParametersToParamsMap(decodedFormParameters, params); - Assert.assertNull(params.get("param")); + Assertions.assertNull(params.get("param")); } @Test @@ -85,7 +85,7 @@ public void testFlattenDecodedFormParametersValueWithNull() { ParEndpoint.flattenDecodedFormParametersToParamsMap(decodedFormParameters, params); - Assert.assertEquals("value", params.get("param")); + Assertions.assertEquals("value", params.get("param")); } @Test @@ -97,6 +97,6 @@ public void testFlattenDecodedFormParametersMultipleDistinctValues() { ParEndpoint.flattenDecodedFormParametersToParamsMap(decodedFormParameters, params); - Assert.assertEquals("valueAAA", params.get("param")); + Assertions.assertEquals("valueAAA", params.get("param")); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/par/ParTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/par/ParTest.java index 96a86ff0bde9..fa4113e55a6d 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/par/ParTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/par/ParTest.java @@ -71,8 +71,8 @@ import org.keycloak.testsuite.util.oauth.ParResponse; import org.keycloak.util.JsonSerialization; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.OAuthErrorException.INVALID_GRANT; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; @@ -82,12 +82,12 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ParTest extends AbstractClientPoliciesTest { @@ -853,7 +853,7 @@ public void testFailureNotIssuedParUsed() throws Exception { String state = "testFailureNotIssuedParUsed"; oauth.loginForm().requestUri(IMAGINARY_REQUEST_URI).state(state).open(); AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); - Assert.assertFalse(errorResponse.isRedirected()); + Assertions.assertFalse(errorResponse.isRedirected()); } // PAR request_uri used twice @@ -897,7 +897,7 @@ public void testFailureParUsedTwice() throws Exception { state = "testFailureParUsedTwice2"; oauth.loginForm().requestUri(requestUri).state(state).open(); AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); - Assert.assertFalse(errorResponse.isRedirected()); + Assertions.assertFalse(errorResponse.isRedirected()); } // PAR request_uri used by other client @@ -942,7 +942,7 @@ public void testFailureParUsedByOtherClient() throws Exception { String state = "testFailureParUsedByOtherClient"; oauth.loginForm().state(state).requestUri(requestUri).open(); AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); - Assert.assertFalse(errorResponse.isRedirected()); + Assertions.assertFalse(errorResponse.isRedirected()); } // not PAR by PAR required client @@ -1004,7 +1004,7 @@ public void testFailureParExpired() throws Exception { String state = "testFailureParExpired"; oauth.loginForm().state(state).requestUri(requestUri).open(); AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); - Assert.assertFalse(errorResponse.isRedirected()); + Assertions.assertFalse(errorResponse.isRedirected()); } // client authentication failed diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/par/ParWithDPoPTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/par/ParWithDPoPTest.java index 34fb2a27ac3f..bfe293204bd1 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/par/ParWithDPoPTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/par/ParWithDPoPTest.java @@ -65,8 +65,8 @@ import static org.keycloak.testsuite.util.ClientPoliciesUtil.generateEcdsaKey; import static org.keycloak.testsuite.util.ClientPoliciesUtil.generateSignedDPoPProof; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ParWithDPoPTest extends AbstractClientPoliciesTest { @Rule diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/rar/AbstractRARParserTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/rar/AbstractRARParserTest.java index 04d7198bddc2..53e27a958d2e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/rar/AbstractRARParserTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/rar/AbstractRARParserTest.java @@ -41,7 +41,7 @@ import org.junit.Before; import org.junit.Rule; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** @@ -107,7 +107,7 @@ protected AuthorizationRequestContextHolder fetchAuthorizationRequestContextHold .collect(Collectors.toList()); return new AuthorizationRequestContextHolder(authorizationRequestHolders); }, AuthorizationRequestContextHolder.class); - assertNotNull("the fetched AuthorizationRequestContext can't be null", authorizationRequestContextHolder); + assertNotNull(authorizationRequestContextHolder, "the fetched AuthorizationRequestContext can't be null"); return authorizationRequestContextHolder; } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/rar/DynamicScopesRARParseTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/rar/DynamicScopesRARParseTest.java index 287372408fc0..4bb78d96c0ab 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/rar/DynamicScopesRARParseTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/rar/DynamicScopesRARParseTest.java @@ -36,10 +36,10 @@ import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.arquillian.annotation.EnableFeature; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Daniel Gozalo @@ -68,7 +68,7 @@ public void generatedAuthorizationRequestsShouldMatchDefaultScopes() { authorizationRequestHolders.stream().map(authorizationRequestHolder -> authorizationRequestHolder.getAuthorizationDetails().getScopeNameFromCustomData()) .collect(Collectors.toSet())); - Assert.assertTrue(authorizationRequestHolders.stream() + Assertions.assertTrue(authorizationRequestHolders.stream() .map(AuthorizationRequestContextHolder.AuthorizationRequestHolder::getAuthorizationDetails) .allMatch(rep -> rep.getType().equalsIgnoreCase(AuthorizationDetailsJSONRepresentation.STATIC_SCOPE_RAR_TYPE))); } @@ -104,7 +104,7 @@ public void generatedAuthorizationRequestsShouldMatchRequestedAndDefaultScopes() authorizationRequestHolders.stream().map(authorizationRequestHolder -> authorizationRequestHolder.getAuthorizationDetails().getScopeNameFromCustomData()) .collect(Collectors.toSet())); - Assert.assertTrue(authorizationRequestHolders.stream() + Assertions.assertTrue(authorizationRequestHolders.stream() .map(AuthorizationRequestContextHolder.AuthorizationRequestHolder::getAuthorizationDetails) .allMatch(rep -> rep.getType().equalsIgnoreCase(AuthorizationDetailsJSONRepresentation.STATIC_SCOPE_RAR_TYPE))); @@ -138,7 +138,7 @@ public void generatedAuthorizationRequestsShouldMatchRequestedDynamicAndDefaultS assertEquals(defScopes.size(), authorizationRequestHolders.size() - 1); - Assert.assertFalse(authorizationRequestHolders.stream() + Assertions.assertFalse(authorizationRequestHolders.stream() .map(AuthorizationRequestContextHolder.AuthorizationRequestHolder::getAuthorizationDetails) .allMatch(rep -> rep.getType().equalsIgnoreCase(AuthorizationDetailsJSONRepresentation.STATIC_SCOPE_RAR_TYPE))); @@ -146,10 +146,10 @@ public void generatedAuthorizationRequestsShouldMatchRequestedDynamicAndDefaultS .filter(authorizationRequestHolder -> authorizationRequestHolder.getAuthorizationDetails().getType().equalsIgnoreCase(AuthorizationDetailsJSONRepresentation.DYNAMIC_SCOPE_RAR_TYPE)) .findAny(); - Assert.assertTrue(authorizationRequestContextHolderOpt.isPresent()); + Assertions.assertTrue(authorizationRequestContextHolderOpt.isPresent()); AuthorizationRequestContextHolder.AuthorizationRequestHolder authorizationRequestHolder = authorizationRequestContextHolderOpt.get(); - Assert.assertTrue(authorizationRequestHolder.getAuthorizationDetails().getScopeNameFromCustomData().equalsIgnoreCase("dynamic-scope:param")); - Assert.assertTrue(authorizationRequestHolder.getAuthorizationDetails().getCustomData().get("scope_parameter").equals("param")); + Assertions.assertTrue(authorizationRequestHolder.getAuthorizationDetails().getScopeNameFromCustomData().equalsIgnoreCase("dynamic-scope:param")); + Assertions.assertTrue(authorizationRequestHolder.getAuthorizationDetails().getCustomData().get("scope_parameter").equals("param")); testApp.removeOptionalClientScope(scopeId); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/ClientTokenExchangeSAML2Test.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/ClientTokenExchangeSAML2Test.java index 5aee0dae2031..769a358ec0c5 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/ClientTokenExchangeSAML2Test.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/ClientTokenExchangeSAML2Test.java @@ -66,7 +66,6 @@ import org.keycloak.services.resources.admin.fgap.AdminPermissionManagement; import org.keycloak.services.resources.admin.fgap.AdminPermissions; import org.keycloak.testsuite.AbstractKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.arquillian.annotation.DisableFeature; import org.keycloak.testsuite.arquillian.annotation.EnableFeature; @@ -78,6 +77,7 @@ import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -86,7 +86,7 @@ import static org.keycloak.protocol.saml.SamlProtocol.SAML_ASSERTION_CONSUMER_URL_POST_ATTRIBUTE; import static org.keycloak.testsuite.auth.page.AuthRealm.TEST; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Hiroyuki Wada @@ -245,8 +245,8 @@ public void testExchangeToSAML2SignedAssertion() throws Exception { String accessToken = response.getAccessToken(); TokenVerifier accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); - Assert.assertEquals(token.getPreferredUsername(), "user"); - Assert.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); + Assertions.assertEquals(token.getPreferredUsername(), "user"); + Assertions.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); { response = oauth.tokenExchangeRequest(accessToken).audience(SAML_SIGNED_TARGET).requestedTokenType(OAuth2Constants.SAML2_TOKEN_TYPE).send(); @@ -255,27 +255,27 @@ public void testExchangeToSAML2SignedAssertion() throws Exception { String assertionXML = new String(Base64Url.decode(exchangedTokenString), StandardCharsets.UTF_8); // Verify issued_token_type - Assert.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType()); + Assertions.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType()); // Verify assertion Element assertionElement = DocumentUtil.getDocument(assertionXML).getDocumentElement(); - Assert.assertTrue(AssertionUtil.isSignedElement(assertionElement)); + Assertions.assertTrue(AssertionUtil.isSignedElement(assertionElement)); AssertionType assertion = (AssertionType) SAMLParser.getInstance().parse(assertionElement); - Assert.assertTrue(AssertionUtil.isSignatureValid(assertionElement, publicKeyFromString())); + Assertions.assertTrue(AssertionUtil.isSignatureValid(assertionElement, publicKeyFromString())); // Expires - Assert.assertEquals(60, response.getExpiresIn()); + Assertions.assertEquals(60, response.getExpiresIn()); // Audience AudienceRestrictionType aud = (AudienceRestrictionType) assertion.getConditions().getConditions().get(0); - Assert.assertEquals(SAML_SIGNED_TARGET, aud.getAudience().get(0).toString()); + Assertions.assertEquals(SAML_SIGNED_TARGET, aud.getAudience().get(0).toString()); // NameID - Assert.assertEquals("user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue()); + Assertions.assertEquals("user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue()); // Role mapping List roles = AssertionUtil.getRoles(assertion, null); - Assert.assertTrue(roles.contains("example")); + Assertions.assertTrue(roles.contains("example")); } { @@ -286,29 +286,29 @@ public void testExchangeToSAML2SignedAssertion() throws Exception { String assertionXML = new String(Base64Url.decode(exchangedTokenString), StandardCharsets.UTF_8); // Verify issued_token_type - Assert.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType()); + Assertions.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType()); // Verify assertion Element assertionElement = DocumentUtil.getDocument(assertionXML).getDocumentElement(); - Assert.assertTrue(AssertionUtil.isSignedElement(assertionElement)); + Assertions.assertTrue(AssertionUtil.isSignedElement(assertionElement)); AssertionType assertion = (AssertionType) SAMLParser.getInstance().parse(assertionElement); - Assert.assertTrue(AssertionUtil.isSignatureValid(assertionElement, publicKeyFromString())); + Assertions.assertTrue(AssertionUtil.isSignatureValid(assertionElement, publicKeyFromString())); // Audience AudienceRestrictionType aud = (AudienceRestrictionType) assertion.getConditions().getConditions().get(0); - Assert.assertEquals(SAML_SIGNED_TARGET, aud.getAudience().get(0).toString()); + Assertions.assertEquals(SAML_SIGNED_TARGET, aud.getAudience().get(0).toString()); // NameID - Assert.assertEquals("user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue()); + Assertions.assertEquals("user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue()); // Role mapping List roles = AssertionUtil.getRoles(assertion, null); - Assert.assertTrue(roles.contains("example")); + Assertions.assertTrue(roles.contains("example")); } { oauth.client("illegal", "secret"); response = oauth.tokenExchangeRequest(accessToken).audience(SAML_SIGNED_TARGET).requestedTokenType(OAuth2Constants.SAML2_TOKEN_TYPE).send(); - Assert.assertEquals(403, response.getStatusCode()); + Assertions.assertEquals(403, response.getStatusCode()); } } @@ -323,8 +323,8 @@ public void testExchangeToSAML2EncryptedAssertion() throws Exception { String accessToken = response.getAccessToken(); TokenVerifier accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); - Assert.assertEquals(token.getPreferredUsername(), "user"); - Assert.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); + Assertions.assertEquals(token.getPreferredUsername(), "user"); + Assertions.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); { response = oauth.tokenExchangeRequest(accessToken).audience(SAML_ENCRYPTED_TARGET).requestedTokenType(OAuth2Constants.SAML2_TOKEN_TYPE).send(); @@ -333,27 +333,27 @@ public void testExchangeToSAML2EncryptedAssertion() throws Exception { String assertionXML = new String(Base64Url.decode(exchangedTokenString), StandardCharsets.UTF_8); // Verify issued_token_type - Assert.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType()); + Assertions.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType()); // Decrypt assertion Document assertionDoc = DocumentUtil.getDocument(assertionXML); Element assertionElement = XMLEncryptionUtil.decryptElementInDocument(assertionDoc, data -> Collections.singletonList(privateKeyFromString(ENCRYPTION_PRIVATE_KEY))); - Assert.assertFalse(AssertionUtil.isSignedElement(assertionElement)); + Assertions.assertFalse(AssertionUtil.isSignedElement(assertionElement)); AssertionType assertion = (AssertionType) SAMLParser.getInstance().parse(assertionElement); // Expires - Assert.assertEquals(30, response.getExpiresIn()); + Assertions.assertEquals(30, response.getExpiresIn()); // Audience AudienceRestrictionType aud = (AudienceRestrictionType) assertion.getConditions().getConditions().get(0); - Assert.assertEquals(SAML_ENCRYPTED_TARGET, aud.getAudience().get(0).toString()); + Assertions.assertEquals(SAML_ENCRYPTED_TARGET, aud.getAudience().get(0).toString()); // NameID - Assert.assertEquals("user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue()); + Assertions.assertEquals("user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue()); // Role mapping List roles = AssertionUtil.getRoles(assertion, null); - Assert.assertTrue(roles.contains("example")); + Assertions.assertTrue(roles.contains("example")); } } @@ -368,8 +368,8 @@ public void testExchangeToSAML2SignedAndEncryptedAssertion() throws Exception { String accessToken = response.getAccessToken(); TokenVerifier accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); - Assert.assertEquals(token.getPreferredUsername(), "user"); - Assert.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); + Assertions.assertEquals(token.getPreferredUsername(), "user"); + Assertions.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); { response = oauth.tokenExchangeRequest(accessToken).audience(SAML_SIGNED_AND_ENCRYPTED_TARGET).requestedTokenType(OAuth2Constants.SAML2_TOKEN_TYPE).send(); @@ -378,25 +378,25 @@ public void testExchangeToSAML2SignedAndEncryptedAssertion() throws Exception { String assertionXML = new String(Base64Url.decode(exchangedTokenString), StandardCharsets.UTF_8); // Verify issued_token_type - Assert.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType()); + Assertions.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType()); // Verify assertion Document assertionDoc = DocumentUtil.getDocument(assertionXML); Element assertionElement = XMLEncryptionUtil.decryptElementInDocument(assertionDoc, data -> Collections.singletonList(privateKeyFromString(ENCRYPTION_PRIVATE_KEY))); - Assert.assertTrue(AssertionUtil.isSignedElement(assertionElement)); + Assertions.assertTrue(AssertionUtil.isSignedElement(assertionElement)); AssertionType assertion = (AssertionType) SAMLParser.getInstance().parse(assertionElement); - Assert.assertTrue(AssertionUtil.isSignatureValid(assertionElement, publicKeyFromString())); + Assertions.assertTrue(AssertionUtil.isSignatureValid(assertionElement, publicKeyFromString())); // Audience AudienceRestrictionType aud = (AudienceRestrictionType) assertion.getConditions().getConditions().get(0); - Assert.assertEquals(SAML_SIGNED_AND_ENCRYPTED_TARGET, aud.getAudience().get(0).toString()); + Assertions.assertEquals(SAML_SIGNED_AND_ENCRYPTED_TARGET, aud.getAudience().get(0).toString()); // NameID - Assert.assertEquals("user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue()); + Assertions.assertEquals("user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue()); // Role mapping List roles = AssertionUtil.getRoles(assertion, null); - Assert.assertTrue(roles.contains("example")); + Assertions.assertTrue(roles.contains("example")); } } @@ -411,8 +411,8 @@ public void testExchangeToSAML2UnsignedAndUnencryptedAssertion() throws Exceptio String accessToken = response.getAccessToken(); TokenVerifier accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); - Assert.assertEquals(token.getPreferredUsername(), "user"); - Assert.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); + Assertions.assertEquals(token.getPreferredUsername(), "user"); + Assertions.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); { response = oauth.tokenExchangeRequest(accessToken).audience(SAML_UNSIGNED_AND_UNENCRYPTED_TARGET).requestedTokenType(OAuth2Constants.SAML2_TOKEN_TYPE).send(); @@ -421,23 +421,23 @@ public void testExchangeToSAML2UnsignedAndUnencryptedAssertion() throws Exceptio String assertionXML = new String(Base64Url.decode(exchangedTokenString), StandardCharsets.UTF_8); // Verify issued_token_type - Assert.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType()); + Assertions.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType()); // Verify assertion Document assertionDoc = DocumentUtil.getDocument(assertionXML); - Assert.assertFalse(AssertionUtil.isSignedElement(assertionDoc.getDocumentElement())); + Assertions.assertFalse(AssertionUtil.isSignedElement(assertionDoc.getDocumentElement())); AssertionType assertion = (AssertionType) SAMLParser.getInstance().parse(assertionDoc); // Audience AudienceRestrictionType aud = (AudienceRestrictionType) assertion.getConditions().getConditions().get(0); - Assert.assertEquals(SAML_UNSIGNED_AND_UNENCRYPTED_TARGET, aud.getAudience().get(0).toString()); + Assertions.assertEquals(SAML_UNSIGNED_AND_UNENCRYPTED_TARGET, aud.getAudience().get(0).toString()); // NameID - Assert.assertEquals("user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue()); + Assertions.assertEquals("user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue()); // Role mapping List roles = AssertionUtil.getRoles(assertion, null); - Assert.assertTrue(roles.contains("example")); + Assertions.assertTrue(roles.contains("example")); } } @@ -453,8 +453,8 @@ public void testImpersonation() throws Exception { String accessToken = response.getAccessToken(); TokenVerifier accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); - Assert.assertEquals(token.getPreferredUsername(), "user"); - Assert.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); + Assertions.assertEquals(token.getPreferredUsername(), "user"); + Assertions.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); // client-exchanger can impersonate from token "user" to user "impersonated-user" and to "target" client @@ -465,24 +465,24 @@ public void testImpersonation() throws Exception { String assertionXML = new String(Base64Url.decode(exchangedTokenString), StandardCharsets.UTF_8); // Verify issued_token_type - Assert.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType()); + Assertions.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType()); // Verify assertion Element assertionElement = DocumentUtil.getDocument(assertionXML).getDocumentElement(); - Assert.assertTrue(AssertionUtil.isSignedElement(assertionElement)); + Assertions.assertTrue(AssertionUtil.isSignedElement(assertionElement)); AssertionType assertion = (AssertionType) SAMLParser.getInstance().parse(assertionElement); - Assert.assertTrue(AssertionUtil.isSignatureValid(assertionElement, publicKeyFromString())); + Assertions.assertTrue(AssertionUtil.isSignatureValid(assertionElement, publicKeyFromString())); // Audience AudienceRestrictionType aud = (AudienceRestrictionType) assertion.getConditions().getConditions().get(0); - Assert.assertEquals(SAML_SIGNED_TARGET, aud.getAudience().get(0).toString()); + Assertions.assertEquals(SAML_SIGNED_TARGET, aud.getAudience().get(0).toString()); // NameID - Assert.assertEquals("impersonated-user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue()); + Assertions.assertEquals("impersonated-user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue()); // Role mapping List roles = AssertionUtil.getRoles(assertion, null); - Assert.assertTrue(roles.contains("example")); + Assertions.assertTrue(roles.contains("example")); } } @@ -498,13 +498,13 @@ public void testBadImpersonator() throws Exception { String accessToken = response.getAccessToken(); TokenVerifier accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); - Assert.assertEquals(token.getPreferredUsername(), "bad-impersonator"); - Assert.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); + Assertions.assertEquals(token.getPreferredUsername(), "bad-impersonator"); + Assertions.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); // test that user does not have impersonator permission { response = oauth.tokenExchangeRequest(accessToken).audience(SAML_SIGNED_TARGET).requestedTokenType(OAuth2Constants.SAML2_TOKEN_TYPE).requestedSubject("impersonated-user").send(); - Assert.assertEquals(403, response.getStatusCode()); + Assertions.assertEquals(403, response.getStatusCode()); } } @@ -531,7 +531,7 @@ public void testDirectImpersonation() throws Exception { .param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user") .param(OAuth2Constants.AUDIENCE, SAML_SIGNED_TARGET) )); - Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); AccessTokenResponse accessTokenResponse = response.readEntity(AccessTokenResponse.class); response.close(); @@ -539,24 +539,24 @@ public void testDirectImpersonation() throws Exception { String assertionXML = new String(Base64Url.decode(exchangedTokenString), StandardCharsets.UTF_8); // Verify issued_token_type - Assert.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, accessTokenResponse.getOtherClaims().get(OAuth2Constants.ISSUED_TOKEN_TYPE)); + Assertions.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, accessTokenResponse.getOtherClaims().get(OAuth2Constants.ISSUED_TOKEN_TYPE)); // Verify assertion Element assertionElement = DocumentUtil.getDocument(assertionXML).getDocumentElement(); - Assert.assertTrue(AssertionUtil.isSignedElement(assertionElement)); + Assertions.assertTrue(AssertionUtil.isSignedElement(assertionElement)); AssertionType assertion = (AssertionType) SAMLParser.getInstance().parse(assertionElement); - Assert.assertTrue(AssertionUtil.isSignatureValid(assertionElement, publicKeyFromString())); + Assertions.assertTrue(AssertionUtil.isSignatureValid(assertionElement, publicKeyFromString())); // Audience AudienceRestrictionType aud = (AudienceRestrictionType) assertion.getConditions().getConditions().get(0); - Assert.assertEquals(SAML_SIGNED_TARGET, aud.getAudience().get(0).toString()); + Assertions.assertEquals(SAML_SIGNED_TARGET, aud.getAudience().get(0).toString()); // NameID - Assert.assertEquals("impersonated-user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue()); + Assertions.assertEquals("impersonated-user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue()); // Role mapping List roles = AssertionUtil.getRoles(assertion, null); - Assert.assertTrue(roles.contains("example")); + Assertions.assertTrue(roles.contains("example")); } // direct-public fails impersonation @@ -570,7 +570,7 @@ public void testDirectImpersonation() throws Exception { .param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user") .param(OAuth2Constants.AUDIENCE, SAML_SIGNED_TARGET) )); - Assert.assertEquals(403, response.getStatus()); + Assertions.assertEquals(403, response.getStatus()); response.close(); } @@ -585,7 +585,7 @@ public void testDirectImpersonation() throws Exception { .param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user") .param(OAuth2Constants.AUDIENCE, SAML_SIGNED_TARGET) )); - Assert.assertTrue(response.getStatus() >= 400); + Assertions.assertTrue(response.getStatus() >= 400); response.close(); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/ExternalInternalTokenExchangeV2Test.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/ExternalInternalTokenExchangeV2Test.java index dcac1f4fe444..eb8d7950d5d2 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/ExternalInternalTokenExchangeV2Test.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/ExternalInternalTokenExchangeV2Test.java @@ -62,6 +62,7 @@ import org.keycloak.util.BasicAuthHelper; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.broker.oidc.OAuth2IdentityProviderConfig.TOKEN_ENDPOINT_URL; import static org.keycloak.broker.oidc.OAuth2IdentityProviderConfig.TOKEN_INTROSPECTION_URL; @@ -74,7 +75,7 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for external-internal token exchange using token_exchange_external_internal:v2 @@ -136,7 +137,7 @@ private ClientRepresentation createProviderClientWithAudienceMapper(String clien private static void setupRealm(KeycloakSession session) { RealmModel realm = session.getContext().getRealm(); IdentityProviderModel idp = session.identityProviders().getByAlias(IDP_OIDC_ALIAS); - org.junit.Assert.assertNotNull(idp); + Assertions.assertNotNull(idp); ClientModel client = realm.addClient("test-app"); client.setClientId("test-app"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/StandardTokenExchangeV1Test.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/StandardTokenExchangeV1Test.java index ecc5db2dc276..88c232c1eb47 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/StandardTokenExchangeV1Test.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/StandardTokenExchangeV1Test.java @@ -46,13 +46,14 @@ import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.auth.page.AuthRealm.TEST; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for standard token exchange (internal-internal) and token-exchange-v1 @@ -91,8 +92,8 @@ protected String getInitialAccessTokenForClientExchanger() throws Exception { String accessToken = response.getAccessToken(); TokenVerifier accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); - Assert.assertNotNull(token.getSessionId()); - Assert.assertEquals(token.getPreferredUsername(), "user"); + Assertions.assertNotNull(token.getSessionId()); + Assertions.assertEquals(token.getPreferredUsername(), "user"); assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); return accessToken; } @@ -115,34 +116,34 @@ public void testExchange() throws Exception { { oauth.client("client-exchanger", "secret"); AccessTokenResponse response = oauth.tokenExchangeRequest(accessToken).audience("target").send(); - Assert.assertEquals(OAuth2Constants.REFRESH_TOKEN_TYPE, response.getIssuedTokenType()); + Assertions.assertEquals(OAuth2Constants.REFRESH_TOKEN_TYPE, response.getIssuedTokenType()); String exchangedTokenString = response.getAccessToken(); TokenVerifier verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class); AccessToken exchangedToken = verifier.parse().getToken(); - Assert.assertEquals(getSessionIdFromToken(accessToken), exchangedToken.getSessionId()); - Assert.assertEquals("client-exchanger", exchangedToken.getIssuedFor()); - Assert.assertEquals("target", exchangedToken.getAudience()[0]); - Assert.assertEquals(exchangedToken.getPreferredUsername(), "user"); + Assertions.assertEquals(getSessionIdFromToken(accessToken), exchangedToken.getSessionId()); + Assertions.assertEquals("client-exchanger", exchangedToken.getIssuedFor()); + Assertions.assertEquals("target", exchangedToken.getAudience()[0]); + Assertions.assertEquals(exchangedToken.getPreferredUsername(), "user"); assertTrue(exchangedToken.getRealmAccess().isUserInRole("example")); } { oauth.client("legal", "secret"); AccessTokenResponse response = oauth.tokenExchangeRequest(accessToken).audience("target").send(); - Assert.assertEquals(OAuth2Constants.REFRESH_TOKEN_TYPE, response.getIssuedTokenType()); + Assertions.assertEquals(OAuth2Constants.REFRESH_TOKEN_TYPE, response.getIssuedTokenType()); String exchangedTokenString = response.getAccessToken(); TokenVerifier verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class); AccessToken exchangedToken = verifier.parse().getToken(); - Assert.assertEquals(getSessionIdFromToken(accessToken), exchangedToken.getSessionId()); - Assert.assertEquals("legal", exchangedToken.getIssuedFor()); - Assert.assertEquals("target", exchangedToken.getAudience()[0]); - Assert.assertEquals(exchangedToken.getPreferredUsername(), "user"); + Assertions.assertEquals(getSessionIdFromToken(accessToken), exchangedToken.getSessionId()); + Assertions.assertEquals("legal", exchangedToken.getIssuedFor()); + Assertions.assertEquals("target", exchangedToken.getAudience()[0]); + Assertions.assertEquals(exchangedToken.getPreferredUsername(), "user"); assertTrue(exchangedToken.getRealmAccess().isUserInRole("example")); } { oauth.client("illegal", "secret"); AccessTokenResponse response = oauth.tokenExchangeRequest(accessToken).audience("target").send(); - Assert.assertEquals(403, response.getStatusCode()); + Assertions.assertEquals(403, response.getStatusCode()); } } @@ -156,14 +157,14 @@ public void testExchangeRequestAccessTokenType() throws Exception { { oauth.client("client-exchanger", "secret"); AccessTokenResponse response = oauth.tokenExchangeRequest(accessToken).audience("target").requestedTokenType(OAuth2Constants.ACCESS_TOKEN_TYPE).send(); - Assert.assertEquals(OAuth2Constants.ACCESS_TOKEN_TYPE, response.getIssuedTokenType()); + Assertions.assertEquals(OAuth2Constants.ACCESS_TOKEN_TYPE, response.getIssuedTokenType()); String exchangedTokenString = response.getAccessToken(); TokenVerifier verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class); AccessToken exchangedToken = verifier.parse().getToken(); - Assert.assertEquals(getSessionIdFromToken(accessToken), exchangedToken.getSessionId()); - Assert.assertEquals("client-exchanger", exchangedToken.getIssuedFor()); - Assert.assertEquals("target", exchangedToken.getAudience()[0]); - Assert.assertEquals(exchangedToken.getPreferredUsername(), "user"); + Assertions.assertEquals(getSessionIdFromToken(accessToken), exchangedToken.getSessionId()); + Assertions.assertEquals("client-exchanger", exchangedToken.getIssuedFor()); + Assertions.assertEquals("target", exchangedToken.getAudience()[0]); + Assertions.assertEquals(exchangedToken.getPreferredUsername(), "user"); assertTrue(exchangedToken.getRealmAccess().isUserInRole("example")); } } @@ -179,18 +180,18 @@ public void testExchangeUsingServiceAccount() throws Exception { String accessToken = response.getAccessToken(); TokenVerifier accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); - Assert.assertNull(token.getSessionId()); + Assertions.assertNull(token.getSessionId()); { response = oauth.tokenExchangeRequest(accessToken).audience("target").send(); - Assert.assertEquals(OAuth2Constants.ACCESS_TOKEN_TYPE, response.getIssuedTokenType()); + Assertions.assertEquals(OAuth2Constants.ACCESS_TOKEN_TYPE, response.getIssuedTokenType()); String exchangedTokenString = response.getAccessToken(); TokenVerifier verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class); AccessToken exchangedToken = verifier.parse().getToken(); - Assert.assertNull(exchangedToken.getSessionId()); - Assert.assertEquals("my-service-account", exchangedToken.getIssuedFor()); - Assert.assertEquals("target", exchangedToken.getAudience()[0]); - Assert.assertEquals(exchangedToken.getPreferredUsername(), "service-account-my-service-account"); + Assertions.assertNull(exchangedToken.getSessionId()); + Assertions.assertEquals("my-service-account", exchangedToken.getIssuedFor()); + Assertions.assertEquals("target", exchangedToken.getAudience()[0]); + Assertions.assertEquals(exchangedToken.getPreferredUsername(), "service-account-my-service-account"); } } @@ -208,12 +209,12 @@ public void testExchangeDifferentScopes() throws Exception { String exchangedTokenString = response.getAccessToken(); TokenVerifier verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class); AccessToken exchangedToken = verifier.parse().getToken(); - Assert.assertEquals("different-scope-client", exchangedToken.getIssuedFor()); - Assert.assertNull(exchangedToken.getAudience()); - Assert.assertEquals(exchangedToken.getPreferredUsername(), "user"); + Assertions.assertEquals("different-scope-client", exchangedToken.getIssuedFor()); + Assertions.assertNull(exchangedToken.getAudience()); + Assertions.assertEquals(exchangedToken.getPreferredUsername(), "user"); String[] expectedScopes = new String[] { "profile", "openid" }; Assert.assertNames(Arrays.asList(exchangedToken.getScope().split(" ")), expectedScopes); - Assert.assertNull(exchangedToken.getEmailVerified()); + Assertions.assertNull(exchangedToken.getEmailVerified()); } { @@ -221,13 +222,13 @@ public void testExchangeDifferentScopes() throws Exception { String exchangedTokenString = response.getAccessToken(); TokenVerifier verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class); AccessToken exchangedToken = verifier.parse().getToken(); - Assert.assertEquals("different-scope-client", exchangedToken.getIssuedFor()); - Assert.assertEquals("target", exchangedToken.getAudience()[0]); - Assert.assertEquals(exchangedToken.getPreferredUsername(), "user"); - Assert.assertTrue(exchangedToken.getRealmAccess().isUserInRole("example")); + Assertions.assertEquals("different-scope-client", exchangedToken.getIssuedFor()); + Assertions.assertEquals("target", exchangedToken.getAudience()[0]); + Assertions.assertEquals(exchangedToken.getPreferredUsername(), "user"); + Assertions.assertTrue(exchangedToken.getRealmAccess().isUserInRole("example")); String[] expectedScopes = new String[] { "profile", "email", "openid" }; Assert.assertNames(Arrays.asList(exchangedToken.getScope().split(" ")),expectedScopes); - Assert.assertFalse(exchangedToken.getEmailVerified()); + Assertions.assertFalse(exchangedToken.getEmailVerified()); } } @@ -244,8 +245,8 @@ public void testExchangeDifferentScopesWithScopeParameter() throws Exception { String accessToken = response.getAccessToken(); TokenVerifier accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); - Assert.assertEquals(token.getPreferredUsername(), "user"); - Assert.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); + Assertions.assertEquals(token.getPreferredUsername(), "user"); + Assertions.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); Assert.assertNames(Arrays.asList(token.getScope().split(" ")),"profile", "email", "openid", "phone"); //change scopes for token exchange - profile,phone must be removed oauth.scope("openid profile email"); @@ -255,11 +256,11 @@ public void testExchangeDifferentScopesWithScopeParameter() throws Exception { String exchangedTokenString = response.getAccessToken(); TokenVerifier verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class); AccessToken exchangedToken = verifier.parse().getToken(); - Assert.assertEquals("different-scope-client", exchangedToken.getIssuedFor()); - Assert.assertNull(exchangedToken.getAudience()); - Assert.assertEquals(exchangedToken.getPreferredUsername(), "user"); + Assertions.assertEquals("different-scope-client", exchangedToken.getIssuedFor()); + Assertions.assertNull(exchangedToken.getAudience()); + Assertions.assertEquals(exchangedToken.getPreferredUsername(), "user"); Assert.assertNames(Arrays.asList(exchangedToken.getScope().split(" ")),"profile", "openid"); - Assert.assertNull(exchangedToken.getEmailVerified()); + Assertions.assertNull(exchangedToken.getEmailVerified()); } { @@ -267,12 +268,12 @@ public void testExchangeDifferentScopesWithScopeParameter() throws Exception { String exchangedTokenString = response.getAccessToken(); TokenVerifier verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class); AccessToken exchangedToken = verifier.parse().getToken(); - Assert.assertEquals("different-scope-client", exchangedToken.getIssuedFor()); - Assert.assertEquals("target", exchangedToken.getAudience()[0]); - Assert.assertEquals(exchangedToken.getPreferredUsername(), "user"); - Assert.assertTrue(exchangedToken.getRealmAccess().isUserInRole("example")); + Assertions.assertEquals("different-scope-client", exchangedToken.getIssuedFor()); + Assertions.assertEquals("target", exchangedToken.getAudience()[0]); + Assertions.assertEquals(exchangedToken.getPreferredUsername(), "user"); + Assertions.assertTrue(exchangedToken.getRealmAccess().isUserInRole("example")); Assert.assertNames(Arrays.asList(exchangedToken.getScope().split(" ")),"profile", "email","openid"); - Assert.assertFalse(exchangedToken.getEmailVerified()); + Assertions.assertFalse(exchangedToken.getEmailVerified()); } oauth.scope(null); } @@ -290,7 +291,7 @@ public void testExchangeFromPublicClient() throws Exception { String accessToken = response.getAccessToken(); TokenVerifier accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); - Assert.assertEquals(token.getPreferredUsername(), "user"); + Assertions.assertEquals(token.getPreferredUsername(), "user"); assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); oauth.client("client-exchanger", "secret"); @@ -299,9 +300,9 @@ public void testExchangeFromPublicClient() throws Exception { String exchangedTokenString = response.getAccessToken(); TokenVerifier verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class); AccessToken exchangedToken = verifier.parse().getToken(); - Assert.assertEquals("client-exchanger", exchangedToken.getIssuedFor()); - Assert.assertEquals("target", exchangedToken.getAudience()[0]); - Assert.assertEquals(exchangedToken.getPreferredUsername(), "user"); + Assertions.assertEquals("client-exchanger", exchangedToken.getIssuedFor()); + Assertions.assertEquals("target", exchangedToken.getAudience()[0]); + Assertions.assertEquals(exchangedToken.getPreferredUsername(), "user"); assertTrue(exchangedToken.getRealmAccess().isUserInRole("example")); // can exchange to itself because the client is within the audience of the token issued to the public client @@ -405,7 +406,7 @@ public void testClientExchange() throws Exception { String accessToken = response.getAccessToken(); TokenVerifier accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); - Assert.assertEquals(token.getPreferredUsername(), "user"); + Assertions.assertEquals(token.getPreferredUsername(), "user"); assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); response = oauth.tokenExchangeRequest(accessToken).audience("target").send(); @@ -435,7 +436,7 @@ public void testPublicClientNotAllowed() throws Exception { String accessToken = response.getAccessToken(); TokenVerifier accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); - Assert.assertEquals(token.getPreferredUsername(), "user"); + Assertions.assertEquals(token.getPreferredUsername(), "user"); assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); // public client has no permission to exchange with the client direct-legal to which the token was issued for @@ -501,7 +502,7 @@ public void testSupportedTokenTypesWhenValidatingSubjectToken() throws Exception oauth.logoutForm().idTokenHint(idTokenString) .postLogoutRedirectUri(oauth.APP_AUTH_ROOT).open(); logoutToken = testingClient.testApp().getBackChannelRawLogoutToken(); - Assert.assertNotNull(logoutToken); + Assertions.assertNotNull(logoutToken); AccessTokenResponse response = oauth.tokenExchangeRequest(logoutToken).audience("target").send(); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode()); @@ -518,9 +519,9 @@ public void testExchangeForDifferentClient() throws Exception { String accessToken = response.getAccessToken(); TokenVerifier accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); - Assert.assertEquals(token.getPreferredUsername(), "user"); + Assertions.assertEquals(token.getPreferredUsername(), "user"); assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); - Assert.assertNotNull(token.getSessionId()); + Assertions.assertNotNull(token.getSessionId()); String sid = token.getSessionId(); oauth.client("client-exchanger", "secret"); @@ -531,10 +532,10 @@ public void testExchangeForDifferentClient() throws Exception { accessToken = response.getAccessToken(); accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); token = accessTokenVerifier.parse().getToken(); - Assert.assertEquals("client-exchanger", token.getIssuedFor()); - Assert.assertEquals("target", token.getAudience()[0]); - Assert.assertEquals(token.getPreferredUsername(), "user"); - Assert.assertEquals(sid, token.getSessionId()); + Assertions.assertEquals("client-exchanger", token.getIssuedFor()); + Assertions.assertEquals("target", token.getAudience()[0]); + Assertions.assertEquals(token.getPreferredUsername(), "user"); + Assertions.assertEquals(sid, token.getSessionId()); // perform a second token exchange just to check everything is OK response = oauth.tokenExchangeRequest(accessToken).audience("target").send(); @@ -542,9 +543,9 @@ public void testExchangeForDifferentClient() throws Exception { accessToken = response.getAccessToken(); accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); token = accessTokenVerifier.parse().getToken(); - Assert.assertEquals("client-exchanger", token.getIssuedFor()); - Assert.assertEquals("target", token.getAudience()[0]); - Assert.assertEquals(token.getPreferredUsername(), "user"); - Assert.assertEquals(sid, token.getSessionId()); + Assertions.assertEquals("client-exchanger", token.getIssuedFor()); + Assertions.assertEquals("target", token.getAudience()[0]); + Assertions.assertEquals(token.getPreferredUsername(), "user"); + Assertions.assertEquals(sid, token.getSessionId()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/StandardTokenExchangeV2Test.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/StandardTokenExchangeV2Test.java index 74c9c17b5b93..c885cbb773e4 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/StandardTokenExchangeV2Test.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/StandardTokenExchangeV2Test.java @@ -87,8 +87,8 @@ import org.hamcrest.MatcherAssert; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.auth.page.AuthRealm.TEST; @@ -97,12 +97,12 @@ import static org.keycloak.testsuite.util.ClientPoliciesUtil.createTestRaiseExeptionExecutorConfig; import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Marek Posolda @@ -399,7 +399,7 @@ public void testTransientOfflineSessionForRequester() throws Exception { assertEquals(OAuth2Constants.ACCESS_TOKEN_TYPE, response.getIssuedTokenType()); String exchangedTokenString = response.getAccessToken(); AccessToken exchangedToken = TokenVerifier.create(exchangedTokenString, AccessToken.class).parse().getToken(); - assertTrue("Exchanged token is not active", exchangedToken.isActive()); + assertTrue(exchangedToken.isActive(), "Exchanged token is not active"); assertEquals(getSessionIdFromToken(accessToken), exchangedToken.getSessionId()); assertEquals("requester-client", exchangedToken.getIssuedFor()); assertAccessTokenContext(exchangedToken.getId(), AccessTokenContext.SessionType.OFFLINE_TRANSIENT_CLIENT, @@ -418,14 +418,14 @@ public void testTransientOfflineSessionForRequester() throws Exception { setTimeOffset(610); final AccessTokenResponse refreshResponse = oauth.client("subject-client", "secret").scope(null) .refreshRequest(initialResponse.getRefreshToken()).send(); - assertNull("Error refreshing the initial token: " + refreshResponse.getErrorDescription(), refreshResponse.getError()); + assertNull(refreshResponse.getError(), "Error refreshing the initial token: " + refreshResponse.getErrorDescription()); accessToken = refreshResponse.getAccessToken(); oauth.scope(OAuth2Constants.SCOPE_OPENID); response = tokenExchange(accessToken, "requester-client", "secret", null, null); - assertNull("Error exchanging the token: " + response.getErrorDescription(), response.getError()); + assertNull(response.getError(), "Error exchanging the token: " + response.getErrorDescription()); exchangedTokenString = response.getAccessToken(); exchangedToken = TokenVerifier.create(exchangedTokenString, AccessToken.class).parse().getToken(); - assertTrue("Exchanged token is not active", exchangedToken.isActive()); + assertTrue(exchangedToken.isActive(), "Exchanged token is not active"); assertEquals(getSessionIdFromToken(accessToken), exchangedToken.getSessionId()); assertEquals("requester-client", exchangedToken.getIssuedFor()); assertAccessTokenContext(exchangedToken.getId(), AccessTokenContext.SessionType.OFFLINE_TRANSIENT_CLIENT, @@ -545,7 +545,7 @@ public void testExchangeForIdToken() throws Exception { .parse().getToken(); assertEquals(TokenUtil.TOKEN_TYPE_BEARER, exchangedToken.getType()); - assertNotNull("ID Token is null, but was expected to be present", response.getIdToken()); + assertNotNull(response.getIdToken(), "ID Token is null, but was expected to be present"); IDToken exchangedIdToken = TokenVerifier.create(response.getIdToken(), IDToken.class) .parse().getToken(); assertEquals(TokenUtil.TOKEN_TYPE_ID, exchangedIdToken.getType()); @@ -558,14 +558,14 @@ public void testExchangeForIdToken() throws Exception { response = tokenExchange(accessToken, "requester-client", "secret", null, OAuth2Constants.ACCESS_TOKEN_TYPE); assertEquals(OAuth2Constants.ACCESS_TOKEN_TYPE, response.getIssuedTokenType()); assertNotNull(response.getAccessToken()); - assertNull("ID Token was present, but should not be present", response.getIdToken()); + assertNull(response.getIdToken(), "ID Token was present, but should not be present"); // Exchange request requesting id-token. ID Token should be issued inside "access_token" parameter (as per token-exchange specification https://datatracker.ietf.org/doc/html/rfc8693#name-successful-response - parameter "access_token") response = tokenExchange(accessToken, "requester-client", "secret", null, OAuth2Constants.ID_TOKEN_TYPE); assertEquals(OAuth2Constants.ID_TOKEN_TYPE, response.getIssuedTokenType()); assertEquals(TokenUtil.TOKEN_TYPE_NA, response.getTokenType()); assertNotNull(response.getAccessToken()); - assertNull("ID Token was present, but should not be present", response.getIdToken()); + assertNull(response.getIdToken(), "ID Token was present, but should not be present"); exchangedIdToken = TokenVerifier.create(response.getAccessToken(), IDToken.class) .parse().getToken(); @@ -829,9 +829,9 @@ public void testExchangeDisabledOnClient() throws Exception { String accessToken = resourceOwnerLogin("john", "password", "subject-client", "secret").getAccessToken(); { AccessTokenResponse response = tokenExchange(accessToken, "disabled-requester-client", "secret", null, null); - org.junit.Assert.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode()); - org.junit.Assert.assertEquals(OAuthErrorException.INVALID_REQUEST, response.getError()); - org.junit.Assert.assertEquals("Standard token exchange is not enabled for the requested client", response.getErrorDescription()); + Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode()); + Assertions.assertEquals(OAuthErrorException.INVALID_REQUEST, response.getError()); + Assertions.assertEquals("Standard token exchange is not enabled for the requested client", response.getErrorDescription()); } } @@ -897,7 +897,7 @@ public void testOfflineAccessNotAllowed() throws Exception { .update()) { String accessToken = resourceOwnerLogin("mike", "password", "subject-client", "secret").getAccessToken(); String sessionId = TokenVerifier.create(accessToken, AccessToken.class).parse().getToken().getSessionId(); - Assert.assertEquals(testingClient.testing(TEST).getClientSessionsCountInUserSession(TEST, sessionId), Integer.valueOf(1)); + Assertions.assertEquals(testingClient.testing(TEST).getClientSessionsCountInUserSession(TEST, sessionId), Integer.valueOf(1)); oauth.scope("offline_access"); AccessTokenResponse response = tokenExchange(accessToken, "requester-client", "secret", List.of("target-client1"), OAuth2Constants.REFRESH_TOKEN_TYPE); @@ -906,7 +906,7 @@ public void testOfflineAccessNotAllowed() throws Exception { assertEquals("Scope offline_access not allowed for token exchange", response.getErrorDescription()); // Check that client session was not created - Assert.assertEquals(testingClient.testing(TEST).getClientSessionsCountInUserSession(TEST, sessionId), Integer.valueOf(1)); + Assertions.assertEquals(testingClient.testing(TEST).getClientSessionsCountInUserSession(TEST, sessionId), Integer.valueOf(1)); } } @@ -969,9 +969,9 @@ public void testOfflineAccessNotAllowedAfterOfflineAccessLogin() throws Exceptio String subjectClientUuid = AdminApiUtil.findClientByClientId(adminClient.realm(TEST), "subject-client").toRepresentation().getId(); String requesterClientUuid = AdminApiUtil.findClientByClientId(adminClient.realm(TEST), "requester-client").toRepresentation().getId(); UserResource user = AdminApiUtil.findUserByUsernameId(adminClient.realm(TEST), "mike"); - Assert.assertEquals(0, user.getUserSessions().size()); - Assert.assertEquals(1, user.getOfflineSessions(subjectClientUuid).size()); - Assert.assertEquals(0, user.getOfflineSessions(requesterClientUuid).size()); + Assertions.assertEquals(0, user.getUserSessions().size()); + Assertions.assertEquals(1, user.getOfflineSessions(subjectClientUuid).size()); + Assertions.assertEquals(0, user.getOfflineSessions(requesterClientUuid).size()); // Token exchange with scope=offline-access should not be allowed oauth.scope("offline_access"); @@ -979,9 +979,9 @@ public void testOfflineAccessNotAllowedAfterOfflineAccessLogin() throws Exceptio assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode()); // Make sure not new user sessions persisted - Assert.assertEquals(0, user.getUserSessions().size()); - Assert.assertEquals(1, user.getOfflineSessions(subjectClientUuid).size()); - Assert.assertEquals(0, user.getOfflineSessions(requesterClientUuid).size()); + Assertions.assertEquals(0, user.getUserSessions().size()); + Assertions.assertEquals(1, user.getOfflineSessions(subjectClientUuid).size()); + Assertions.assertEquals(0, user.getOfflineSessions(requesterClientUuid).size()); } } @@ -1000,7 +1000,7 @@ public void testIntrospectionWithExchangedTokenAfterSSOLoginOfRequesterClient() // Token exchange access-token for "Requester-client" . No client session yet for "requester-client" at this stage AccessTokenResponse response = tokenExchange(accessToken, "requester-client", "secret", null, null); String exchangedToken = response.getAccessToken(); - Assert.assertNotNull(exchangedToken); + Assertions.assertNotNull(exchangedToken); // Set time offset setTimeOffset(10); @@ -1381,7 +1381,7 @@ private AccessToken assertAudiencesAndScopes(AccessTokenResponse tokenExchangeRe TokenVerifier accessTokenVerifier = TokenVerifier.create(tokenExchangeResponse.getAccessToken(), AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); if (expectedAudiences == null) { - assertNull("Expected token to not contain audience", token.getAudience()); + assertNull(token.getAudience(), "Expected token to not contain audience"); } else { assertAudiences(token, expectedAudiences); } @@ -1476,7 +1476,7 @@ public void testSenderConstrainedTokenRejection() throws Exception { assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode()); assertEquals(OAuthErrorException.INVALID_REQUEST, response.getError()); - assertTrue("Error should mention sender-constrained tokens", response.getErrorDescription().contains("Sender-constrained")); + assertTrue(response.getErrorDescription().contains("Sender-constrained"), "Error should mention sender-constrained tokens"); client.getProtocolMappers().delete(mapperId); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/StandardTokenExchangeV2WithLegacyTokenExchangeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/StandardTokenExchangeV2WithLegacyTokenExchangeTest.java index 24f1987972f4..b98a396e3fed 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/StandardTokenExchangeV2WithLegacyTokenExchangeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/StandardTokenExchangeV2WithLegacyTokenExchangeTest.java @@ -29,6 +29,7 @@ import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.auth.page.AuthRealm.TEST; @@ -51,9 +52,9 @@ public void testExchangeDisabledOnClient() throws Exception { String accessToken = resourceOwnerLogin("john", "password", "subject-client", "secret").getAccessToken(); { AccessTokenResponse response = tokenExchange(accessToken, "disabled-requester-client", "secret", null, null); - org.junit.Assert.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatusCode()); - org.junit.Assert.assertEquals(OAuthErrorException.ACCESS_DENIED, response.getError()); - org.junit.Assert.assertEquals("Client is not within the token audience", response.getErrorDescription()); + Assertions.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatusCode()); + Assertions.assertEquals(OAuthErrorException.ACCESS_DENIED, response.getError()); + Assertions.assertEquals("Client is not within the token audience", response.getErrorDescription()); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/SubjectImpersonationTokenExchangeV1Test.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/SubjectImpersonationTokenExchangeV1Test.java index 5b91bd3ae915..d7e67ae01ef1 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/SubjectImpersonationTokenExchangeV1Test.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/SubjectImpersonationTokenExchangeV1Test.java @@ -37,7 +37,6 @@ import org.keycloak.representations.idm.OAuth2ErrorRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.AbstractKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.arquillian.annotation.DisableFeature; import org.keycloak.testsuite.arquillian.annotation.EnableFeature; @@ -51,14 +50,15 @@ import com.fasterxml.jackson.databind.JsonNode; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.auth.page.AuthRealm.TEST; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for subject impersonation token exchange (including "direct naked impersonation") @@ -93,7 +93,7 @@ protected boolean isImportAfterEachMethod() { public void checkFeatureDisabled() { // Required feature should return Status code 400 - Feature doesn't work testingClient.server().run(TokenExchangeTestUtils::addDirectExchanger); - Assert.assertEquals(400, checkTokenExchange().getStatus()); + Assertions.assertEquals(400, checkTokenExchange().getStatus()); testingClient.server().run(TokenExchangeTestUtils::removeDirectExchanger); } @@ -101,7 +101,7 @@ public void checkFeatureDisabled() { public void checkFeatureEnabled() { // Test if the required feature really works. testingClient.server().run(TokenExchangeTestUtils::addDirectExchanger); - Assert.assertEquals(200, checkTokenExchange().getStatus()); + Assertions.assertEquals(200, checkTokenExchange().getStatus()); testingClient.server().run(TokenExchangeTestUtils::removeDirectExchanger); } @@ -125,7 +125,7 @@ public void testImpersonation() throws Exception { String accessToken = tokenResponse.getAccessToken(); TokenVerifier accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); - Assert.assertEquals(token.getPreferredUsername(), "user"); + Assertions.assertEquals(token.getPreferredUsername(), "user"); assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); // client-exchanger can impersonate from token "user" to user "impersonated-user" @@ -140,24 +140,24 @@ public void testImpersonation() throws Exception { .param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user") )); - org.junit.Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); AccessTokenResponse accessTokenResponse = response.readEntity(AccessTokenResponse.class); response.close(); String exchangedTokenString = accessTokenResponse.getToken(); TokenVerifier verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class); AccessToken exchangedToken = verifier.parse().getToken(); - Assert.assertEquals("client-exchanger", exchangedToken.getIssuedFor()); + Assertions.assertEquals("client-exchanger", exchangedToken.getIssuedFor()); assertNotNull(exchangedToken.getAudience()); - Assert.assertEquals("impersonated-user", exchangedToken.getPreferredUsername()); - Assert.assertNull(exchangedToken.getRealmAccess()); + Assertions.assertEquals("impersonated-user", exchangedToken.getPreferredUsername()); + Assertions.assertNull(exchangedToken.getRealmAccess()); Object impersonatorRaw = exchangedToken.getOtherClaims().get("impersonator"); assertThat(impersonatorRaw, instanceOf(Map.class)); Map impersonatorClaim = (Map) impersonatorRaw; - Assert.assertEquals(token.getSubject(), impersonatorClaim.get("id")); - Assert.assertEquals("user", impersonatorClaim.get("username")); + Assertions.assertEquals(token.getSubject(), impersonatorClaim.get("id")); + Assertions.assertEquals("user", impersonatorClaim.get("username")); } // client-exchanger can impersonate from token "user" to user "impersonated-user" and to "target" client @@ -173,16 +173,16 @@ public void testImpersonation() throws Exception { .param(OAuth2Constants.AUDIENCE, "target") )); - org.junit.Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); AccessTokenResponse accessTokenResponse = response.readEntity(AccessTokenResponse.class); response.close(); String exchangedTokenString = accessTokenResponse.getToken(); TokenVerifier verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class); AccessToken exchangedToken = verifier.parse().getToken(); - Assert.assertEquals("client-exchanger", exchangedToken.getIssuedFor()); - Assert.assertEquals("target", exchangedToken.getAudience()[0]); - Assert.assertEquals(exchangedToken.getPreferredUsername(), "impersonated-user"); + Assertions.assertEquals("client-exchanger", exchangedToken.getIssuedFor()); + Assertions.assertEquals("target", exchangedToken.getAudience()[0]); + Assertions.assertEquals(exchangedToken.getPreferredUsername(), "impersonated-user"); assertTrue(exchangedToken.getRealmAccess().isUserInRole("example")); } @@ -201,7 +201,7 @@ public void testImpersonation() throws Exception { .param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user") .param(OAuth2Constants.AUDIENCE, "target") ))) { - Assert.assertEquals(403, response.getStatus()); + Assertions.assertEquals(403, response.getStatus()); } try (Response response = exchangeUrl.request() @@ -214,7 +214,7 @@ public void testImpersonation() throws Exception { .param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user") ))) { - org.junit.Assert.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus()); + Assertions.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus()); assertEquals("Client is not the holder of the token", response.readEntity(OAuth2ErrorRepresentation.class).getErrorDescription()); } @@ -230,7 +230,7 @@ public void testImpersonation() throws Exception { .param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user") ))) { - org.junit.Assert.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus()); + Assertions.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus()); assertEquals("Client is not the holder of the token", response.readEntity(OAuth2ErrorRepresentation.class).getErrorDescription()); } @@ -246,7 +246,7 @@ public void testImpersonation() throws Exception { .param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user") ))) { - org.junit.Assert.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus()); + Assertions.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus()); assertEquals("Client is not the holder of the token", response.readEntity(OAuth2ErrorRepresentation.class).getErrorDescription()); } @@ -281,7 +281,7 @@ public void testIntrospectTokenAfterImpersonation() throws Exception { .param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user") ))) { - org.junit.Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); AccessTokenResponse accessTokenResponse = response.readEntity(AccessTokenResponse.class); String exchangedTokenString = accessTokenResponse.getToken(); JsonNode json = oauth.doIntrospectionAccessTokenRequest(exchangedTokenString).asJsonNode(); @@ -301,7 +301,7 @@ public void testIntrospectTokenAfterImpersonation() throws Exception { .param(OAuth2Constants.AUDIENCE, "target") ))) { - org.junit.Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); AccessTokenResponse accessTokenResponse = response.readEntity(AccessTokenResponse.class); String exchangedTokenString = accessTokenResponse.getToken(); JsonNode json = oauth.doIntrospectionAccessTokenRequest(exchangedTokenString).asJsonNode(); @@ -326,7 +326,7 @@ public void testImpersonationUsingPublicClient() throws Exception { String accessToken = tokenResponse.getAccessToken(); TokenVerifier accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); - Assert.assertEquals(token.getPreferredUsername(), "user"); + Assertions.assertEquals(token.getPreferredUsername(), "user"); assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); WebTarget exchangeUrl = httpClient.target(OAuthClient.AUTH_SERVER_ROOT) @@ -345,16 +345,16 @@ public void testImpersonationUsingPublicClient() throws Exception { .param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user") )); - org.junit.Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); AccessTokenResponse accessTokenResponse = response.readEntity(AccessTokenResponse.class); response.close(); String exchangedTokenString = accessTokenResponse.getToken(); TokenVerifier verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class); AccessToken exchangedToken = verifier.parse().getToken(); - Assert.assertEquals("direct-public", exchangedToken.getIssuedFor()); - Assert.assertEquals("impersonated-user", exchangedToken.getPreferredUsername()); - Assert.assertNull(exchangedToken.getRealmAccess()); + Assertions.assertEquals("direct-public", exchangedToken.getIssuedFor()); + Assertions.assertEquals("impersonated-user", exchangedToken.getPreferredUsername()); + Assertions.assertNull(exchangedToken.getRealmAccess()); testingClient.server().run(TokenExchangeTestUtils::setUpUserImpersonatePermissions); } @@ -375,7 +375,7 @@ public void testImpersonationUsingTokenIssuedToUntrustedPublicClient() throws Ex String accessToken = tokenResponse.getAccessToken(); TokenVerifier accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); - Assert.assertEquals(token.getPreferredUsername(), "user"); + Assertions.assertEquals(token.getPreferredUsername(), "user"); assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); WebTarget exchangeUrl = httpClient.target(OAuthClient.AUTH_SERVER_ROOT) @@ -394,7 +394,7 @@ public void testImpersonationUsingTokenIssuedToUntrustedPublicClient() throws Ex .param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user") )); - org.junit.Assert.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus()); + Assertions.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus()); oauth.logoutForm().idTokenHint(tokenResponse.getIdToken()).open(); oauth.client("direct-public", "secret"); @@ -412,7 +412,7 @@ public void testImpersonationUsingTokenIssuedToUntrustedPublicClient() throws Ex .param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user") )); - org.junit.Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); } @Test @@ -435,7 +435,7 @@ public void testBadImpersonator() throws Exception { String accessToken = tokenResponse.getAccessToken(); TokenVerifier accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class); AccessToken token = accessTokenVerifier.parse().getToken(); - Assert.assertEquals(token.getPreferredUsername(), "bad-impersonator"); + Assertions.assertEquals(token.getPreferredUsername(), "bad-impersonator"); assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example")); // test that user does not have impersonator permission @@ -450,7 +450,7 @@ public void testBadImpersonator() throws Exception { .param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user") )); - org.junit.Assert.assertEquals(403, response.getStatus()); + Assertions.assertEquals(403, response.getStatus()); response.close(); } @@ -480,17 +480,17 @@ public void testDirectImpersonation() throws Exception { .param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user") )); - Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); AccessTokenResponse accessTokenResponse = response.readEntity(AccessTokenResponse.class); response.close(); String exchangedTokenString = accessTokenResponse.getToken(); TokenVerifier verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class); AccessToken exchangedToken = verifier.parse().getToken(); - Assert.assertEquals("direct-exchanger", exchangedToken.getIssuedFor()); - Assert.assertNull(exchangedToken.getAudience()); - Assert.assertEquals(exchangedToken.getPreferredUsername(), "impersonated-user"); - Assert.assertNull(exchangedToken.getRealmAccess()); + Assertions.assertEquals("direct-exchanger", exchangedToken.getIssuedFor()); + Assertions.assertNull(exchangedToken.getAudience()); + Assertions.assertEquals(exchangedToken.getPreferredUsername(), "impersonated-user"); + Assertions.assertNull(exchangedToken.getRealmAccess()); } // direct-legal can impersonate from token "user" to user "impersonated-user" and to "target" client @@ -504,16 +504,16 @@ public void testDirectImpersonation() throws Exception { .param(OAuth2Constants.AUDIENCE, "target") )); - Assert.assertEquals(200, response.getStatus()); + Assertions.assertEquals(200, response.getStatus()); AccessTokenResponse accessTokenResponse = response.readEntity(AccessTokenResponse.class); response.close(); String exchangedTokenString = accessTokenResponse.getToken(); TokenVerifier verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class); AccessToken exchangedToken = verifier.parse().getToken(); - Assert.assertEquals("direct-legal", exchangedToken.getIssuedFor()); - Assert.assertEquals("target", exchangedToken.getAudience()[0]); - Assert.assertEquals(exchangedToken.getPreferredUsername(), "impersonated-user"); + Assertions.assertEquals("direct-legal", exchangedToken.getIssuedFor()); + Assertions.assertEquals("target", exchangedToken.getAudience()[0]); + Assertions.assertEquals(exchangedToken.getPreferredUsername(), "impersonated-user"); assertTrue(exchangedToken.getRealmAccess().isUserInRole("example")); } @@ -528,7 +528,7 @@ public void testDirectImpersonation() throws Exception { .param(OAuth2Constants.AUDIENCE, "target") )); - Assert.assertEquals(403, response.getStatus()); + Assertions.assertEquals(403, response.getStatus()); response.close(); } @@ -560,7 +560,7 @@ public void testDirectImpersonation() throws Exception { .param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user") .param(OAuth2Constants.AUDIENCE, "target") ))) { - Assert.assertEquals(403, response.getStatus()); + Assertions.assertEquals(403, response.getStatus()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/TokenExchangeTestUtils.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/TokenExchangeTestUtils.java index 4121bf2b414d..9d4df485db9b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/TokenExchangeTestUtils.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/tokenexchange/TokenExchangeTestUtils.java @@ -45,7 +45,7 @@ import static org.keycloak.models.ImpersonationSessionNote.IMPERSONATOR_USERNAME; import static org.keycloak.testsuite.auth.page.AuthRealm.TEST; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Marek Posolda diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/credentialbuilder/JwtCredentialBuilderTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/credentialbuilder/JwtCredentialBuilderTest.java index cd9dba74fc74..eef378ae5342 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/credentialbuilder/JwtCredentialBuilderTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/credentialbuilder/JwtCredentialBuilderTest.java @@ -37,7 +37,7 @@ import static org.keycloak.OID4VCConstants.CREDENTIAL_SUBJECT; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Ingrid Kamga diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/credentialbuilder/SdJwtCredentialBuilderTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/credentialbuilder/SdJwtCredentialBuilderTest.java index 04bd84c7dddc..1de0a39149f7 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/credentialbuilder/SdJwtCredentialBuilderTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/credentialbuilder/SdJwtCredentialBuilderTest.java @@ -40,8 +40,8 @@ import static org.keycloak.OID4VCConstants.CLAIM_NAME_SD_HASH_ALGORITHM; import static org.keycloak.OID4VCConstants.CLAIM_NAME_VCT; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Ingrid Kamga @@ -110,33 +110,33 @@ public static void testSignSDJwtCredential(Map claims, int decoy IssuerSignedJWT jwt = sdJwt.getIssuerSignedJWT(); - assertEquals("The issuer should be set in the token.", - issuerDid, - jwt.getPayload().get(CLAIM_NAME_ISSUER).asText()); + assertEquals(issuerDid, + jwt.getPayload().get(CLAIM_NAME_ISSUER).asText(), + "The issuer should be set in the token."); - assertEquals("The type should be included", - credentialBuildConfig.getCredentialType(), - jwt.getPayload().get(CLAIM_NAME_VCT).asText()); + assertEquals(credentialBuildConfig.getCredentialType(), + jwt.getPayload().get(CLAIM_NAME_VCT).asText(), + "The type should be included"); - assertEquals("The JWS token type should be included", - credentialBuildConfig.getTokenJwsType(), - jwt.getJwsHeader().getType()); + assertEquals(credentialBuildConfig.getTokenJwsType(), + jwt.getJwsHeader().getType(), + "The JWS token type should be included"); ArrayNode sdArrayNode = (ArrayNode) jwt.getPayload().get(CLAIM_NAME_SD); if (sdArrayNode != null) { - assertEquals("The algorithm should be included and lowercase", - credentialBuildConfig.getHashAlgorithm().toLowerCase(), - jwt.getPayload().get(CLAIM_NAME_SD_HASH_ALGORITHM).asText()); + assertEquals(credentialBuildConfig.getHashAlgorithm().toLowerCase(), + jwt.getPayload().get(CLAIM_NAME_SD_HASH_ALGORITHM).asText(), + "The algorithm should be included and lowercase"); } List disclosed = sdJwt.getDisclosures().values().stream().toList(); - assertEquals("All undisclosed claims and decoys should be provided.", - disclosed.size() + (decoys == 0 ? SdJwt.DEFAULT_NUMBER_OF_DECOYS : decoys), - sdArrayNode == null ? 0 : sdArrayNode.size()); + assertEquals(disclosed.size() + (decoys == 0 ? SdJwt.DEFAULT_NUMBER_OF_DECOYS : decoys), + sdArrayNode == null ? 0 : sdArrayNode.size(), + "All undisclosed claims and decoys should be provided."); visibleClaims.forEach(vc -> - assertTrue("The visible claims should be present within the token.", - jwt.getPayload().has(vc)) + assertTrue(jwt.getPayload().has(vc), + "The visible claims should be present within the token.") ); // Will check disclosure conformity diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/JWTVCIssuerWellKnownProviderTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/JWTVCIssuerWellKnownProviderTest.java index dd8385d155b3..ccdc517aa12b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/JWTVCIssuerWellKnownProviderTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/JWTVCIssuerWellKnownProviderTest.java @@ -38,9 +38,9 @@ import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -59,10 +59,10 @@ public void getConfig() throws IOException { try (Response jwtIssuerResponse = jwtIssuerTarget.request().get()) { JWTVCIssuerMetadata jwtvcIssuerMetadata = JsonSerialization.readValue(jwtIssuerResponse.readEntity(String.class), JWTVCIssuerMetadata.class); - assertEquals("The correct issuer should be included.", expectedIssuer, jwtvcIssuerMetadata.getIssuer()); + assertEquals(expectedIssuer, jwtvcIssuerMetadata.getIssuer(), "The correct issuer should be included."); JSONWebKeySet jwks = jwtvcIssuerMetadata.getJwks(); - assertNotNull("The key set shall not be null", jwks.getKeys()); - assertTrue("The key set shall not be empty", jwks.getKeys().length > 0); + assertNotNull(jwks.getKeys(), "The key set shall not be null"); + assertTrue(jwks.getKeys().length > 0, "The key set shall not be empty"); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/JwtCredentialSignerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/JwtCredentialSignerTest.java index 59ad4d23bc81..5fa6a30a6166 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/JwtCredentialSignerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/JwtCredentialSignerTest.java @@ -51,9 +51,9 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; public class JwtCredentialSignerTest extends OID4VCTest { @@ -211,30 +211,30 @@ public static void testSignJwtCredential( try { JsonWebToken theToken = verifier.getToken(); - assertEquals("JWT claim in JWT encoded VC or VP MUST be used to set the value of the “expirationDate” of the VC", TEST_EXPIRATION_DATE.getEpochSecond(), theToken.getExp().longValue()); + assertEquals(TEST_EXPIRATION_DATE.getEpochSecond(), theToken.getExp().longValue(), "JWT claim in JWT encoded VC or VP MUST be used to set the value of the “expirationDate” of the VC"); if (claims.containsKey("issuanceDate")) { - assertEquals("VC Data Model v1.1 specifies that “issuanceDate” property MUST be represented as an nbf JWT claim, and not iat JWT claim.", ((Instant) claims.get("issuanceDate")).getEpochSecond(), theToken.getNbf().longValue()); + assertEquals(((Instant) claims.get("issuanceDate")).getEpochSecond(), theToken.getNbf().longValue(), "VC Data Model v1.1 specifies that “issuanceDate” property MUST be represented as an nbf JWT claim, and not iat JWT claim."); } else { // if not specific date is set, check against "currentTime" - assertEquals("VC Data Model v1.1 specifies that “issuanceDate” property MUST be represented as an nbf JWT claim, and not iat JWT claim.", TEST_ISSUANCE_DATE.getEpochSecond(), theToken.getNbf().longValue()); + assertEquals(TEST_ISSUANCE_DATE.getEpochSecond(), theToken.getNbf().longValue(), "VC Data Model v1.1 specifies that “issuanceDate” property MUST be represented as an nbf JWT claim, and not iat JWT claim."); } - assertEquals("The issuer should be set in the token.", TEST_DID.toString(), theToken.getIssuer()); - assertEquals("The credential ID should be set as the token ID.", testCredential.getId().toString(), theToken.getId()); - Optional.ofNullable(testCredential.getCredentialSubject().getClaims().get("id")).ifPresent(id -> assertEquals("If the credentials subject id is set, it should be set as the token subject.", id.toString(), theToken.getSubject())); + assertEquals(TEST_DID.toString(), theToken.getIssuer(), "The issuer should be set in the token."); + assertEquals(testCredential.getId().toString(), theToken.getId(), "The credential ID should be set as the token ID."); + Optional.ofNullable(testCredential.getCredentialSubject().getClaims().get("id")).ifPresent(id -> assertEquals(id.toString(), theToken.getSubject(), "If the credentials subject id is set, it should be set as the token subject.")); - assertNotNull("The credentials should be included at the vc-claim.", theToken.getOtherClaims().get("vc")); + assertNotNull(theToken.getOtherClaims().get("vc"), "The credentials should be included at the vc-claim."); VerifiableCredential credential = JsonSerialization.mapper.convertValue(theToken.getOtherClaims().get("vc"), VerifiableCredential.class); - assertEquals("The types should be included", TEST_TYPES, credential.getType()); - assertEquals("The issuer should be included", TEST_DID, credential.getIssuer()); - assertEquals("The expiration date should be included", TEST_EXPIRATION_DATE, credential.getExpirationDate()); + assertEquals(TEST_TYPES, credential.getType(), "The types should be included"); + assertEquals(TEST_DID, credential.getIssuer(), "The issuer should be included"); + assertEquals(TEST_EXPIRATION_DATE, credential.getExpirationDate(), "The expiration date should be included"); if (claims.containsKey("issuanceDate")) { - assertEquals("The issuance date should be included", claims.get("issuanceDate"), credential.getIssuanceDate()); + assertEquals(claims.get("issuanceDate"), credential.getIssuanceDate(), "The issuance date should be included"); } CredentialSubject subject = credential.getCredentialSubject(); claims.entrySet().stream() .filter(e -> !e.getKey().equals("issuanceDate")) - .forEach(e -> assertEquals(String.format("All additional claims should be set - %s is incorrect", e.getKey()), e.getValue(), subject.getClaims().get(e.getKey()))); + .forEach(e -> assertEquals(e.getValue(), subject.getClaims().get(e.getKey()), String.format("All additional claims should be set - %s is incorrect", e.getKey()))); } catch (VerificationException e) { fail("Was not able to get the token from the verifier."); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/LDCredentialSignerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/LDCredentialSignerTest.java index baa9159895b8..c708fd174147 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/LDCredentialSignerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/LDCredentialSignerTest.java @@ -45,8 +45,8 @@ import org.junit.Ignore; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; // LDP_VC format is intentionally disabled to keep scope limited to supported formats. @Ignore("LDP_VC format is currently not supported and providers are disabled.") @@ -190,25 +190,25 @@ public static void testSignLdCredential( VerifiableCredential verifiableCredential = ldCredentialSigner .signCredential(ldCredentialBody, credentialBuildConfig); - assertEquals("The types should be included", TEST_TYPES, verifiableCredential.getType()); - assertEquals("The issuer should be included", TEST_DID, verifiableCredential.getIssuer()); - assertNotNull("The context needs to be set.", verifiableCredential.getContext()); - assertEquals("The expiration date should be included", TEST_EXPIRATION_DATE, verifiableCredential.getExpirationDate()); + assertEquals(TEST_TYPES, verifiableCredential.getType(), "The types should be included"); + assertEquals(TEST_DID, verifiableCredential.getIssuer(), "The issuer should be included"); + assertNotNull(verifiableCredential.getContext(), "The context needs to be set."); + assertEquals(TEST_EXPIRATION_DATE, verifiableCredential.getExpirationDate(), "The expiration date should be included"); if (claims.containsKey("issuanceDate")) { - assertEquals("The issuance date should be included", claims.get("issuanceDate"), verifiableCredential.getIssuanceDate()); + assertEquals(claims.get("issuanceDate"), verifiableCredential.getIssuanceDate(), "The issuance date should be included"); } CredentialSubject subject = verifiableCredential.getCredentialSubject(); claims.entrySet().stream() .filter(e -> !e.getKey().equals("issuanceDate")) - .forEach(e -> assertEquals(String.format("All additional claims should be set - %s is incorrect", e.getKey()), e.getValue(), subject.getClaims().get(e.getKey()))); + .forEach(e -> assertEquals(e.getValue(), subject.getClaims().get(e.getKey()), String.format("All additional claims should be set - %s is incorrect", e.getKey()))); - assertNotNull("The credential should contain a signed proof.", verifiableCredential.getAdditionalProperties().get("proof")); + assertNotNull(verifiableCredential.getAdditionalProperties().get("proof"), "The credential should contain a signed proof."); LdProof ldProof = (LdProof) verifiableCredential.getAdditionalProperties().get("proof"); KeyWrapper keyWrapper = getKeyFromSession(session); String expectedKid = Optional.ofNullable(overrideKeyId).orElse(keyWrapper.getKid()); - assertEquals("The verification method should be set to the key id.", expectedKid, ldProof.getVerificationMethod()); + assertEquals(expectedKid, ldProof.getVerificationMethod(), "The verification method should be set to the key id."); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCAttestationProofTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCAttestationProofTest.java index af060fb93e8d..1471bc4e118e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCAttestationProofTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCAttestationProofTest.java @@ -41,11 +41,11 @@ import static org.keycloak.OID4VCConstants.OPENID_CREDENTIAL; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Test class for verifying Attestation Proof functionality with trusted keys configuration. @@ -110,8 +110,8 @@ public void testAttestationProofWithInvalidTrustedKey() { runAttestationProofWithInvalidTrustedKey(session, cNonce); fail("Expected VCIssuerException to be thrown"); } catch (VCIssuerException e) { - assertTrue("Expected error about key not found in trusted key registry but got: " + e.getMessage(), - e.getMessage().contains("not found in trusted key registry")); + assertTrue(e.getMessage().contains("not found in trusted key registry"), + "Expected error about key not found in trusted key registry but got: " + e.getMessage()); } }); } @@ -121,13 +121,11 @@ public void testAttestationProofValidatorFactoryConfiguration() { testingClient.server(TEST_REALM_NAME).run(session -> { AttestationProofValidatorFactory factory = new AttestationProofValidatorFactory(); - assertEquals("Factory ID should be 'attestation'", - "attestation", factory.getId()); + assertEquals("attestation", factory.getId(), "Factory ID should be 'attestation'"); ProofValidator validator = factory.create(session); - assertNotNull("Factory should create validator", validator); - assertEquals("Validator proof type should be 'attestation'", - "attestation", validator.getProofType()); + assertNotNull(validator, "Factory should create validator"); + assertEquals("attestation", validator.getProofType(), "Validator proof type should be 'attestation'"); }); } @@ -154,10 +152,10 @@ public void testCredentialIssuanceWithAttestationProof() { AccessTokenResponse tokenResponse = getBearerToken(oauth, authCode, authDetail); String token = tokenResponse.getAccessToken(); List authDetailsResponse = tokenResponse.getOID4VCAuthorizationDetails(); - assertNotNull("authorization_details should be present in the response", authDetailsResponse); - assertFalse("authorization_details should not be empty", authDetailsResponse.isEmpty()); + assertNotNull(authDetailsResponse, "authorization_details should be present in the response"); + assertFalse(authDetailsResponse.isEmpty(), "authorization_details should not be empty"); String credentialIdentifier = authDetailsResponse.get(0).getCredentialIdentifiers().get(0); - assertNotNull("credential_identifier should be present", credentialIdentifier); + assertNotNull(credentialIdentifier, "credential_identifier should be present"); String cNonce = getCNonce(); testingClient.server(TEST_REALM_NAME).run(session -> { @@ -187,18 +185,18 @@ public void testCredentialIssuanceWithAttestationProof() { String requestPayload = JsonSerialization.writeValueAsString(request); Response response = endpoint.requestCredential(requestPayload); - assertEquals("Response status should be OK", Response.Status.OK.getStatusCode(), response.getStatus()); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus(), "Response status should be OK"); CredentialResponse credentialResponse = JsonSerialization.mapper .convertValue(response.getEntity(), CredentialResponse.class); - assertNotNull("Credential response should not be null", credentialResponse); - assertNotNull("Credentials array should not be null", credentialResponse.getCredentials()); - assertEquals("Should return 1 credential", 1, credentialResponse.getCredentials().size()); + assertNotNull(credentialResponse, "Credential response should not be null"); + assertNotNull(credentialResponse.getCredentials(), "Credentials array should not be null"); + assertEquals(1, credentialResponse.getCredentials().size(), "Should return 1 credential"); // Validate the credential Object credentialObj = credentialResponse.getCredentials().get(0).getCredential(); - assertNotNull("Credential should not be null", credentialObj); - assertTrue("Credential should be a string", credentialObj instanceof String); + assertNotNull(credentialObj, "Credential should not be null"); + assertTrue(credentialObj instanceof String, "Credential should be a string"); String credentialString = (String) credentialObj; JsonWebToken jsonWebToken; @@ -209,13 +207,13 @@ public void testCredentialIssuanceWithAttestationProof() { return; } - assertNotNull("A valid credential JWT should be returned", jsonWebToken); - assertNotNull("The credentials should include the vc claim", jsonWebToken.getOtherClaims().get("vc")); + assertNotNull(jsonWebToken, "A valid credential JWT should be returned"); + assertNotNull(jsonWebToken.getOtherClaims().get("vc"), "The credentials should include the vc claim"); VerifiableCredential vc = JsonSerialization.mapper.convertValue( jsonWebToken.getOtherClaims().get("vc"), VerifiableCredential.class); - assertNotNull("VerifiableCredential should not be null", vc); - assertNotNull("Credential subject should not be null", vc.getCredentialSubject()); + assertNotNull(vc, "VerifiableCredential should not be null"); + assertNotNull(vc.getCredentialSubject(), "Credential subject should not be null"); } catch (Exception e) { LOGGER.error("Test failed with exception", e); fail("Test should not throw exception: " + e.getMessage()); @@ -268,10 +266,9 @@ private static List validateProofAndAssert(AttestationProofValidator valida VCIssuanceContext vcIssuanceContext, KeyWrapper expectedProofKey) { List attestedKeys = validator.validateProof(vcIssuanceContext); - assertNotNull("Attested keys should not be null", attestedKeys); - assertEquals("Should contain exactly one attested key", 1, attestedKeys.size()); - assertEquals("Attested key ID should match proof key ID", - expectedProofKey.getKid(), attestedKeys.get(0).getKeyId()); + assertNotNull(attestedKeys, "Attested keys should not be null"); + assertEquals(1, attestedKeys.size(), "Should contain exactly one attested key"); + assertEquals(expectedProofKey.getKid(), attestedKeys.get(0).getKeyId(), "Attested key ID should match proof key ID"); return attestedKeys; } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCAuthorizationCodeFlowWithPARTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCAuthorizationCodeFlowWithPARTest.java index 847847afbaa8..84e190c8211a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCAuthorizationCodeFlowWithPARTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCAuthorizationCodeFlowWithPARTest.java @@ -41,11 +41,11 @@ import static org.keycloak.OID4VCConstants.OPENID_CREDENTIAL; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test class for Authorization Code Flow with PAR (Pushed Authorization Request) containing authorization_details. @@ -134,7 +134,7 @@ public void testAuthorizationCodeFlowWithPARAndAuthorizationDetails() throws Exc .send(); assertEquals(HttpStatus.SC_CREATED, parResponse.getStatusCode()); String requestUri = parResponse.getRequestUri(); - assertNotNull("Request URI should not be null", requestUri); + assertNotNull(requestUri, "Request URI should not be null"); // Step 2: Perform authorization with PAR oauth.client(clientId); @@ -142,7 +142,7 @@ public void testAuthorizationCodeFlowWithPARAndAuthorizationDetails() throws Exc oauth.loginForm().requestUri(requestUri).doLogin("john", "password"); String code = oauth.parseLoginResponse().getCode(); - assertNotNull("Authorization code should not be null", code); + assertNotNull(code, "Authorization code should not be null"); // Step 3: Exchange authorization code for tokens (WITHOUT authorization_details in token request) // This tests that authorization_details from PAR request is processed and returned @@ -154,27 +154,27 @@ public void testAuthorizationCodeFlowWithPARAndAuthorizationDetails() throws Exc // Step 4: Verify authorization_details is present in token response List authDetailsResponse = tokenResponse.getOID4VCAuthorizationDetails(); - assertNotNull("authorization_details should be present in the response", authDetailsResponse); - assertEquals("Should have exactly one authorization detail", 1, authDetailsResponse.size()); + assertNotNull(authDetailsResponse, "authorization_details should be present in the response"); + assertEquals(1, authDetailsResponse.size(), "Should have exactly one authorization detail"); OID4VCAuthorizationDetail authDetailResponse = authDetailsResponse.get(0); - assertEquals("Type should be openid_credential", OPENID_CREDENTIAL, authDetailResponse.getType()); - assertEquals("Credential configuration ID should match", credentialConfigurationId, authDetailResponse.getCredentialConfigurationId()); + assertEquals(OPENID_CREDENTIAL, authDetailResponse.getType(), "Type should be openid_credential"); + assertEquals(credentialConfigurationId, authDetailResponse.getCredentialConfigurationId(), "Credential configuration ID should match"); // Verify claims are preserved - assertNotNull("Claims should be present", authDetailResponse.getClaims()); - assertEquals("Should have exactly one claim", 1, authDetailResponse.getClaims().size()); + assertNotNull(authDetailResponse.getClaims(), "Claims should be present"); + assertEquals(1, authDetailResponse.getClaims().size(), "Should have exactly one claim"); ClaimsDescription responseClaim = authDetailResponse.getClaims().get(0); - assertEquals("Claim path should match", claimPath, responseClaim.getPath()); - assertTrue("Claim should be mandatory", responseClaim.isMandatory()); + assertEquals(claimPath, responseClaim.getPath(), "Claim path should match"); + assertTrue(responseClaim.isMandatory(), "Claim should be mandatory"); // Verify credential identifiers are present - assertNotNull("Credential identifiers should be present", authDetailResponse.getCredentialIdentifiers()); - assertEquals("Should have exactly one credential identifier", 1, authDetailResponse.getCredentialIdentifiers().size()); + assertNotNull(authDetailResponse.getCredentialIdentifiers(), "Credential identifiers should be present"); + assertEquals(1, authDetailResponse.getCredentialIdentifiers().size(), "Should have exactly one credential identifier"); String credentialIdentifier = authDetailResponse.getCredentialIdentifiers().get(0); - assertNotNull("Credential identifier should not be null", credentialIdentifier); - assertFalse("Credential identifier should not be empty", credentialIdentifier.isEmpty()); + assertNotNull(credentialIdentifier, "Credential identifier should not be null"); + assertFalse(credentialIdentifier.isEmpty(), "Credential identifier should not be empty"); // Step 5: Request the actual credential using the identifier // When authorization_details are present in the token, credential_identifier must be used @@ -189,16 +189,16 @@ public void testAuthorizationCodeFlowWithPARAndAuthorizationDetails() throws Exc // Parse the credential response CredentialResponse parsedResponse = credentialResponse.getCredentialResponse(); - assertNotNull("Credential response should not be null", parsedResponse); - assertNotNull("Credentials should be present", parsedResponse.getCredentials()); - assertEquals("Should have exactly one credential", 1, parsedResponse.getCredentials().size()); + assertNotNull(parsedResponse, "Credential response should not be null"); + assertNotNull(parsedResponse.getCredentials(), "Credentials should be present"); + assertEquals(1, parsedResponse.getCredentials().size(), "Should have exactly one credential"); // Verify that the issued credential contains the requested claims CredentialResponse.Credential credentialWrapper = parsedResponse.getCredentials().get(0); - assertNotNull("Credential wrapper should not be null", credentialWrapper); + assertNotNull(credentialWrapper, "Credential wrapper should not be null"); Object credentialObj = credentialWrapper.getCredential(); - assertNotNull("Credential object should not be null", credentialObj); + assertNotNull(credentialObj, "Credential object should not be null"); // Verify the credential structure verifyCredentialStructure(credentialObj); @@ -228,7 +228,7 @@ public void testAuthorizationCodeFlowWithPARAndAuthorizationDetailsFailure() thr .send(); assertEquals(HttpStatus.SC_CREATED, parResponse.getStatusCode()); String requestUri = parResponse.getRequestUri(); - assertNotNull("Request URI should not be null", requestUri); + assertNotNull(requestUri, "Request URI should not be null"); // Step 2: Perform authorization with PAR oauth.client(clientId); @@ -238,7 +238,7 @@ public void testAuthorizationCodeFlowWithPARAndAuthorizationDetailsFailure() thr // [TODO #47649] OAuthClient cannot handle invalid authorization requests assertNotNull("No error message", ex.getMessage()); - assertTrue(ex.getMessage(), ex.getMessage().contains("waiting for element Proxy element for: DefaultElementLocator 'By.id: username' to be present")); + assertTrue(ex.getMessage().contains("waiting for element Proxy element for: DefaultElementLocator 'By.id: username' to be present"), ex.getMessage()); } @Test @@ -255,14 +255,14 @@ public void testAuthorizationCodeFlowWithPARButNoAuthorizationDetailsInTokenRequ .send(); assertEquals(HttpStatus.SC_CREATED, parResponse.getStatusCode()); String requestUri = parResponse.getRequestUri(); - assertNotNull("Request URI should not be null", requestUri); + assertNotNull(requestUri, "Request URI should not be null"); // Step 2: Perform authorization with PAR oauth.scope(getCredentialClientScope().getName()); oauth.loginForm().requestUri(requestUri).doLogin("john", "password"); String code = oauth.parseLoginResponse().getCode(); - assertNotNull("Authorization code should not be null", code); + assertNotNull(code, "Authorization code should not be null"); // Step 3: Exchange authorization code for tokens AccessTokenResponse tokenResponse = oauth.accessTokenRequest(code) @@ -272,14 +272,14 @@ public void testAuthorizationCodeFlowWithPARButNoAuthorizationDetailsInTokenRequ // Step 4: Verify authorization_details are derived from requested OID4VC scope List authDetailsResponse = tokenResponse.getOID4VCAuthorizationDetails(); - assertNotNull("authorization_details should be present in the token response", authDetailsResponse); - assertFalse("authorization_details should not be empty", authDetailsResponse.isEmpty()); + assertNotNull(authDetailsResponse, "authorization_details should be present in the token response"); + assertFalse(authDetailsResponse.isEmpty(), "authorization_details should not be empty"); OID4VCAuthorizationDetail firstAuthorizationDetail = authDetailsResponse.get(0); - assertEquals("credential_configuration_id should match requested scope", - getCredentialClientScope().getAttributes().get(CredentialScopeModel.VC_CONFIGURATION_ID), - firstAuthorizationDetail.getCredentialConfigurationId()); - assertNotNull("credential_identifiers should be present", firstAuthorizationDetail.getCredentialIdentifiers()); - assertFalse("credential_identifiers should not be empty", firstAuthorizationDetail.getCredentialIdentifiers().isEmpty()); + assertEquals(getCredentialClientScope().getAttributes().get(CredentialScopeModel.VC_CONFIGURATION_ID), + firstAuthorizationDetail.getCredentialConfigurationId(), + "credential_configuration_id should match requested scope"); + assertNotNull(firstAuthorizationDetail.getCredentialIdentifiers(), "credential_identifiers should be present"); + assertFalse(firstAuthorizationDetail.getCredentialIdentifiers().isEmpty(), "credential_identifiers should not be empty"); } /** @@ -288,6 +288,6 @@ public void testAuthorizationCodeFlowWithPARButNoAuthorizationDetailsInTokenRequ */ protected void verifyCredentialStructure(Object credentialObj) { // Default implementation - subclasses should override - assertNotNull("Credential object should not be null", credentialObj); + assertNotNull(credentialObj, "Credential object should not be null"); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCAuthorizationDetailsTypesSupportedTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCAuthorizationDetailsTypesSupportedTest.java index 228f4d395987..77a1173bde0c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCAuthorizationDetailsTypesSupportedTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCAuthorizationDetailsTypesSupportedTest.java @@ -35,11 +35,11 @@ import static org.keycloak.OID4VCConstants.OPENID_CREDENTIAL; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test to verify that authorization_details_types_supported is included in the OAuth Authorization Server @@ -67,13 +67,13 @@ public void testAuthorizationDetailsTypesSupportedInOAuthAuthorizationServerMeta OIDCConfigurationRepresentation oauthConfig = getOAuth2WellKnownConfiguration(client); // Verify that authorization_details_types_supported is present - assertNotNull("authorization_details_types_supported should be present", - oauthConfig.getAuthorizationDetailsTypesSupported()); + assertNotNull(oauthConfig.getAuthorizationDetailsTypesSupported(), + "authorization_details_types_supported should be present"); // Verify that it contains openid_credential List supportedTypes = oauthConfig.getAuthorizationDetailsTypesSupported(); - assertTrue("authorization_details_types_supported should contain openid_credential", - supportedTypes.contains(OPENID_CREDENTIAL)); + assertTrue(supportedTypes.contains(OPENID_CREDENTIAL), + "authorization_details_types_supported should contain openid_credential"); } } @@ -83,17 +83,17 @@ public void testCredentialIssuerAuthorizationServerMetadata() { try (Client client = AdminClientUtil.createResteasyClient()) { // Get credential issuer metadata CredentialIssuer credentialIssuer = getCredentialIssuerMetadata(); - assertNotNull("Credential issuer should not be null", credentialIssuer); - assertNotNull("Authorization servers should be present", credentialIssuer.getAuthorizationServers()); - assertFalse("Authorization servers should not be empty", credentialIssuer.getAuthorizationServers().isEmpty()); + assertNotNull(credentialIssuer, "Credential issuer should not be null"); + assertNotNull(credentialIssuer.getAuthorizationServers(), "Authorization servers should be present"); + assertFalse(credentialIssuer.getAuthorizationServers().isEmpty(), "Authorization servers should not be empty"); // Verify the authorization server from credential issuer metadata String authServerUri = credentialIssuer.getAuthorizationServers().get(0); OIDCConfigurationRepresentation authServerConfig = getOAuth2WellKnownConfiguration(client, authServerUri + "/.well-known/oauth-authorization-server"); - assertNotNull("Authorization server should support authorization_details_types_supported", - authServerConfig.getAuthorizationDetailsTypesSupported()); - assertTrue("Authorization server should support openid_credential", - authServerConfig.getAuthorizationDetailsTypesSupported().contains(OPENID_CREDENTIAL)); + assertNotNull(authServerConfig.getAuthorizationDetailsTypesSupported(), + "Authorization server should support authorization_details_types_supported"); + assertTrue(authServerConfig.getAuthorizationDetailsTypesSupported().contains(OPENID_CREDENTIAL), + "Authorization server should support openid_credential"); } } @@ -107,8 +107,8 @@ public void testAuthorizationDetailsTypesSupportedNotInOAuth2WellKnownWhenOID4VC OIDCConfigurationRepresentation oauth2Config = getOAuth2WellKnownConfiguration(client); // Verify that authorization_details_types_supported is not present - assertNull("authorization_details_types_supported should not be present when OID4VC is disabled", - oauth2Config.getAuthorizationDetailsTypesSupported()); + assertNull(oauth2Config.getAuthorizationDetailsTypesSupported(), + "authorization_details_types_supported should not be present when OID4VC is disabled"); } } @@ -122,7 +122,7 @@ private OIDCConfigurationRepresentation getOAuth2WellKnownConfiguration(Client c .request() .get(); - assertEquals("OAuth Authorization Server metadata endpoint should return 200", 200, response.getStatus()); + assertEquals(200, response.getStatus(), "OAuth Authorization Server metadata endpoint should return 200"); return response.readEntity(OIDCConfigurationRepresentation.class); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCCredentialOfferCorsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCCredentialOfferCorsTest.java index 70911cbb5f0f..f76d0fb9ab57 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCCredentialOfferCorsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCCredentialOfferCorsTest.java @@ -55,10 +55,10 @@ import org.junit.Rule; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test class for CORS functionality on OID4VCI credential offer endpoints. @@ -114,8 +114,8 @@ public void testCredentialOfferUriCorsValidOrigin() throws Exception { // Verify response content CredentialOfferURI offerUri = response.getCredentialOfferURI(); - assertNotNull("Credential offer URI should not be null", offerUri.getIssuer()); - assertNotNull("Nonce should not be null", offerUri.getNonce()); + assertNotNull(offerUri.getIssuer(), "Credential offer URI should not be null"); + assertNotNull(offerUri.getNonce(), "Nonce should not be null"); // Verify VERIFIABLE_CREDENTIAL_CREATE_OFFER event was fired events.expect(EventType.VERIFIABLE_CREDENTIAL_CREATE_OFFER) @@ -186,8 +186,8 @@ public void testCredentialOfferSessionCorsValidOrigin() throws Exception { // Verify response content CredentialsOffer offer = response.getCredentialsOffer(); - assertNotNull("Credential offer should not be null", offer.getCredentialIssuer()); - assertNotNull("Credential configuration IDs should not be null", offer.getCredentialConfigurationIds()); + assertNotNull(offer.getCredentialIssuer(), "Credential offer should not be null"); + assertNotNull(offer.getCredentialConfigurationIds(), "Credential configuration IDs should not be null"); // The credential_type detail contains the credential configuration ID from the offer // We already assert that credentialConfigurationIds is not null and not empty above @@ -248,7 +248,7 @@ public void testCredentialOfferUriQrCodeCorsValidOrigin() throws Exception { // Verify response is PNG image String contentType = response.getFirstHeader("Content-Type").getValue(); - assertTrue("Response should be PNG image", contentType.contains("image/png")); + assertTrue(contentType.contains("image/png"), "Response should be PNG image"); } } @@ -337,7 +337,7 @@ public void testCredentialOfferWithExpiredNonce() throws Exception { session.getTransactionManager().commit(); return offerState.getNonce(); }); - assertNotNull("CredentialOffer nonce not null", nonce); + assertNotNull(nonce, "CredentialOffer nonce not null"); events.clear(); @@ -426,89 +426,81 @@ private String getResponseBody(CloseableHttpResponse response) throws IOExceptio } private void assertCorsHeaders(AbstractHttpResponse response, String expectedOrigin) { - assertNotNull("Access-Control-Allow-Origin header should be present", - response.getHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("Access-Control-Allow-Origin should match request origin", - expectedOrigin, response.getHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN)); - - assertNotNull("Access-Control-Allow-Credentials header should be present", - response.getHeader(Cors.ACCESS_CONTROL_ALLOW_CREDENTIALS)); - assertEquals("Access-Control-Allow-Credentials should be true", - "true", response.getHeader(Cors.ACCESS_CONTROL_ALLOW_CREDENTIALS)); + assertNotNull(response.getHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN), + "Access-Control-Allow-Origin header should be present"); + assertEquals(expectedOrigin, response.getHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN), "Access-Control-Allow-Origin should match request origin"); + + assertNotNull(response.getHeader(Cors.ACCESS_CONTROL_ALLOW_CREDENTIALS), + "Access-Control-Allow-Credentials header should be present"); + assertEquals("true", response.getHeader(Cors.ACCESS_CONTROL_ALLOW_CREDENTIALS), "Access-Control-Allow-Credentials should be true"); } private void assertCorsHeadersForSessionEndpoint(AbstractHttpResponse response, String expectedOrigin) { - assertNotNull("Access-Control-Allow-Origin header should be present", - response.getHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("Access-Control-Allow-Origin should match request origin", - expectedOrigin, response.getHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN)); + assertNotNull(response.getHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN), + "Access-Control-Allow-Origin header should be present"); + assertEquals(expectedOrigin, response.getHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN), "Access-Control-Allow-Origin should match request origin"); // Session-based endpoints don't require credentials since they use nonces for security // and allow all origins, so credentials header should be false for security reasons String credentialsHeader = response.getHeader(Cors.ACCESS_CONTROL_ALLOW_CREDENTIALS); - assertNotNull("Access-Control-Allow-Credentials header should be present for session endpoints", - credentialsHeader); - assertEquals("Access-Control-Allow-Credentials should be false when allowing all origins", - "false", credentialsHeader); + assertNotNull(credentialsHeader, + "Access-Control-Allow-Credentials header should be present for session endpoints"); + assertEquals("false", credentialsHeader, "Access-Control-Allow-Credentials should be false when allowing all origins"); } private void assertCorsPreflightHeaders(CloseableHttpResponse response, String expectedOrigin) { assertCorsHeadersFromCloseableResponse(response, expectedOrigin); - assertNotNull("Access-Control-Allow-Methods header should be present", - response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_METHODS)); + assertNotNull(response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_METHODS), + "Access-Control-Allow-Methods header should be present"); String allowedMethods = response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_METHODS).getValue(); Set methods = Arrays.stream(allowedMethods.split(", ")) .collect(Collectors.toSet()); - assertTrue("GET should be allowed", methods.contains("GET")); - assertTrue("OPTIONS should be allowed", methods.contains("OPTIONS")); + assertTrue(methods.contains("GET"), "GET should be allowed"); + assertTrue(methods.contains("OPTIONS"), "OPTIONS should be allowed"); } private void assertCorsPreflightHeadersForSessionEndpoint(CloseableHttpResponse response, String expectedOrigin) { assertCorsHeadersForSessionEndpointFromCloseableResponse(response, expectedOrigin); - assertNotNull("Access-Control-Allow-Methods header should be present", - response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_METHODS)); + assertNotNull(response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_METHODS), + "Access-Control-Allow-Methods header should be present"); String allowedMethods = response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_METHODS).getValue(); Set methods = Arrays.stream(allowedMethods.split(", ")) .collect(Collectors.toSet()); - assertTrue("GET should be allowed", methods.contains("GET")); - assertTrue("OPTIONS should be allowed", methods.contains("OPTIONS")); + assertTrue(methods.contains("GET"), "GET should be allowed"); + assertTrue(methods.contains("OPTIONS"), "OPTIONS should be allowed"); } private void assertCorsHeadersFromCloseableResponse(CloseableHttpResponse response, String expectedOrigin) { - assertNotNull("Access-Control-Allow-Origin header should be present", - response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("Access-Control-Allow-Origin should match request origin", - expectedOrigin, response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN).getValue()); - - assertNotNull("Access-Control-Allow-Credentials header should be present", - response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_CREDENTIALS)); - assertEquals("Access-Control-Allow-Credentials should be true", - "true", response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_CREDENTIALS).getValue()); + assertNotNull(response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN), + "Access-Control-Allow-Origin header should be present"); + assertEquals(expectedOrigin, response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN).getValue(), "Access-Control-Allow-Origin should match request origin"); + + assertNotNull(response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_CREDENTIALS), + "Access-Control-Allow-Credentials header should be present"); + assertEquals("true", response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_CREDENTIALS).getValue(), "Access-Control-Allow-Credentials should be true"); } private void assertCorsHeadersForSessionEndpointFromCloseableResponse(CloseableHttpResponse response, String expectedOrigin) { - assertNotNull("Access-Control-Allow-Origin header should be present", - response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("Access-Control-Allow-Origin should match request origin", - expectedOrigin, response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN).getValue()); + assertNotNull(response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN), + "Access-Control-Allow-Origin header should be present"); + assertEquals(expectedOrigin, response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN).getValue(), "Access-Control-Allow-Origin should match request origin"); // Session-based endpoints don't require credentials since they use nonces for security // and allow all origins, so credentials header should be false for security reasons Header credentialsHeader = response.getFirstHeader(Cors.ACCESS_CONTROL_ALLOW_CREDENTIALS); - assertNotNull("Access-Control-Allow-Credentials header should be present for session endpoints", - credentialsHeader); - assertEquals("Access-Control-Allow-Credentials should be false when allowing all origins", - "false", credentialsHeader.getValue()); + assertNotNull(credentialsHeader, + "Access-Control-Allow-Credentials header should be present for session endpoints"); + assertEquals("false", credentialsHeader.getValue(), "Access-Control-Allow-Credentials should be false when allowing all origins"); } private void assertNoCorsHeaders(AbstractHttpResponse response) { - assertNull("Access-Control-Allow-Origin header should not be present", response.getHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertNull("Access-Control-Allow-Credentials header should not be present", response.getHeader(Cors.ACCESS_CONTROL_ALLOW_CREDENTIALS)); + assertNull(response.getHeader(Cors.ACCESS_CONTROL_ALLOW_ORIGIN), "Access-Control-Allow-Origin header should not be present"); + assertNull(response.getHeader(Cors.ACCESS_CONTROL_ALLOW_CREDENTIALS), "Access-Control-Allow-Credentials header should not be present"); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCIssuerEndpointEncryptionTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCIssuerEndpointEncryptionTest.java index 4388c6d462d7..3ea00e3529e2 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCIssuerEndpointEncryptionTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCIssuerEndpointEncryptionTest.java @@ -51,7 +51,6 @@ import org.keycloak.protocol.oid4vc.model.VerifiableCredential; import org.keycloak.representations.JsonWebToken; import org.keycloak.services.managers.AppAuthManager; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.keycloak.util.JsonSerialization; import org.keycloak.utils.MediaType; @@ -59,17 +58,18 @@ import org.apache.http.HttpStatus; import org.jboss.logging.Logger; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.OID4VCConstants.OPENID_CREDENTIAL; import static org.keycloak.jose.jwe.JWEConstants.A256GCM; import static org.keycloak.testsuite.oid4vc.issuance.signing.OID4VCSdJwtIssuingEndpointTest.getCredentialIssuer; import static org.keycloak.utils.MediaType.APPLICATION_JWT; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Test class for Credential Request and Response Encryption @@ -94,10 +94,10 @@ public void testRequestCredentialWithEncryption() { AccessTokenResponse tokenResponse = getBearerToken(oauth, authCode, authDetail); String token = tokenResponse.getAccessToken(); List authDetailsResponse = tokenResponse.getOID4VCAuthorizationDetails(); - assertNotNull("authorization_details should be present in the response", authDetailsResponse); - assertFalse("authorization_details should not be empty", authDetailsResponse.isEmpty()); + assertNotNull(authDetailsResponse, "authorization_details should be present in the response"); + assertFalse(authDetailsResponse.isEmpty(), "authorization_details should not be empty"); String credentialIdentifier = authDetailsResponse.get(0).getCredentialIdentifiers().get(0); - assertNotNull("credential_identifier should be present", credentialIdentifier); + assertNotNull(credentialIdentifier, "credential_identifier should be present"); String cNonce = getCNonce(); testingClient @@ -128,10 +128,8 @@ public void testRequestCredentialWithEncryption() { Response credentialResponse = issuerEndpoint.requestCredential(credentialRequestPayload); - assertEquals("The credential request should be answered successfully.", - HttpStatus.SC_OK, credentialResponse.getStatus()); - assertEquals("Response should be JWT type for encrypted responses", - APPLICATION_JWT, credentialResponse.getMediaType().toString()); + assertEquals(HttpStatus.SC_OK, credentialResponse.getStatus(), "The credential request should be answered successfully."); + assertEquals(APPLICATION_JWT, credentialResponse.getMediaType().toString(), "Response should be JWT type for encrypted responses"); String encryptedResponse = (String) credentialResponse.getEntity(); CredentialResponse decryptedResponse; @@ -143,7 +141,7 @@ public void testRequestCredentialWithEncryption() { } // Verify the decrypted payload - assertNotNull("Decrypted response should contain a credential", decryptedResponse.getCredentials()); + assertNotNull(decryptedResponse.getCredentials(), "Decrypted response should contain a credential"); JsonWebToken jsonWebToken; try { jsonWebToken = TokenVerifier.create((String) decryptedResponse.getCredentials().get(0).getCredential(), JsonWebToken.class).getToken(); @@ -151,10 +149,10 @@ public void testRequestCredentialWithEncryption() { fail("Failed to verify JWT: " + e.getMessage()); return; } - assertNotNull("A valid credential string should have been responded", jsonWebToken); + assertNotNull(jsonWebToken, "A valid credential string should have been responded"); VerifiableCredential credential = JsonSerialization.mapper.convertValue( jsonWebToken.getOtherClaims().get("vc"), VerifiableCredential.class); - assertTrue("The static claim should be set.", credential.getCredentialSubject().getClaims().containsKey("scope-name")); + assertTrue(credential.getCredentialSubject().getClaims().containsKey("scope-name"), "The static claim should be set."); })); } @@ -205,10 +203,10 @@ public void testEncryptedCredentialRequest() { AccessTokenResponse tokenResponse = getBearerToken(oauth, authCode, authDetail); String token = tokenResponse.getAccessToken(); List authDetailsResponse = tokenResponse.getOID4VCAuthorizationDetails(); - assertNotNull("authorization_details should be present in the response", authDetailsResponse); - assertFalse("authorization_details should not be empty", authDetailsResponse.isEmpty()); + assertNotNull(authDetailsResponse, "authorization_details should be present in the response"); + assertFalse(authDetailsResponse.isEmpty(), "authorization_details should not be empty"); String credentialIdentifier = authDetailsResponse.get(0).getCredentialIdentifiers().get(0); - assertNotNull("credential_identifier should be present", credentialIdentifier); + assertNotNull(credentialIdentifier, "credential_identifier should be present"); String cNonce = getCNonce(); testingClient.server(TEST_REALM_NAME).run(session -> { @@ -247,25 +245,23 @@ public void testEncryptedCredentialRequest() { Response response = issuerEndpoint.requestCredential(encryptedRequest); - assertEquals("Encrypted request should be processed successfully", - 200, response.getStatus()); - assertEquals("Response should be JWT type for encrypted responses", - APPLICATION_JWT, response.getMediaType().toString()); + assertEquals(200, response.getStatus(), "Encrypted request should be processed successfully"); + assertEquals(APPLICATION_JWT, response.getMediaType().toString(), "Response should be JWT type for encrypted responses"); // Decrypt and verify response String encryptedResponse = (String) response.getEntity(); CredentialResponse decryptedResponse = decryptJweResponse(encryptedResponse, responsePrivateKey); - assertNotNull("Decrypted response should contain a credential", decryptedResponse.getCredentials()); + assertNotNull(decryptedResponse.getCredentials(), "Decrypted response should contain a credential"); JsonWebToken jsonWebToken = TokenVerifier.create( (String) decryptedResponse.getCredentials().get(0).getCredential(), JsonWebToken.class).getToken(); - assertNotNull("A valid credential string should have been responded", jsonWebToken); + assertNotNull(jsonWebToken, "A valid credential string should have been responded"); VerifiableCredential credential = JsonSerialization.mapper.convertValue( jsonWebToken.getOtherClaims().get("vc"), VerifiableCredential.class); - assertTrue("The static claim should be set.", - credential.getCredentialSubject().getClaims().containsKey("scope-name")); + assertTrue(credential.getCredentialSubject().getClaims().containsKey("scope-name"), + "The static claim should be set."); } catch (Exception e) { fail("Test failed with exception: " + e.getClass().getName() + ": " + e.getMessage()); @@ -287,10 +283,10 @@ public void testEncryptedCredentialRequestWithCompression() { AccessTokenResponse tokenResponse = getBearerToken(oauth, authCode, authDetail); String token = tokenResponse.getAccessToken(); List authDetailsResponse = tokenResponse.getOID4VCAuthorizationDetails(); - assertNotNull("authorization_details should be present in the response", authDetailsResponse); - assertFalse("authorization_details should not be empty", authDetailsResponse.isEmpty()); + assertNotNull(authDetailsResponse, "authorization_details should be present in the response"); + assertFalse(authDetailsResponse.isEmpty(), "authorization_details should not be empty"); String credentialIdentifier = authDetailsResponse.get(0).getCredentialIdentifiers().get(0); - assertNotNull("credential_identifier should be present", credentialIdentifier); + assertNotNull(credentialIdentifier, "credential_identifier should be present"); String cNonce = getCNonce(); testingClient.server(TEST_REALM_NAME).run(session -> { @@ -336,25 +332,23 @@ public void testEncryptedCredentialRequestWithCompression() { Response response = issuerEndpoint.requestCredential(encryptedRequest); // Verify response - assertEquals("Encrypted compressed request should be processed successfully", - 200, response.getStatus()); - assertEquals("Response should be JWT type for encrypted responses", - MediaType.APPLICATION_JWT, response.getMediaType().toString()); + assertEquals(200, response.getStatus(), "Encrypted compressed request should be processed successfully"); + assertEquals(MediaType.APPLICATION_JWT, response.getMediaType().toString(), "Response should be JWT type for encrypted responses"); // Decrypt and verify the response String encryptedResponse = (String) response.getEntity(); CredentialResponse decryptedResponse = decryptJweResponse(encryptedResponse, responsePrivateKey); - assertNotNull("Decrypted response should contain a credential", decryptedResponse.getCredentials()); + assertNotNull(decryptedResponse.getCredentials(), "Decrypted response should contain a credential"); JsonWebToken jsonWebToken = TokenVerifier.create( (String) decryptedResponse.getCredentials().get(0).getCredential(), JsonWebToken.class).getToken(); - assertNotNull("A valid credential string should have been responded", jsonWebToken); + assertNotNull(jsonWebToken, "A valid credential string should have been responded"); VerifiableCredential credential = JsonSerialization.mapper.convertValue( jsonWebToken.getOtherClaims().get("vc"), VerifiableCredential.class); - assertTrue("The static claim should be set.", - credential.getCredentialSubject().getClaims().containsKey("scope-name")); + assertTrue(credential.getCredentialSubject().getClaims().containsKey("scope-name"), + "The static claim should be set."); } catch (Exception e) { LOGGER.error("Test failed", e); @@ -383,12 +377,12 @@ public void testRequestCredentialWithIncompleteEncryptionParams() throws Throwab try { issuerEndpoint.requestCredential(credentialRequestPayload); - Assert.fail("Expected BadRequestException due to missing encryption parameter 'enc'"); + Assertions.fail("Expected BadRequestException due to missing encryption parameter 'enc'"); } catch (BadRequestException e) { ErrorResponse error = (ErrorResponse) e.getResponse().getEntity(); assertEquals(ErrorType.INVALID_ENCRYPTION_PARAMETERS.getValue(), error.getError()); - assertTrue("Error message should specify missing parameter 'enc'", - error.getErrorDescription().contains("Missing required parameters: enc")); + assertTrue(error.getErrorDescription().contains("Missing required parameters: enc"), + "Error message should specify missing parameter 'enc'"); } }); } @@ -557,10 +551,10 @@ public void testRequestCredentialWithInvalidJWK() throws Throwable { AccessTokenResponse tokenResponse = getBearerToken(oauth, authCode, authDetail); String token = tokenResponse.getAccessToken(); List authDetailsResponse = tokenResponse.getOID4VCAuthorizationDetails(); - assertNotNull("authorization_details should be present in the response", authDetailsResponse); - assertFalse("authorization_details should not be empty", authDetailsResponse.isEmpty()); + assertNotNull(authDetailsResponse, "authorization_details should be present in the response"); + assertFalse(authDetailsResponse.isEmpty(), "authorization_details should not be empty"); String credentialIdentifier = authDetailsResponse.get(0).getCredentialIdentifiers().get(0); - assertNotNull("credential_identifier should be present", credentialIdentifier); + assertNotNull(credentialIdentifier, "credential_identifier should be present"); String cNonce = getCNonce(); testingClient.server(TEST_REALM_NAME).run(session -> { @@ -582,12 +576,12 @@ public void testRequestCredentialWithInvalidJWK() throws Throwable { try { issuerEndpoint.requestCredential(requestPayload); - Assert.fail("Expected BadRequestException due to invalid JWK missing modulus"); + Assertions.fail("Expected BadRequestException due to invalid JWK missing modulus"); } catch (BadRequestException e) { ErrorResponse error = (ErrorResponse) e.getResponse().getEntity(); assertEquals(ErrorType.INVALID_ENCRYPTION_PARAMETERS.getValue(), error.getError()); - assertTrue("Error should mention invalid JWK. Actual: " + error.getErrorDescription(), - error.getErrorDescription().contains("Invalid JWK")); + assertTrue(error.getErrorDescription().contains("Invalid JWK"), + "Error should mention invalid JWK. Actual: " + error.getErrorDescription()); } }); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCIssuerEndpointTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCIssuerEndpointTest.java index fcc5ff3e458e..5f0821637d2a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCIssuerEndpointTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCIssuerEndpointTest.java @@ -100,7 +100,6 @@ import org.keycloak.representations.userprofile.config.UPConfig; import org.keycloak.services.managers.AppAuthManager; import org.keycloak.services.managers.AuthenticationManager; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.runonserver.RunOnServerException; @@ -123,6 +122,7 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.jboss.logging.Logger; import org.junit.Before; +import org.junit.jupiter.api.Assertions; import static org.keycloak.OID4VCConstants.CLAIM_NAME_VC; import static org.keycloak.OID4VCConstants.OID4VCI_ENABLED_ATTRIBUTE_KEY; @@ -143,11 +143,11 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.aMapWithSize; import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; /** * Moved test to subclass. so we can reuse initialization code. @@ -422,7 +422,7 @@ protected ClientScopeRepresentation registerOptionalClientScope(ClientScopeRepre protected ClientRepresentation requireExistingClient(String clientId) { List clientRepresentations = testRealm().clients().findByClientId(clientId); - assertFalse("No such client", clientRepresentations.isEmpty()); + assertFalse(clientRepresentations.isEmpty(), "No such client"); return clientRepresentations.get(0); } @@ -509,8 +509,8 @@ public static Map generateRsaJwkWithPrivateKey() throws NoSuchAl } public static CredentialResponse decryptJweResponse(String encryptedResponse, PrivateKey privateKey) throws IOException, JWEException { - assertNotNull("Encrypted response should not be null", encryptedResponse); - assertEquals("Response should be a JWE", 5, encryptedResponse.split("\\.").length); + assertNotNull(encryptedResponse, "Encrypted response should not be null"); + assertEquals(5, encryptedResponse.split("\\.").length, "Response should be a JWE"); JWE jwe = new JWE(encryptedResponse); jwe.getKeyStorage().setDecryptionKey(privateKey); @@ -678,7 +678,7 @@ protected void testCredentialIssuanceWithAuthZCodeFlow(ClientScopeRepresentation } } } catch (IOException e) { - Assert.fail(); + Assertions.fail(); } } @@ -787,25 +787,25 @@ protected static class CredentialResponseHandler { protected void handleCredentialResponse(CredentialResponse credentialResponse, ClientScopeRepresentation clientScope) throws VerificationException { - assertNotNull("The credentials array should be present in the response.", credentialResponse.getCredentials()); - assertFalse("The credentials array should not be empty.", credentialResponse.getCredentials().isEmpty()); + assertNotNull(credentialResponse.getCredentials(), "The credentials array should be present in the response."); + assertFalse(credentialResponse.getCredentials().isEmpty(), "The credentials array should not be empty."); // Get the first credential from the array (maintaining compatibility with single credential tests) CredentialResponse.Credential credentialObj = credentialResponse.getCredentials().get(0); - assertNotNull("The first credential in the array should not be null.", credentialObj); + assertNotNull(credentialObj, "The first credential in the array should not be null."); JsonWebToken jsonWebToken = TokenVerifier.create((String) credentialObj.getCredential(), JsonWebToken.class).getToken(); Map otherClaims = jsonWebToken.getOtherClaims(); log.infof("JsonWebToken: %s", valueAsPrettyString(jsonWebToken)); - assertNotNull("Expected jti claim", jsonWebToken.getId()); - assertNotNull("Expected exp claim", jsonWebToken.getExp()); - assertNotNull("Expected nbf claim", jsonWebToken.getNbf()); - assertNotNull("Expected iss claim", jsonWebToken.getIssuer()); - assertNotNull("Expected sub claim", jsonWebToken.getSubject()); + assertNotNull(jsonWebToken.getId(), "Expected jti claim"); + assertNotNull(jsonWebToken.getExp(), "Expected exp claim"); + assertNotNull(jsonWebToken.getNbf(), "Expected nbf claim"); + assertNotNull(jsonWebToken.getIssuer(), "Expected iss claim"); + assertNotNull(jsonWebToken.getSubject(), "Expected sub claim"); - assertNull("Unexpected aud claim", jsonWebToken.getAudience()); - assertNull("Unexpected iat claim", jsonWebToken.getIat()); + assertNull(jsonWebToken.getAudience(), "Unexpected aud claim"); + assertNull(jsonWebToken.getIat(), "Unexpected iat claim"); assertEquals("did:web:test.org", jsonWebToken.getIssuer()); assertEquals(Set.of(CLAIM_NAME_VC), otherClaims.keySet()); @@ -814,24 +814,24 @@ protected void handleCredentialResponse(CredentialResponse credentialResponse, VerifiableCredential credential = JsonSerialization.mapper.convertValue(vc, VerifiableCredential.class); Map subClaims = credential.getCredentialSubject().getClaims(); - assertNotNull("Expected vc.issuanceDate claim", credential.getIssuanceDate()); - assertNotNull("Expected vc.expirationDate claim", credential.getExpirationDate()); - assertNotNull("Expected vc.@context claim", credential.getContext()); - - assertEquals("vc.type mapped correctly", List.of(clientScope.getName()), credential.getType()); - assertEquals("iss mapped correctly", "did:web:test.org", jsonWebToken.getIssuer()); - assertEquals("vc.issuer mapped correctly", URI.create("did:web:test.org"), credential.getIssuer()); - assertEquals("vc.credentialSubject.id mapped correctly", jsonWebToken.getSubject(), subClaims.get("id")); - assertEquals("vc.credentialSubject.given_name mapped correctly", "John", subClaims.get("given_name")); - assertEquals("vc.credentialSubject.email mapped correctly", "john@email.cz", subClaims.get("email")); - assertEquals("vc.credentialSubject.scope-name mapped correctly", clientScope.getName(), subClaims.get("scope-name")); + assertNotNull(credential.getIssuanceDate(), "Expected vc.issuanceDate claim"); + assertNotNull(credential.getExpirationDate(), "Expected vc.expirationDate claim"); + assertNotNull(credential.getContext(), "Expected vc.@context claim"); + + assertEquals(List.of(clientScope.getName()), credential.getType(), "vc.type mapped correctly"); + assertEquals("did:web:test.org", jsonWebToken.getIssuer(), "iss mapped correctly"); + assertEquals(URI.create("did:web:test.org"), credential.getIssuer(), "vc.issuer mapped correctly"); + assertEquals(jsonWebToken.getSubject(), subClaims.get("id"), "vc.credentialSubject.id mapped correctly"); + assertEquals("John", subClaims.get("given_name"), "vc.credentialSubject.given_name mapped correctly"); + assertEquals("john@email.cz", subClaims.get("email"), "vc.credentialSubject.email mapped correctly"); + assertEquals(clientScope.getName(), subClaims.get("scope-name"), "vc.credentialSubject.scope-name mapped correctly"); assertThat("vc.credentialSubject.address is parent claim for nested claims", subClaims.get("address"), instanceOf(Map.class)); Map nestedAddressClaim = (Map) subClaims.get("address"); assertThat("vc.credentialSubject.address contains two nested claims", nestedAddressClaim, aMapWithSize(2)); - assertEquals("vc.credentialSubject.address.street_address mapped correctly", "221B Baker Street", nestedAddressClaim.get("street_address")); - assertEquals("vc.credentialSubject.address.locality mapped correctly", "London", nestedAddressClaim.get("locality")); + assertEquals("221B Baker Street", nestedAddressClaim.get("street_address"), "vc.credentialSubject.address.street_address mapped correctly"); + assertEquals("London", nestedAddressClaim.get("locality"), "vc.credentialSubject.address.locality mapped correctly"); - assertFalse("Unexpected other claim", subClaims.containsKey("AnotherCredentialType")); + assertFalse(subClaims.containsKey("AnotherCredentialType"), "Unexpected other claim"); } } @@ -839,7 +839,7 @@ protected List parseAuthorizationDetails(String respo Map responseMap = JsonSerialization.readValue(responseBody, new TypeReference>() { }); Object authDetailsObj = responseMap.get("authorization_details"); - assertNotNull("authorization_details should be present in the response", authDetailsObj); + assertNotNull(authDetailsObj, "authorization_details should be present in the response"); return JsonSerialization.readValue( JsonSerialization.writeValueAsString(authDetailsObj), new TypeReference>() { @@ -851,7 +851,7 @@ protected String getAccessToken(String responseBody) throws IOException { Map responseMap = JsonSerialization.readValue(responseBody, new TypeReference>() { }); String token = (String) responseMap.get("access_token"); - assertNotNull("Access token should be present", token); + assertNotNull(token, "Access token should be present"); return token; } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCJWTIssuerEndpointDisabledTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCJWTIssuerEndpointDisabledTest.java index 57bab447e051..7a4b4165df8e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCJWTIssuerEndpointDisabledTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCJWTIssuerEndpointDisabledTest.java @@ -10,13 +10,13 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.services.CorsErrorResponseException; import org.keycloak.services.managers.AppAuthManager; -import org.keycloak.testsuite.Assert; import org.keycloak.util.JsonSerialization; import com.fasterxml.jackson.core.JsonProcessingException; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests for OID4VCIssuerEndpoint with OID4VCI disabled. @@ -45,9 +45,8 @@ public void testRealmDisabledEndpoints() { OID4VCIssuerEndpoint issuerEndpoint = prepareIssuerEndpoint(session, authenticator); // Nonce endpoint should be forbidden when OID4VCI is disabled for the realm - CorsErrorResponseException nonceException = Assert.assertThrows(CorsErrorResponseException.class, issuerEndpoint::getCNonce); - assertEquals("Realm-disabled OID4VCI should return 403 for nonce endpoint", - Response.Status.FORBIDDEN.getStatusCode(), nonceException.getResponse().getStatus()); + CorsErrorResponseException nonceException = Assertions.assertThrows(CorsErrorResponseException.class, issuerEndpoint::getCNonce); + assertEquals(Response.Status.FORBIDDEN.getStatusCode(), nonceException.getResponse().getStatus(), "Realm-disabled OID4VCI should return 403 for nonce endpoint"); })); } @@ -59,11 +58,10 @@ public void testClientNotEnabled() { OID4VCIssuerEndpoint issuerEndpoint = prepareIssuerEndpoint(session, authenticator); // Test getCredentialOfferURI - CorsErrorResponseException offerUriException = Assert.assertThrows(CorsErrorResponseException.class, () -> + CorsErrorResponseException offerUriException = Assertions.assertThrows(CorsErrorResponseException.class, () -> issuerEndpoint.createCredentialOffer("test-credential") ); - assertEquals("Should fail with 403 Forbidden when client is not OID4VCI-enabled", - Response.Status.FORBIDDEN.getStatusCode(), offerUriException.getResponse().getStatus()); + assertEquals(Response.Status.FORBIDDEN.getStatusCode(), offerUriException.getResponse().getStatus(), "Should fail with 403 Forbidden when client is not OID4VCI-enabled"); // Test requestCredential CredentialRequest credentialRequest = new CredentialRequest() @@ -72,14 +70,13 @@ public void testClientNotEnabled() { try { requestPayload = JsonSerialization.writeValueAsString(credentialRequest); } catch (JsonProcessingException e) { - Assert.fail("Failed to serialize CredentialRequest: " + e.getMessage()); + Assertions.fail("Failed to serialize CredentialRequest: " + e.getMessage()); return; } - CorsErrorResponseException requestException = Assert.assertThrows(CorsErrorResponseException.class, () -> + CorsErrorResponseException requestException = Assertions.assertThrows(CorsErrorResponseException.class, () -> issuerEndpoint.requestCredential(requestPayload) ); - assertEquals("Should fail with 403 Forbidden when client is not OID4VCI-enabled", - Response.Status.FORBIDDEN.getStatusCode(), requestException.getResponse().getStatus()); + assertEquals(Response.Status.FORBIDDEN.getStatusCode(), requestException.getResponse().getStatus(), "Should fail with 403 Forbidden when client is not OID4VCI-enabled"); })); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCSdJwtIssuingEndpointDisabledTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCSdJwtIssuingEndpointDisabledTest.java index 38139d44fd98..78abd8317f98 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCSdJwtIssuingEndpointDisabledTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCSdJwtIssuingEndpointDisabledTest.java @@ -10,13 +10,13 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.services.CorsErrorResponseException; import org.keycloak.services.managers.AppAuthManager; -import org.keycloak.testsuite.Assert; import org.keycloak.util.JsonSerialization; import com.fasterxml.jackson.core.JsonProcessingException; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests for OID4VCIssuerEndpoint with OID4VCI disabled for SD-JWT format @@ -41,11 +41,10 @@ public void testClientNotEnabled() { OID4VCIssuerEndpoint issuerEndpoint = prepareIssuerEndpoint(session, authenticator); // Test getCredentialOfferURI - CorsErrorResponseException offerUriException = Assert.assertThrows(CorsErrorResponseException.class, () -> + CorsErrorResponseException offerUriException = Assertions.assertThrows(CorsErrorResponseException.class, () -> issuerEndpoint.createCredentialOffer("test-credential") ); - assertEquals("Should fail with 403 Forbidden when client is not OID4VCI-enabled", - Response.Status.FORBIDDEN.getStatusCode(), offerUriException.getResponse().getStatus()); + assertEquals(Response.Status.FORBIDDEN.getStatusCode(), offerUriException.getResponse().getStatus(), "Should fail with 403 Forbidden when client is not OID4VCI-enabled"); CredentialRequest credentialRequest = new CredentialRequest() .setCredentialConfigurationId(sdJwtTypeCredentialConfigurationIdName); @@ -53,14 +52,13 @@ public void testClientNotEnabled() { try { requestPayload = JsonSerialization.writeValueAsString(credentialRequest); } catch (JsonProcessingException e) { - Assert.fail("Failed to serialize CredentialRequest: " + e.getMessage()); + Assertions.fail("Failed to serialize CredentialRequest: " + e.getMessage()); return; } - CorsErrorResponseException requestException = Assert.assertThrows(CorsErrorResponseException.class, () -> + CorsErrorResponseException requestException = Assertions.assertThrows(CorsErrorResponseException.class, () -> issuerEndpoint.requestCredential(requestPayload) ); - assertEquals("Should fail with 403 Forbidden when client is not OID4VCI-enabled", - Response.Status.FORBIDDEN.getStatusCode(), requestException.getResponse().getStatus()); + assertEquals(Response.Status.FORBIDDEN.getStatusCode(), requestException.getResponse().getStatus(), "Should fail with 403 Forbidden when client is not OID4VCI-enabled"); })); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCSdJwtIssuingEndpointTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCSdJwtIssuingEndpointTest.java index 94623134c16e..4ff4ca22f25f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCSdJwtIssuingEndpointTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCSdJwtIssuingEndpointTest.java @@ -68,19 +68,19 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.http.HttpStatus; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.OID4VCConstants.CLAIM_NAME_SUBJECT_ID; import static org.keycloak.OID4VCConstants.OPENID_CREDENTIAL; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Endpoint test with sd-jwt specific config. @@ -148,7 +148,7 @@ public void testRequestTestCredentialWithKeybinding() { ClientScopeRepresentation.class); SdJwtVP sdJwtVP = testRequestTestCredential(session, clientScope, token, proof, credentialIdentifier); - assertNotNull("A cnf claim must be attached to the credential", sdJwtVP.getCnfClaim()); + assertNotNull(sdJwtVP.getCnfClaim(), "A cnf claim must be attached to the credential"); })); } @@ -183,11 +183,11 @@ public void testRequestTestCredentialWithInvalidKeybinding() throws Throwable { testRequestTestCredential(session, clientScope, token, proof, credentialIdentifier); })); }); - Assert.fail("Should have thrown an exception"); + Assertions.fail("Should have thrown an exception"); } catch (ErrorResponseException ex) { String message = ex.getErrorDescription(); - Assert.assertEquals(ErrorType.INVALID_PROOF.getValue(), ex.getError()); - Assert.assertTrue("Unexpected: " + message, message.contains("Could not verify signature of provided proof")); + Assertions.assertEquals(ErrorType.INVALID_PROOF.getValue(), ex.getError()); + Assertions.assertTrue(message.contains("Could not verify signature of provided proof"), "Unexpected: " + message); } } @@ -225,11 +225,11 @@ public void testProofOfPossessionWithMissingAudience() throws Throwable { ClientScopeRepresentation.class); testRequestTestCredential(session, clientScope, token, proof, credentialIdentifier); }))); - Assert.fail("Should have thrown an exception"); + Assertions.fail("Should have thrown an exception"); } catch (ErrorResponseException ex) { String message = ex.getErrorDescription(); - Assert.assertEquals(ErrorType.INVALID_NONCE.getValue(), ex.getError()); - Assert.assertEquals(""" + Assertions.assertEquals(ErrorType.INVALID_NONCE.getValue(), ex.getError()); + Assertions.assertEquals(""" c_nonce: expected 'aud' to be equal to \ '[https://localhost:8543/auth/realms/test/protocol/oid4vc/credential]' but \ actual value was '[]'""", message); @@ -269,11 +269,11 @@ public void testProofOfPossessionWithIllegalSourceEndpoint() throws Throwable { ClientScopeRepresentation.class); testRequestTestCredential(session, clientScope, token, proof, credentialIdentifier); }))); - Assert.fail("Should have thrown an exception"); + Assertions.fail("Should have thrown an exception"); } catch (ErrorResponseException ex) { String message = ex.getErrorDescription(); - Assert.assertEquals(ErrorType.INVALID_NONCE.getValue(), ex.getError()); - Assert.assertEquals(""" + Assertions.assertEquals(ErrorType.INVALID_NONCE.getValue(), ex.getError()); + Assertions.assertEquals(""" c_nonce: expected 'source_endpoint' to be equal to \ 'https://localhost:8543/auth/realms/test/protocol/oid4vc/nonce' but \ actual value was 'null'""", message); @@ -321,12 +321,12 @@ public void testProofOfPossessionWithExpiredState() throws Throwable { session.getContext().getRealm().removeAttribute(OID4VCIConstants.C_NONCE_LIFETIME_IN_SECONDS); } }))); - Assert.fail("Should have thrown an exception"); + Assertions.fail("Should have thrown an exception"); } catch (ErrorResponseException ex) { String message = ex.getErrorDescription(); - Assert.assertEquals(ErrorType.INVALID_NONCE.getValue(), ex.getError()); - Assert.assertTrue(String.format("Message '%s' should match regular expression", message), - message.matches("c_nonce not valid: \\d+\\(exp\\) < \\d+\\(now\\)")); + Assertions.assertEquals(ErrorType.INVALID_NONCE.getValue(), ex.getError()); + Assertions.assertTrue(message.matches("c_nonce not valid: \\d+\\(exp\\) < \\d+\\(now\\)"), + String.format("Message '%s' should match regular expression", message)); } } @@ -350,10 +350,10 @@ private static SdJwtVP testRequestTestCredential(KeycloakSession session, Client String requestPayload = JsonSerialization.writeValueAsString(credentialRequest); Response credentialResponse = issuerEndpoint.requestCredential(requestPayload); - assertEquals("The credential request should be answered successfully.", - HttpStatus.SC_OK, - credentialResponse.getStatus()); - assertNotNull("A credential should be responded.", credentialResponse.getEntity()); + assertEquals(HttpStatus.SC_OK, + credentialResponse.getStatus(), + "The credential request should be answered successfully."); + assertNotNull(credentialResponse.getEntity(), "A credential should be responded."); CredentialResponse credentialResponseVO = JsonSerialization.mapper.convertValue(credentialResponse.getEntity(), CredentialResponse.class); new TestCredentialResponseHandler(sdJwtCredentialVct).handleCredentialResponse(credentialResponseVO, @@ -386,13 +386,13 @@ public void testCredentialIssuance() throws Exception { .send() .getCredentialOfferURI(); - assertNotNull("A valid offer uri should be returned", credOfferUri); + assertNotNull(credOfferUri, "A valid offer uri should be returned"); // 2. Using the uri to get the actual credential offer CredentialOfferResponse credentialOfferResponse = oauth.oid4vc().doCredentialOfferRequest(credOfferUri); CredentialsOffer credentialsOffer = credentialOfferResponse.getCredentialsOffer(); - assertNotNull("A valid offer should be returned", credentialsOffer); + assertNotNull(credentialsOffer, "A valid offer should be returned"); // 3. Get the issuer metadata CredentialIssuer credentialIssuer = oauth.oid4vc() @@ -401,8 +401,8 @@ public void testCredentialIssuance() throws Exception { .send() .getMetadata(); - assertNotNull("Issuer metadata should be returned", credentialIssuer); - assertEquals("We only expect one authorization server.", 1, credentialIssuer.getAuthorizationServers().size()); + assertNotNull(credentialIssuer, "Issuer metadata should be returned"); + assertEquals(1, credentialIssuer.getAuthorizationServers().size(), "We only expect one authorization server."); // 4. Get the openid-configuration OIDCConfigurationRepresentation openidConfig = oauth @@ -411,8 +411,8 @@ public void testCredentialIssuance() throws Exception { .send() .getOidcConfiguration(); - assertNotNull("A token endpoint should be included.", openidConfig.getTokenEndpoint()); - assertTrue("The pre-authorized code should be supported.", openidConfig.getGrantTypesSupported().contains(PreAuthorizedCodeGrant.PRE_AUTH_GRANT_TYPE)); + assertNotNull(openidConfig.getTokenEndpoint(), "A token endpoint should be included."); + assertTrue(openidConfig.getGrantTypesSupported().contains(PreAuthorizedCodeGrant.PRE_AUTH_GRANT_TYPE), "The pre-authorized code should be supported."); // 5. Get an access token for the pre-authorized code AccessTokenResponse accessTokenResponse = oauth.oid4vc() @@ -422,14 +422,14 @@ public void testCredentialIssuance() throws Exception { assertEquals(HttpStatus.SC_OK, accessTokenResponse.getStatusCode()); String theToken = accessTokenResponse.getAccessToken(); - assertNotNull("Access token should be present", theToken); + assertNotNull(theToken, "Access token should be present"); // Extract credential_identifier from authorization_details in token response List authDetailsResponse = accessTokenResponse.getOID4VCAuthorizationDetails(); - assertNotNull("authorization_details should be present in the response", authDetailsResponse); - assertFalse("authorization_details should not be empty", authDetailsResponse.isEmpty()); + assertNotNull(authDetailsResponse, "authorization_details should be present in the response"); + assertFalse(authDetailsResponse.isEmpty(), "authorization_details should not be empty"); String credentialIdentifier = authDetailsResponse.get(0).getCredentialIdentifiers().get(0); - assertNotNull("Credential identifier should be present", credentialIdentifier); + assertNotNull(credentialIdentifier, "Credential identifier should be present"); String cNonce = getCNonce(); final String vct = clientScope.getAttributes().get(CredentialScopeModel.VCT); @@ -441,8 +441,8 @@ public void testCredentialIssuance() throws Exception { .proofs(proof) .bearerToken(theToken) .send(); - assertEquals("The credential request should be answered successfully.", HttpStatus.SC_OK, credentialResponse.getStatusCode()); - assertNotNull("A credential should be responded.", credentialResponse.getCredentialResponse()); + assertEquals(HttpStatus.SC_OK, credentialResponse.getStatusCode(), "The credential request should be answered successfully."); + assertNotNull(credentialResponse.getCredentialResponse(), "A credential should be responded."); new TestCredentialResponseHandler(vct).handleCredentialResponse(credentialResponse.getCredentialResponse(), clientScope); } @@ -466,133 +466,133 @@ public void testGetSdJwtConfigFromMetadata() { .run((session -> { OID4VCIssuerWellKnownProvider oid4VCIssuerWellKnownProvider = new OID4VCIssuerWellKnownProvider(session); CredentialIssuer credentialIssuer = oid4VCIssuerWellKnownProvider.getIssuerMetadata(); - assertEquals("The correct issuer should be included.", expectedIssuer, credentialIssuer.getCredentialIssuer()); - assertEquals("The correct credentials endpoint should be included.", expectedCredentialsEndpoint, credentialIssuer.getCredentialEndpoint()); - assertEquals("The correct nonce endpoint should be included.", - expectedNonceEndpoint, - credentialIssuer.getNonceEndpoint()); - assertEquals("Since the authorization server is equal to the issuer, just 1 should be returned.", 1, credentialIssuer.getAuthorizationServers().size()); - assertEquals("The expected server should have been returned.", expectedAuthorizationServer, credentialIssuer.getAuthorizationServers().get(0)); + assertEquals(expectedIssuer, credentialIssuer.getCredentialIssuer(), "The correct issuer should be included."); + assertEquals(expectedCredentialsEndpoint, credentialIssuer.getCredentialEndpoint(), "The correct credentials endpoint should be included."); + assertEquals(expectedNonceEndpoint, + credentialIssuer.getNonceEndpoint(), + "The correct nonce endpoint should be included."); + assertEquals(1, credentialIssuer.getAuthorizationServers().size(), "Since the authorization server is equal to the issuer, just 1 should be returned."); + assertEquals(expectedAuthorizationServer, credentialIssuer.getAuthorizationServers().get(0), "The expected server should have been returned."); - assertTrue("The sd-jwt-credential should be supported.", - credentialIssuer.getCredentialsSupported().containsKey(credentialConfigurationId)); + assertTrue(credentialIssuer.getCredentialsSupported().containsKey(credentialConfigurationId), + "The sd-jwt-credential should be supported."); SupportedCredentialConfiguration jwtVcConfig = credentialIssuer.getCredentialsSupported().get(credentialConfigurationId); - assertEquals("The sd-jwt-credential should offer type test-credential", - scopeName, - jwtVcConfig.getScope()); - assertEquals("The sd-jwt-credential should be offered in the jwt_vc format.", - VCFormat.SD_JWT_VC, - jwtVcConfig.getFormat()); - - assertNotNull("The sd-jwt-credential can optionally provide a claims claim.", - credentialIssuer.getCredentialsSupported().get(credentialConfigurationId) + assertEquals(scopeName, + jwtVcConfig.getScope(), + "The sd-jwt-credential should offer type test-credential"); + assertEquals(VCFormat.SD_JWT_VC, + jwtVcConfig.getFormat(), + "The sd-jwt-credential should be offered in the jwt_vc format."); + + assertNotNull(credentialIssuer.getCredentialsSupported().get(credentialConfigurationId) .getCredentialMetadata() != null ? credentialIssuer.getCredentialsSupported().get(credentialConfigurationId) - .getCredentialMetadata().getClaims() : null); + .getCredentialMetadata().getClaims() : null, + "The sd-jwt-credential can optionally provide a claims claim."); Claims jwtVcClaims = jwtVcConfig.getCredentialMetadata() != null ? jwtVcConfig.getCredentialMetadata().getClaims() : null; - assertNotNull("The sd-jwt-credential can optionally provide a claims claim.", - jwtVcClaims); + assertNotNull(jwtVcClaims, + "The sd-jwt-credential can optionally provide a claims claim."); assertEquals(7, jwtVcClaims.size()); { Claim claim = jwtVcClaims.get(0); - assertEquals("id claim is present", CLAIM_NAME_SUBJECT_ID, claim.getPath().get(0)); - assertFalse("id claim not mandatory.", claim.isMandatory()); - assertNull("id has no display value", claim.getDisplay()); + assertEquals(CLAIM_NAME_SUBJECT_ID, claim.getPath().get(0), "id claim is present"); + assertFalse(claim.isMandatory(), "id claim not mandatory."); + assertNull(claim.getDisplay(), "id has no display value"); } { Claim claim = jwtVcClaims.get(1); - assertEquals("email claim is present", "email", claim.getPath().get(0)); - assertFalse("email claim not mandatory.", claim.isMandatory()); - assertNull("email has no display value", claim.getDisplay()); + assertEquals("email", claim.getPath().get(0), "email claim is present"); + assertFalse(claim.isMandatory(), "email claim not mandatory."); + assertNull(claim.getDisplay(), "email has no display value"); } { Claim claim = jwtVcClaims.get(2); - assertEquals("firstName claim is present", "firstName", claim.getPath().get(0)); - assertFalse("firstName claim not mandatory.", claim.isMandatory()); - assertNull("firstName has no display value", claim.getDisplay()); + assertEquals("firstName", claim.getPath().get(0), "firstName claim is present"); + assertFalse(claim.isMandatory(), "firstName claim not mandatory."); + assertNull(claim.getDisplay(), "firstName has no display value"); } { Claim claim = jwtVcClaims.get(3); - assertEquals("lastName claim is present", "lastName", claim.getPath().get(0)); - assertFalse("lastName claim not mandatory.", claim.isMandatory()); - assertNull("lastName has no display value", claim.getDisplay()); + assertEquals("lastName", claim.getPath().get(0), "lastName claim is present"); + assertFalse(claim.isMandatory(), "lastName claim not mandatory."); + assertNull(claim.getDisplay(), "lastName has no display value"); } { Claim claim = jwtVcClaims.get(4); - assertEquals("address.street_address claim is nested.", - 2, - claim.getPath().size()); - assertEquals("address.street_address claim has correct parent claim name.", - "address", - claim.getPath().get(0)); - assertEquals("address.street_address claim has correct nested claim name.", - "street_address", - claim.getPath().get(1)); - assertFalse("address.street_address claim is not mandatory.", - claim.isMandatory()); - assertNull("address.street_address claim has no display value", - claim.getDisplay()); + assertEquals(2, + claim.getPath().size(), + "address.street_address claim is nested."); + assertEquals("address", + claim.getPath().get(0), + "address.street_address claim has correct parent claim name."); + assertEquals("street_address", + claim.getPath().get(1), + "address.street_address claim has correct nested claim name."); + assertFalse(claim.isMandatory(), + "address.street_address claim is not mandatory."); + assertNull(claim.getDisplay(), + "address.street_address claim has no display value"); } { Claim claim = jwtVcClaims.get(5); - assertEquals("address.locality claim is nested.", - 2, - claim.getPath().size()); - assertEquals("address.locality claim has correct parent claim name.", - "address", - claim.getPath().get(0)); - assertEquals("address.locality claim has correct nested claim name.", - "locality", - claim.getPath().get(1)); - assertFalse("address.locality claim is not mandatory.", - claim.isMandatory()); - assertNull("address.locality claim has no display value", - claim.getDisplay()); + assertEquals(2, + claim.getPath().size(), + "address.locality claim is nested."); + assertEquals("address", + claim.getPath().get(0), + "address.locality claim has correct parent claim name."); + assertEquals("locality", + claim.getPath().get(1), + "address.locality claim has correct nested claim name."); + assertFalse(claim.isMandatory(), + "address.locality claim is not mandatory."); + assertNull(claim.getDisplay(), + "address.locality claim has no display value"); } { Claim claim = jwtVcClaims.get(6); - assertEquals("scope-name claim is present", "scope-name", claim.getPath().get(0)); - assertFalse("scope-name claim not mandatory.", claim.isMandatory()); - assertNull("scope-name has no display value", claim.getDisplay()); + assertEquals("scope-name", claim.getPath().get(0), "scope-name claim is present"); + assertFalse(claim.isMandatory(), "scope-name claim not mandatory."); + assertNull(claim.getDisplay(), "scope-name has no display value"); } - assertEquals("The sd-jwt-credential should offer vct", - verifiableCredentialType, - credentialIssuer.getCredentialsSupported().get(credentialConfigurationId).getVct()); + assertEquals(verifiableCredentialType, + credentialIssuer.getCredentialsSupported().get(credentialConfigurationId).getVct(), + "The sd-jwt-credential should offer vct"); - assertNotNull("Cryptographic binding methods should be advertised for SD-JWT test credential", - credentialIssuer.getCredentialsSupported().get(credentialConfigurationId) - .getCryptographicBindingMethodsSupported()); - assertTrue("The sd-jwt-credential should contain a credential signing algorithm named ES256", - credentialIssuer.getCredentialsSupported().get(credentialConfigurationId) - .getCredentialSigningAlgValuesSupported().contains("ES256")); + assertNotNull(credentialIssuer.getCredentialsSupported().get(credentialConfigurationId) + .getCryptographicBindingMethodsSupported(), + "Cryptographic binding methods should be advertised for SD-JWT test credential"); + assertTrue(credentialIssuer.getCredentialsSupported().get(credentialConfigurationId) + .getCredentialSigningAlgValuesSupported().contains("ES256"), + "The sd-jwt-credential should contain a credential signing algorithm named ES256"); SupportedCredentialConfiguration sdJwtConfig = credentialIssuer.getCredentialsSupported().get(credentialConfigurationId); - assertNotNull("Proof types should be advertised when binding is required", - sdJwtConfig.getProofTypesSupported()); - assertNotNull("JWT proof type should be present for SD-JWT test credential", - sdJwtConfig.getProofTypesSupported() + assertNotNull(sdJwtConfig.getProofTypesSupported(), + "Proof types should be advertised when binding is required"); + assertNotNull(sdJwtConfig.getProofTypesSupported() .getSupportedProofTypes() - .get("jwt")); - assertTrue("The sd-jwt-credential should support a proof of type jwt with signing algorithm ES256", - sdJwtConfig.getProofTypesSupported() + .get("jwt"), + "JWT proof type should be present for SD-JWT test credential"); + assertTrue(sdJwtConfig.getProofTypesSupported() .getSupportedProofTypes() .get("jwt") .getSigningAlgorithmsSupported() - .contains("ES256")); - assertEquals("The sd-jwt-credential should display as Test Credential", - credentialConfigurationId, + .contains("ES256"), + "The sd-jwt-credential should support a proof of type jwt with signing algorithm ES256"); + assertEquals(credentialConfigurationId, credentialIssuer.getCredentialsSupported().get(credentialConfigurationId) .getCredentialMetadata() != null && credentialIssuer.getCredentialsSupported().get(credentialConfigurationId) .getCredentialMetadata().getDisplay() != null ? credentialIssuer.getCredentialsSupported().get(credentialConfigurationId) - .getCredentialMetadata().getDisplay().get(0).getName() : null); + .getCredentialMetadata().getDisplay().get(0).getName() : null, + "The sd-jwt-credential should display as Test Credential"); })); } @@ -654,10 +654,10 @@ protected void handleCredentialResponse(CredentialResponse credentialResponse, C SdJwtVP sdJwtVP = SdJwtVP.of(credentialResponse.getCredentials().get(0).getCredential().toString()); JsonWebToken jsonWebToken = TokenVerifier.create(sdJwtVP.getIssuerSignedJWT().getJws(), JsonWebToken.class).getToken(); - assertNotNull("A valid credential string should have been responded", jsonWebToken); - assertNotNull("The credentials should include the id claim", jsonWebToken.getId()); - assertNotNull("The credentials should be included at the vct-claim.", jsonWebToken.getOtherClaims().get("vct")); - assertEquals("The credentials should be included at the vct-claim.", vct, jsonWebToken.getOtherClaims().get("vct").toString()); + assertNotNull(jsonWebToken, "A valid credential string should have been responded"); + assertNotNull(jsonWebToken.getId(), "The credentials should include the id claim"); + assertNotNull(jsonWebToken.getOtherClaims().get("vct"), "The credentials should be included at the vct-claim."); + assertEquals(vct, jsonWebToken.getOtherClaims().get("vct").toString(), "The credentials should be included at the vct-claim."); Map disclosureMap = sdJwtVP.getDisclosures().values().stream() .map(disclosure -> { @@ -669,28 +669,28 @@ protected void handleCredentialResponse(CredentialResponse credentialResponse, C } }) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - assertFalse("Only mappers supported for the requested type should have been evaluated.", disclosureMap.containsKey("given_name")); - assertTrue("The credentials should include the firstName claim.", disclosureMap.containsKey("firstName")); - assertEquals("firstName claim incorrectly mapped.", "John", disclosureMap.get("firstName").get(2).asText()); - assertTrue("The credentials should include the lastName claim.", disclosureMap.containsKey("lastName")); - assertEquals("lastName claim incorrectly mapped.", "Doe", disclosureMap.get("lastName").get(2).asText()); + assertFalse(disclosureMap.containsKey("given_name"), "Only mappers supported for the requested type should have been evaluated."); + assertTrue(disclosureMap.containsKey("firstName"), "The credentials should include the firstName claim."); + assertEquals("John", disclosureMap.get("firstName").get(2).asText(), "firstName claim incorrectly mapped."); + assertTrue(disclosureMap.containsKey("lastName"), "The credentials should include the lastName claim."); + assertEquals("Doe", disclosureMap.get("lastName").get(2).asText(), "lastName claim incorrectly mapped."); assertThat("address is parent claim for nested claims", disclosureMap.get("address").get(2), instanceOf(ObjectNode.class)); ObjectNode nestedAddressClaim = (ObjectNode) disclosureMap.get("address").get(2); - assertEquals("address contains two nested claims", 2, nestedAddressClaim.size()); - assertEquals("street_address mapped correctly", "221B Baker Street", nestedAddressClaim.get("street_address").asText()); - assertEquals("locality mapped correctly", "London", nestedAddressClaim.get("locality").asText()); - - assertTrue("The credentials should include the scope-name claim.", - disclosureMap.containsKey("scope-name")); - assertEquals("The credentials should include the scope-name claims correct value.", - clientScope.getName(), - disclosureMap.get("scope-name").get(2).textValue()); - assertTrue("The credentials should include the email claim.", disclosureMap.containsKey("email")); - assertEquals("email claim incorrectly mapped.", "john@email.cz", disclosureMap.get("email").get(2).asText()); - - assertNotNull("Test credential shall include an iat claim.", jsonWebToken.getIat()); - assertNotNull("Test credential shall include an nbf claim.", jsonWebToken.getNbf()); + assertEquals(2, nestedAddressClaim.size(), "address contains two nested claims"); + assertEquals("221B Baker Street", nestedAddressClaim.get("street_address").asText(), "street_address mapped correctly"); + assertEquals("London", nestedAddressClaim.get("locality").asText(), "locality mapped correctly"); + + assertTrue(disclosureMap.containsKey("scope-name"), + "The credentials should include the scope-name claim."); + assertEquals(clientScope.getName(), + disclosureMap.get("scope-name").get(2).textValue(), + "The credentials should include the scope-name claims correct value."); + assertTrue(disclosureMap.containsKey("email"), "The credentials should include the email claim."); + assertEquals("john@email.cz", disclosureMap.get("email").get(2).asText(), "email claim incorrectly mapped."); + + assertNotNull(jsonWebToken.getIat(), "Test credential shall include an iat claim."); + assertNotNull(jsonWebToken.getNbf(), "Test credential shall include an nbf claim."); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCSdJwtPreInstalledNaturalPersonTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCSdJwtPreInstalledNaturalPersonTest.java index 13f44494d6d4..f0b1cc242d7b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCSdJwtPreInstalledNaturalPersonTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCSdJwtPreInstalledNaturalPersonTest.java @@ -29,9 +29,9 @@ import static org.keycloak.models.oid4vci.CredentialScopeModel.VC_CONFIGURATION_ID; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; /** * OID4VCI testing for the pre-installed oid4vc_natural_person diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCTest.java index 0099268a3f9d..84b03934052a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCTest.java @@ -109,8 +109,8 @@ import com.fasterxml.jackson.core.type.TypeReference; import org.apache.http.HttpStatus; import org.jboss.logging.Logger; -import org.junit.Assert; import org.junit.BeforeClass; +import org.junit.jupiter.api.Assertions; import static org.keycloak.OID4VCConstants.CLAIM_NAME_SUBJECT_ID; import static org.keycloak.OID4VCConstants.OPENID_CREDENTIAL; @@ -647,11 +647,11 @@ public static String getCNonce() { .header(HttpHeaders.COOKIE, null); try (Response response = nonceInvocationBuilder.post(null)) { - Assert.assertEquals(HttpStatus.SC_OK, response.getStatus()); - Assert.assertTrue(response.getMediaType().toString().startsWith(MediaType.APPLICATION_JSON_TYPE.toString())); + Assertions.assertEquals(HttpStatus.SC_OK, response.getStatus()); + Assertions.assertTrue(response.getMediaType().toString().startsWith(MediaType.APPLICATION_JSON_TYPE.toString())); nonceResponseString = parseResponse(response); - Assert.assertNotNull(nonceResponseString); - Assert.assertEquals("no-store", response.getHeaderString(HttpHeaders.CACHE_CONTROL)); + Assertions.assertNotNull(nonceResponseString); + Assertions.assertEquals("no-store", response.getHeaderString(HttpHeaders.CACHE_CONTROL)); } } NonceResponse nonceResponse; diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/SdJwtCredentialSignerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/SdJwtCredentialSignerTest.java index a106c09dbbb7..49ce40bd6c1f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/SdJwtCredentialSignerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/SdJwtCredentialSignerTest.java @@ -59,11 +59,11 @@ import static org.keycloak.OID4VCConstants.CLAIM_NAME_SD_HASH_ALGORITHM; import static org.keycloak.OID4VCConstants.SDJWT_DELIMITER; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class SdJwtCredentialSignerTest extends OID4VCTest { @@ -252,14 +252,13 @@ public void testSdJwtCredentialContainsX5cHeader() { verifier.verify(); JWSHeader header = verifier.getHeader(); - assertNotNull("x5c header should be present in SD-JWT credential", header.getX5c()); - assertFalse("x5c header should contain at least one certificate", header.getX5c().isEmpty()); + assertNotNull(header.getX5c(), "x5c header should be present in SD-JWT credential"); + assertFalse(header.getX5c().isEmpty(), "x5c header should contain at least one certificate"); if (keyWrapper.getCertificate() != null) { try { String expectedCert = Base64.getEncoder().encodeToString(keyWrapper.getCertificate().getEncoded()); - assertEquals("First certificate in x5c should match the signing key certificate", - expectedCert, header.getX5c().get(0)); + assertEquals(expectedCert, header.getX5c().get(0), "First certificate in x5c should match the signing key certificate"); } catch (CertificateEncodingException e) { fail("Failed to encode certificate for comparison: " + e.getMessage()); } @@ -332,21 +331,21 @@ public static void testSignSDJwtCredential(KeycloakSession session, String signi try { JsonWebToken theToken = verifier.getToken(); - assertEquals("The issuer should be set in the token.", TEST_DID.toString(), theToken.getIssuer()); - assertEquals("The type should be included", "https://credentials.example.com/test-credential", theToken.getOtherClaims().get("vct")); + assertEquals(TEST_DID.toString(), theToken.getIssuer(), "The issuer should be set in the token."); + assertEquals("https://credentials.example.com/test-credential", theToken.getOtherClaims().get("vct"), "The type should be included"); List sds = (List) theToken.getOtherClaims().get(CLAIM_NAME_SD); if (sds != null && !sds.isEmpty()) { - assertEquals("The algorithm should be included", OID4VCConstants.SD_HASH_DEFAULT_ALGORITHM, theToken.getOtherClaims().get(CLAIM_NAME_SD_HASH_ALGORITHM)); + assertEquals(OID4VCConstants.SD_HASH_DEFAULT_ALGORITHM, theToken.getOtherClaims().get(CLAIM_NAME_SD_HASH_ALGORITHM), "The algorithm should be included"); } List disclosed = Arrays.asList(splittedSdToken).subList(1, splittedSdToken.length); int numSds = sds != null ? sds.size() : 0; - assertEquals("All undisclosed claims and decoys should be provided.", - disclosed.size() + (decoys == 0 ? decoys + SdJwt.DEFAULT_NUMBER_OF_DECOYS : decoys), - numSds); + assertEquals(disclosed.size() + (decoys == 0 ? decoys + SdJwt.DEFAULT_NUMBER_OF_DECOYS : decoys), + numSds, + "All undisclosed claims and decoys should be provided."); verifyDisclosures(sds, disclosed); visibleClaims - .forEach(vc -> assertTrue("The visible claims should be present within the token.", theToken.getOtherClaims().containsKey(vc))); + .forEach(vc -> assertTrue(theToken.getOtherClaims().containsKey(vc), "The visible claims should be present within the token.")); } catch (VerificationException e) { fail("Was not able to extract the token."); } @@ -363,7 +362,7 @@ private static void verifyDisclosures(List undisclosed, List dis } }) .map(dl -> new DisclosedClaim((String) dl.get(0), (String) dl.get(1), dl.get(2))) - .forEach(dc -> assertTrue("Every disclosure claim should be provided in the undisclosures.", undisclosed.contains(dc.getHash()))); + .forEach(dc -> assertTrue(undisclosed.contains(dc.getHash()), "Every disclosure claim should be provided in the undisclosures.")); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AbstractOIDCScopeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AbstractOIDCScopeTest.java index cc1afda9df08..46c6fa7c8a68 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AbstractOIDCScopeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AbstractOIDCScopeTest.java @@ -25,7 +25,6 @@ import org.keycloak.representations.IDToken; import org.keycloak.representations.idm.EventRepresentation; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.pages.AppPage; import org.keycloak.testsuite.pages.ErrorPage; @@ -35,6 +34,7 @@ import org.jboss.arquillian.graphene.page.Page; import org.junit.Rule; +import org.junit.jupiter.api.Assertions; /** * @author Marek Posolda @@ -63,7 +63,7 @@ protected AbstractOIDCScopeTest.Tokens sendTokenRequest(EventRepresentation logi String code = oauth.parseLoginResponse().getCode(); AccessTokenResponse response = oauth.client(clientId, "password").doAccessTokenRequest(code); - Assert.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(200, response.getStatusCode()); // Test scopes log.info("expectedScopes = " + expectedScope); @@ -90,8 +90,8 @@ protected AbstractOIDCScopeTest.Tokens sendTokenRequest(EventRepresentation logi public static void assertScopes(String expectedScope, String receivedScope) { Collection expectedScopes = Arrays.asList(expectedScope.split(" ")); Collection receivedScopes = Arrays.asList(receivedScope.split(" ")); - Assert.assertTrue("Not matched. expectedScope: " + expectedScope + ", receivedScope: " + receivedScope, - expectedScopes.containsAll(receivedScopes) && receivedScopes.containsAll(expectedScopes)); + Assertions.assertTrue(expectedScopes.containsAll(receivedScopes) && receivedScopes.containsAll(expectedScopes), + "Not matched. expectedScope: " + expectedScope + ", receivedScope: " + receivedScope); } static class Tokens { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AbstractWellKnownProviderTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AbstractWellKnownProviderTest.java index bfbefdfe1f7c..bbafd251bb46 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AbstractWellKnownProviderTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AbstractWellKnownProviderTest.java @@ -75,6 +75,7 @@ import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import static jakarta.ws.rs.core.HttpHeaders.ACCEPT; @@ -82,8 +83,8 @@ import static org.keycloak.utils.MediaType.APPLICATION_JWKS; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public abstract class AbstractWellKnownProviderTest extends AbstractKeycloakTest { @@ -185,15 +186,15 @@ public void testDiscovery() { // Claims assertContains(oidcConfig.getClaimsSupported(), "iss", IDToken.SUBJECT, IDToken.AUD, "exp", "iat", IDToken.AUTH_TIME, IDToken.NAME, IDToken.GIVEN_NAME, IDToken.FAMILY_NAME, IDToken.PREFERRED_USERNAME, IDToken.EMAIL, IDToken.ACR, IDToken.AZP, "nonce"); Assert.assertNames(oidcConfig.getClaimTypesSupported(), "normal"); - Assert.assertTrue(oidcConfig.getClaimsParameterSupported()); + Assertions.assertTrue(oidcConfig.getClaimsParameterSupported()); // Scopes supported assertScopesSupportedMatchesWithRealm(oidcConfig); // Request and Request_Uri - Assert.assertTrue(oidcConfig.getRequestParameterSupported()); - Assert.assertTrue(oidcConfig.getRequestUriParameterSupported()); - Assert.assertTrue(oidcConfig.getRequireRequestUriRegistration()); + Assertions.assertTrue(oidcConfig.getRequestParameterSupported()); + Assertions.assertTrue(oidcConfig.getRequestUriParameterSupported()); + Assertions.assertTrue(oidcConfig.getRequireRequestUriRegistration()); // KEYCLOAK-7451 OAuth Authorization Server Metadata for Proof Key for Code Exchange // PKCE support @@ -201,10 +202,10 @@ public void testDiscovery() { // KEYCLOAK-6771 Certificate Bound Token // https://tools.ietf.org/html/draft-ietf-oauth-mtls-08#section-6.2 - Assert.assertTrue(oidcConfig.getTlsClientCertificateBoundAccessTokens()); + Assertions.assertTrue(oidcConfig.getTlsClientCertificateBoundAccessTokens()); MTLSEndpointAliases mtlsEndpointAliases = oidcConfig.getMtlsEndpointAliases(); - Assert.assertEquals(oidcConfig.getTokenEndpoint(), mtlsEndpointAliases.getTokenEndpoint()); - Assert.assertEquals(oidcConfig.getRevocationEndpoint(), mtlsEndpointAliases.getRevocationEndpoint()); + Assertions.assertEquals(oidcConfig.getTokenEndpoint(), mtlsEndpointAliases.getTokenEndpoint()); + Assertions.assertEquals(oidcConfig.getRevocationEndpoint(), mtlsEndpointAliases.getRevocationEndpoint()); // CIBA assertEquals(oidcConfig.getBackchannelAuthenticationEndpoint(), oauth.getEndpoints().getBackchannelAuthentication()); @@ -212,8 +213,8 @@ public void testDiscovery() { Assert.assertNames(oidcConfig.getBackchannelTokenDeliveryModesSupported(), "poll", "ping"); Assert.assertNames(oidcConfig.getBackchannelAuthenticationRequestSigningAlgValuesSupported(), Algorithm.PS256, Algorithm.PS384, Algorithm.PS512, Algorithm.RS256, Algorithm.RS384, Algorithm.RS512, Algorithm.ES256, Algorithm.ES384, Algorithm.ES512, Algorithm.EdDSA); - Assert.assertTrue(oidcConfig.getBackchannelLogoutSupported()); - Assert.assertTrue(oidcConfig.getBackchannelLogoutSessionSupported()); + Assertions.assertTrue(oidcConfig.getBackchannelLogoutSupported()); + Assertions.assertTrue(oidcConfig.getBackchannelLogoutSessionSupported()); // Token Revocation assertEquals(oidcConfig.getRevocationEndpoint(), oauth.getEndpoints().getRevocation()); @@ -243,12 +244,12 @@ public void testHttpDiscovery() { try { OIDCConfigurationRepresentation oidcConfig = getOIDCDiscoveryRepresentation(client, "http://localhost:8180/auth"); - Assert.assertNotNull(oidcConfig.getJwksUri()); + Assertions.assertNotNull(oidcConfig.getJwksUri()); // Token Revocation - Assert.assertNotNull(oidcConfig.getRevocationEndpoint()); - Assert.assertNotNull(oidcConfig.getRevocationEndpointAuthMethodsSupported()); - Assert.assertNotNull(oidcConfig.getRevocationEndpointAuthSigningAlgValuesSupported()); + Assertions.assertNotNull(oidcConfig.getRevocationEndpoint()); + Assertions.assertNotNull(oidcConfig.getRevocationEndpointAuthMethodsSupported()); + Assertions.assertNotNull(oidcConfig.getRevocationEndpointAuthSigningAlgValuesSupported()); } finally { client.close(); } @@ -482,7 +483,7 @@ private String getOIDCDiscoveryConfiguration(Client client, String uriTemplate) private void assertContains(List actual, String... expected) { for (String exp : expected) { - Assert.assertTrue(actual.contains(exp)); + Assertions.assertTrue(actual.contains(exp)); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AcrAuthFlowTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AcrAuthFlowTest.java index fd039e98f3bd..8cc47b6e89b5 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AcrAuthFlowTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AcrAuthFlowTest.java @@ -57,9 +57,9 @@ import org.jboss.arquillian.graphene.page.Page; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @author Giuseppe Graziano @@ -216,7 +216,7 @@ public void cleanupTest() { adminClient.realm(TEST_REALM_NAME).clientPoliciesProfilesResource().updateProfiles(clientProfilesRepresentation); } catch (Exception e) { - Assert.fail(); + Assertions.fail(); } } @@ -402,7 +402,7 @@ public static void setAcrClientPolicy(Keycloak adminClient, String realm, String adminClient.realm(realm).clientPoliciesPoliciesResource().updatePolicies(clientPolicies); } catch (Exception e) { - Assert.fail(); + Assertions.fail(); } } @@ -458,7 +458,7 @@ private void logout(String userId, Tokens tokens){ * @param password The password to log in with */ private void authenticatePassword(String username, String password){ - Assert.assertTrue(loginPage.isCurrent()); + Assertions.assertTrue(loginPage.isCurrent()); loginPage.login(username, password); } @@ -467,7 +467,7 @@ private void authenticatePassword(String username, String password){ * @param totpSecret The secret to use to generate the TOTP token */ private void authenticateTOTP(String totpSecret){ - Assert.assertTrue(loginTotpPage.isCurrent()); + Assertions.assertTrue(loginTotpPage.isCurrent()); setOtpTimeOffset(TimeBasedOTP.DEFAULT_INTERVAL_SECONDS, totp); loginTotpPage.login(totp.generateTOTP(totpSecret)); @@ -501,10 +501,10 @@ private void assertAcr(IDToken token, String expectedAcr) { String acr = token.getAcr(); getLogger().infof("Response acr = %s", acr); if (expectedAcr != null) { - Assert.assertNotNull(acr); + Assertions.assertNotNull(acr); } - Assert.assertEquals(acr, expectedAcr); + Assertions.assertEquals(acr, expectedAcr); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AudienceTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AudienceTest.java index 4180ddddd26b..8152b4b733d6 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AudienceTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AudienceTest.java @@ -35,7 +35,6 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.RoleRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.util.ProtocolMapperUtil; @@ -43,6 +42,7 @@ import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * Test for the 'aud' claim in tokens @@ -180,7 +180,7 @@ public void testAudienceProtocolMapperWithCustomAudience() throws Exception { private void assertAudiences(JsonWebToken token, String... expectedAudience) { Collection audiences = token.getAudience() == null ? Collections.emptyList() : Arrays.asList(token.getAudience()); Collection expectedAudiences = Arrays.asList(expectedAudience); - Assert.assertTrue("Not matched. expectedAudiences: " + expectedAudiences + ", audiences: " + audiences, - expectedAudiences.containsAll(audiences) && audiences.containsAll(expectedAudiences)); + Assertions.assertTrue(expectedAudiences.containsAll(audiences) && audiences.containsAll(expectedAudiences), + "Not matched. expectedAudiences: " + expectedAudiences + ", audiences: " + audiences); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AuthenticationMethodReferenceTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AuthenticationMethodReferenceTest.java index 96373c52452d..b36f9ac9e067 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AuthenticationMethodReferenceTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AuthenticationMethodReferenceTest.java @@ -43,7 +43,6 @@ import org.keycloak.representations.idm.ProtocolMapperRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.forms.LevelOfAssuranceFlowTest; import org.keycloak.testsuite.pages.LoginPage; import org.keycloak.testsuite.pages.LoginTotpPage; @@ -56,6 +55,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @author Ben Cresitello-Dittmar @@ -504,7 +504,7 @@ private void authenticatePassword(String username, String password){ * @param totpSecret The secret to use to generate the TOTP token */ private void authenticateTOTP(String totpSecret){ - org.junit.Assert.assertTrue(loginTotpPage.isCurrent()); + Assertions.assertTrue(loginTotpPage.isCurrent()); setOtpTimeOffset(TimeBasedOTP.DEFAULT_INTERVAL_SECONDS, totp); loginTotpPage.login(totp.generateTOTP(totpSecret)); @@ -531,17 +531,17 @@ private Tokens assertLogin(String userId){ private void assertAmr(IDToken token, List expectedValues) { getLogger().infof("Got claims %s", token.getOtherClaims().toString()); List amr = (List) token.getOtherClaims().get("amr"); - Assert.assertNotNull(amr); + Assertions.assertNotNull(amr); // sort otherwise order may be different Collections.sort(amr); Collections.sort(expectedValues); - Assert.assertArrayEquals(expectedValues.toArray(), amr.toArray()); + Assertions.assertArrayEquals(expectedValues.toArray(), amr.toArray()); } private void assertAcr(IDToken token, String acr){ - Assert.assertEquals(acr, token.getAcr()); + Assertions.assertEquals(acr, token.getAcr()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AuthorizationTokenEncryptionTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AuthorizationTokenEncryptionTest.java index 1f10678ea43b..98c106e41660 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AuthorizationTokenEncryptionTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AuthorizationTokenEncryptionTest.java @@ -41,7 +41,6 @@ import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected; @@ -59,6 +58,7 @@ import org.jboss.arquillian.graphene.page.Page; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; public class AuthorizationTokenEncryptionTest extends AbstractTestRealmKeycloakTest { @@ -191,7 +191,7 @@ private void testAuthorizationTokenSignatureAndEncryption(String sigAlgorithm, S // parse JWE and JOSE Header String jweStr = response.getResponse(); String[] parts = jweStr.split("\\."); - Assert.assertEquals(parts.length, 5); + Assertions.assertEquals(parts.length, 5); // get decryption key // not publickey , use privateKey @@ -206,15 +206,15 @@ private void testAuthorizationTokenSignatureAndEncryption(String sigAlgorithm, S // a nested JWT (signed and encrypted JWT) needs to set "JWT" to its JOSE Header's "cty" field JWEHeader jweHeader = (JWEHeader) getHeader(parts[0]); - Assert.assertEquals("JWT", jweHeader.getContentType()); + Assertions.assertEquals("JWT", jweHeader.getContentType()); // verify JWS AuthorizationResponseToken authorizationToken = oauth.verifyAuthorizationResponseToken(authorizationTokenString); - Assert.assertEquals("test-app", authorizationToken.getAudience()[0]); - Assert.assertEquals("OpenIdConnect.AuthenticationProperties=2302984sdlk", authorizationToken.getOtherClaims().get("state")); - Assert.assertNotNull(authorizationToken.getOtherClaims().get("code")); + Assertions.assertEquals("test-app", authorizationToken.getAudience()[0]); + Assertions.assertEquals("OpenIdConnect.AuthenticationProperties=2302984sdlk", authorizationToken.getOtherClaims().get("state")); + Assertions.assertNotNull(authorizationToken.getOtherClaims().get("code")); } catch (JWEException e) { - Assert.fail(); + Assertions.fail(); } finally { clientResource = AdminApiUtil.findClientByClientId(adminClient.realm("test"), "test-app"); clientRep = clientResource.toRepresentation(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AuthorizationTokenResponseModeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AuthorizationTokenResponseModeTest.java index d462b828ea2f..2c8439e7f072 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AuthorizationTokenResponseModeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/AuthorizationTokenResponseModeTest.java @@ -33,17 +33,17 @@ import org.keycloak.testsuite.util.ClientManager; import org.keycloak.testsuite.util.oauth.AuthorizationEndpointResponse; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public class AuthorizationTokenResponseModeTest extends AbstractTestRealmKeycloakTest { @@ -60,9 +60,9 @@ public void authorizationRequestQueryJWTResponseMode() throws Exception { AuthorizationResponseToken responseToken = oauth.verifyAuthorizationResponseToken(response.getResponse()); assertEquals("test-app", responseToken.getAudience()[0]); - Assert.assertNotNull(responseToken.getOtherClaims().get("code")); + Assertions.assertNotNull(responseToken.getOtherClaims().get("code")); assertEquals("OpenIdConnect.AuthenticationProperties=2302984sdlk", responseToken.getOtherClaims().get("state")); - Assert.assertNull(responseToken.getOtherClaims().get("error")); + Assertions.assertNull(responseToken.getOtherClaims().get("error")); String codeId = events.expectLogin().assertEvent().getDetails().get(Details.CODE_ID); } @@ -78,15 +78,15 @@ public void authorizationRequestJWTResponseMode() throws Exception { AuthorizationResponseToken responseToken = oauth.verifyAuthorizationResponseToken(response.getResponse()); assertEquals("test-app", responseToken.getAudience()[0]); - Assert.assertNotNull(responseToken.getOtherClaims().get("code")); + Assertions.assertNotNull(responseToken.getOtherClaims().get("code")); // should not return code when response_type not 'token' assertFalse(responseToken.getOtherClaims().containsKey(OAuth2Constants.SCOPE)); assertEquals("OpenIdConnect.AuthenticationProperties=2302984sdlk", responseToken.getOtherClaims().get("state")); - Assert.assertNull(responseToken.getOtherClaims().get("error")); + Assertions.assertNull(responseToken.getOtherClaims().get("error")); URI currentUri = new URI(driver.getCurrentUrl()); - Assert.assertNotNull(currentUri.getRawQuery()); - Assert.assertNull(currentUri.getRawFragment()); + Assertions.assertNotNull(currentUri.getRawQuery()); + Assertions.assertNull(currentUri.getRawFragment()); String codeId = events.expectLogin().assertEvent().getDetails().get(Details.CODE_ID); } @@ -101,13 +101,13 @@ public void authorizationRequestFragmentJWTResponseMode() throws Exception { AuthorizationResponseToken responseToken = oauth.verifyAuthorizationResponseToken(response.getResponse()); assertEquals("test-app", responseToken.getAudience()[0]); - Assert.assertNotNull(responseToken.getOtherClaims().get("code")); + Assertions.assertNotNull(responseToken.getOtherClaims().get("code")); assertEquals("OpenIdConnect.AuthenticationProperties=2302984sdlk", responseToken.getOtherClaims().get("state")); - Assert.assertNull(responseToken.getOtherClaims().get("error")); + Assertions.assertNull(responseToken.getOtherClaims().get("error")); URI currentUri = new URI(driver.getCurrentUrl()); - Assert.assertNull(currentUri.getRawQuery()); - Assert.assertNotNull(currentUri.getRawFragment()); + Assertions.assertNull(currentUri.getRawQuery()); + Assertions.assertNotNull(currentUri.getRawFragment()); String codeId = events.expectLogin().assertEvent().getDetails().get(Details.CODE_ID); } @@ -125,9 +125,9 @@ public void authorizationRequestFormPostJWTResponseMode() throws IOException { AuthorizationResponseToken responseToken = oauth.verifyAuthorizationResponseToken(responseTokenEncoded); assertEquals("test-app", responseToken.getAudience()[0]); - Assert.assertNotNull(responseToken.getOtherClaims().get("code")); + Assertions.assertNotNull(responseToken.getOtherClaims().get("code")); assertEquals("OpenIdConnect.AuthenticationProperties=2302984sdlk", responseToken.getOtherClaims().get("state")); - Assert.assertNull(responseToken.getOtherClaims().get("error")); + Assertions.assertNull(responseToken.getOtherClaims().get("error")); String codeId = events.expectLogin().assertEvent().getDetails().get(Details.CODE_ID); } @@ -145,18 +145,18 @@ public void authorizationRequestJWTResponseModeIdTokenResponseType() throws Exce AuthorizationResponseToken responseToken = oauth.verifyAuthorizationResponseToken(response.getResponse()); assertEquals("test-app", responseToken.getAudience()[0]); - Assert.assertNotNull(responseToken.getOtherClaims().get("code")); + Assertions.assertNotNull(responseToken.getOtherClaims().get("code")); assertEquals("OpenIdConnect.AuthenticationProperties=2302984sdlk", responseToken.getOtherClaims().get("state")); - Assert.assertNull(responseToken.getOtherClaims().get("error")); + Assertions.assertNull(responseToken.getOtherClaims().get("error")); - Assert.assertNotNull(responseToken.getOtherClaims().get("id_token")); + Assertions.assertNotNull(responseToken.getOtherClaims().get("id_token")); String idTokenEncoded = (String) responseToken.getOtherClaims().get("id_token"); IDToken idToken = oauth.verifyIDToken(idTokenEncoded); assertEquals("123456", idToken.getNonce()); URI currentUri = new URI(driver.getCurrentUrl()); - Assert.assertNull(currentUri.getRawQuery()); - Assert.assertNotNull(currentUri.getRawFragment()); + Assertions.assertNull(currentUri.getRawQuery()); + Assertions.assertNotNull(currentUri.getRawFragment()); String codeId = events.expectLogin().assertEvent().getDetails().get(Details.CODE_ID); } @@ -174,23 +174,23 @@ public void authorizationRequestJWTResponseModeAccessTokenResponseType() throws AuthorizationResponseToken responseToken = oauth.verifyAuthorizationResponseToken(response.getResponse()); assertEquals("test-app", responseToken.getAudience()[0]); - Assert.assertNull(responseToken.getOtherClaims().get("code")); + Assertions.assertNull(responseToken.getOtherClaims().get("code")); assertEquals("OpenIdConnect.AuthenticationProperties=2302984sdlk", responseToken.getOtherClaims().get("state")); - Assert.assertNull(responseToken.getOtherClaims().get("error")); + Assertions.assertNull(responseToken.getOtherClaims().get("error")); - Assert.assertNotNull(responseToken.getOtherClaims().get("id_token")); + Assertions.assertNotNull(responseToken.getOtherClaims().get("id_token")); String idTokenEncoded = (String) responseToken.getOtherClaims().get("id_token"); IDToken idToken = oauth.verifyIDToken(idTokenEncoded); assertEquals("123456", idToken.getNonce()); - Assert.assertNotNull(responseToken.getOtherClaims().get("access_token")); + Assertions.assertNotNull(responseToken.getOtherClaims().get("access_token")); String accessTokenEncoded = (String) responseToken.getOtherClaims().get("access_token"); AccessToken accessToken = oauth.verifyToken(accessTokenEncoded); assertNull(accessToken.getNonce()); URI currentUri = new URI(driver.getCurrentUrl()); - Assert.assertNull(currentUri.getRawQuery()); - Assert.assertNotNull(currentUri.getRawFragment()); + Assertions.assertNull(currentUri.getRawQuery()); + Assertions.assertNotNull(currentUri.getRawFragment()); } @Test @@ -202,8 +202,8 @@ public void authorizationRequestFailInvalidResponseModeQueryJWT() throws Excepti AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); AuthorizationResponseToken responseToken = oauth.verifyAuthorizationResponseToken(errorResponse.getResponse()); - Assert.assertEquals(OAuthErrorException.INVALID_REQUEST, responseToken.getOtherClaims().get("error")); - Assert.assertEquals("Response_mode 'query.jwt' is allowed only when the authorization response token is encrypted", responseToken.getOtherClaims().get("error_description")); + Assertions.assertEquals(OAuthErrorException.INVALID_REQUEST, responseToken.getOtherClaims().get("error")); + Assertions.assertEquals("Response_mode 'query.jwt' is allowed only when the authorization response token is encrypted", responseToken.getOtherClaims().get("error_description")); events.expectLogin().error(Errors.INVALID_REQUEST).user((String) null).session((String) null).clearDetails().assertEvent(); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/IdTokenEncryptionTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/IdTokenEncryptionTest.java index fd94ff7f0aae..8dac81836ee6 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/IdTokenEncryptionTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/IdTokenEncryptionTest.java @@ -42,7 +42,6 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.AbstractAdminTest; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected; @@ -63,6 +62,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; public class IdTokenEncryptionTest extends AbstractTestRealmKeycloakTest { @@ -219,7 +219,7 @@ private void testIdTokenSignatureAndEncryption(String sigAlgorithm, String algAl // parse JWE and JOSE Header String jweStr = tokenResponse.getIdToken(); String[] parts = jweStr.split("\\."); - Assert.assertEquals(parts.length, 5); + Assertions.assertEquals(parts.length, 5); // get decryption key // not publickey , use privateKey @@ -228,7 +228,7 @@ private void testIdTokenSignatureAndEncryption(String sigAlgorithm, String algAl // a nested JWT (signed and encrypted JWT) needs to set "JWT" to its JOSE Header's "cty" field JWEHeader jweHeader = (JWEHeader) getHeader(parts[0]); - Assert.assertEquals("JWT", jweHeader.getContentType()); + Assertions.assertEquals("JWT", jweHeader.getContentType()); // verify and decrypt JWE if (encAlgorithm == null) encAlgorithm = JWEConstants.A128CBC_HS256; @@ -239,10 +239,10 @@ private void testIdTokenSignatureAndEncryption(String sigAlgorithm, String algAl // verify JWS IDToken idToken = oauth.verifyIDToken(idTokenString); - Assert.assertEquals("test-user@localhost", idToken.getPreferredUsername()); - Assert.assertEquals("test-app", idToken.getIssuedFor()); + Assertions.assertEquals("test-user@localhost", idToken.getPreferredUsername()); + Assertions.assertEquals("test-app", idToken.getIssuedFor()); } catch (JWEException e) { - Assert.fail(); + Assertions.fail(); } finally { clientResource = AdminApiUtil.findClientByClientId(adminClient.realm("test"), "test-app"); clientRep = clientResource.toRepresentation(); @@ -311,14 +311,14 @@ public void testIdTokenEncryptionWithoutEncryptionKEK() throws Exception{ // get id token but failed AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password"); AccessTokenResponse atr = oauth.doAccessTokenRequest(response.getCode()); - Assert.assertEquals(OAuthErrorException.INVALID_REQUEST, atr.getError()); - Assert.assertEquals("can not get encryption KEK", atr.getErrorDescription()); + Assertions.assertEquals(OAuthErrorException.INVALID_REQUEST, atr.getError()); + Assertions.assertEquals("can not get encryption KEK", atr.getErrorDescription()); // get id token but failed with client_credentials grant type oauth.scope("openid"); AccessTokenResponse responseClientCredentials = oauth.client(clientRep.getClientId(), clientRep.getSecret()).doClientCredentialsGrantAccessTokenRequest(); - Assert.assertEquals(OAuthErrorException.INVALID_REQUEST, responseClientCredentials.getError()); - Assert.assertEquals("can not get encryption KEK", responseClientCredentials.getErrorDescription()); + Assertions.assertEquals(OAuthErrorException.INVALID_REQUEST, responseClientCredentials.getError()); + Assertions.assertEquals("can not get encryption KEK", responseClientCredentials.getErrorDescription()); } finally { // Revert clientResource = AdminApiUtil.findClientByClientId(adminClient.realm("test"), "test-app"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/LightWeightAccessTokenTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/LightWeightAccessTokenTest.java index e45e09521ca0..f75ee6524e2b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/LightWeightAccessTokenTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/LightWeightAccessTokenTest.java @@ -80,9 +80,9 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.jboss.logging.Logger; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.protocol.ProtocolMapperUtils.USER_SESSION_NOTE; import static org.keycloak.protocol.oidc.OIDCLoginProtocolFactory.ACR; @@ -228,7 +228,7 @@ public void accessTokenTrueIntrospectionReturnedAsJwt() throws IOException { AccessToken introspectionResult = JsonSerialization.readValue(tokenResponse, AccessToken.class); assertTokenIntrospectionResponse(introspectionResult, true, true, false); - Assert.assertNotNull(introspectionResult.getOtherClaims().get("jwt")); + Assertions.assertNotNull(introspectionResult.getOtherClaims().get("jwt")); } finally { deleteProtocolMappers(protocolMappers); } @@ -355,9 +355,9 @@ public void testPolicyLightWeightTrueTest() throws Exception { assertAccessToken(token, true, true, true); AccessTokenContext ctx = testingClient.testing("test").getTokenContext(token.getId()); - Assert.assertEquals(ctx.getSessionType(), AccessTokenContext.SessionType.ONLINE); - Assert.assertEquals(ctx.getTokenType(), AccessTokenContext.TokenType.LIGHTWEIGHT); - Assert.assertEquals(ctx.getGrantType(), OAuth2Constants.AUTHORIZATION_CODE); + Assertions.assertEquals(ctx.getSessionType(), AccessTokenContext.SessionType.ONLINE); + Assertions.assertEquals(ctx.getTokenType(), AccessTokenContext.TokenType.LIGHTWEIGHT); + Assertions.assertEquals(ctx.getGrantType(), OAuth2Constants.AUTHORIZATION_CODE); oauth.client(RESOURCE_SERVER_CLIENT_ID, RESOURCE_SERVER_CLIENT_PASSWORD); String introspectResponse = oauth.doIntrospectionAccessTokenRequest(accessToken).getRaw(); @@ -511,12 +511,12 @@ public void testAdminConsoleClientWithLightweightAccessToken() { HttpGet get = new HttpGet(OAuthClient.SERVER_ROOT + "/auth/admin/realms/master"); get.setHeader("Authorization", "Bearer " + accessToken); try (CloseableHttpResponse response = client.execute(get)) { - Assert.assertEquals(200, response.getStatusLine().getStatusCode()); + Assertions.assertEquals(200, response.getStatusLine().getStatusCode()); RealmRepresentation realmRepresentation = JsonSerialization.readValue(response.getEntity().getContent(), RealmRepresentation.class); - Assert.assertEquals("master", realmRepresentation.getRealm()); + Assertions.assertEquals("master", realmRepresentation.getRealm()); } } catch (Exception e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } } @@ -537,7 +537,7 @@ public void testAdminConsoleClientWithLightweightAccessTokenTransientSessionDyna post.setHeader("Authorization", "Bearer " + accessToken); post.setEntity(new StringEntity("{\"realm\":\"invalid\",\"enabled\":true}", ContentType.APPLICATION_JSON)); try (CloseableHttpResponse resp = client.execute(post)) { - Assert.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), resp.getStatusLine().getStatusCode()); + Assertions.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), resp.getStatusLine().getStatusCode()); } } } @@ -560,21 +560,21 @@ public void testAdminApiWithLightweightAccessTokenAndTransientSession() { oauth.client(transientClient.getClientId(), transientClient.getSecret()); AccessTokenResponse tokenResponse = oauth.doClientCredentialsGrantAccessTokenRequest(); String accessTokenString = tokenResponse.getAccessToken(); - Assert.assertNull(tokenResponse.getRefreshToken()); + Assertions.assertNull(tokenResponse.getRefreshToken()); AccessToken accessToken = oauth.verifyToken(accessTokenString); - Assert.assertNotNull(accessToken.getSubject()); - Assert.assertNull(accessToken.getSessionId()); + Assertions.assertNotNull(accessToken.getSubject()); + Assertions.assertNull(accessToken.getSessionId()); CloseableHttpClient client = HttpClientBuilder.create().build(); HttpGet get = new HttpGet(OAuthClient.SERVER_ROOT + "/auth/admin/realms/master"); get.setHeader("Authorization", "Bearer " + accessTokenString); CloseableHttpResponse response = client.execute(get); - Assert.assertEquals(200, response.getStatusLine().getStatusCode()); + Assertions.assertEquals(200, response.getStatusLine().getStatusCode()); RealmRepresentation realmRepresentation = JsonSerialization.readValue(response.getEntity().getContent(), RealmRepresentation.class); - Assert.assertEquals("master", realmRepresentation.getRealm()); + Assertions.assertEquals("master", realmRepresentation.getRealm()); } catch (Exception e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } } @@ -598,12 +598,12 @@ public void testAdminApiWithLightweightAccessAndSubClaim() { HttpGet get = new HttpGet(OAuthClient.SERVER_ROOT + "/auth/admin/realms/master"); get.setHeader("Authorization", "Bearer " + accessToken); try (CloseableHttpResponse response = client.execute(get)) { - Assert.assertEquals(200, response.getStatusLine().getStatusCode()); + Assertions.assertEquals(200, response.getStatusLine().getStatusCode()); RealmRepresentation realmRepresentation = JsonSerialization.readValue(response.getEntity().getContent(), RealmRepresentation.class); - Assert.assertEquals("master", realmRepresentation.getRealm()); + Assertions.assertEquals("master", realmRepresentation.getRealm()); } } catch (Exception e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } setScopeProtocolMapper("master", OIDCLoginProtocolFactory.BASIC_SCOPE, "sub", true, false, false); @@ -642,8 +642,8 @@ public void testPublicClientWithLightweightAccessTokenViaDirectGrant() throws Ex // Verify lightweight token AccessToken token = oauth.verifyToken(response.getAccessToken()); AccessTokenContext ctx = testingClient.testing(REALM_NAME).getTokenContext(token.getId()); - Assert.assertEquals(AccessTokenContext.TokenType.LIGHTWEIGHT, ctx.getTokenType()); - Assert.assertEquals(TEST_USER_PASSWORD, ctx.getGrantType()); + Assertions.assertEquals(AccessTokenContext.TokenType.LIGHTWEIGHT, ctx.getTokenType()); + Assertions.assertEquals(TEST_USER_PASSWORD, ctx.getGrantType()); } private void removeSession(final String sessionId) { @@ -658,88 +658,88 @@ private void removeSession(final String sessionId) { private void assertMapperClaims(AccessToken token, boolean isAddMapperResponseFlag, boolean isAuthCodeFlow) { if (isAddMapperResponseFlag) { if (isAuthCodeFlow) { - Assert.assertNotNull(token.getName()); - Assert.assertNotNull(token.getGivenName()); - Assert.assertNotNull(token.getFamilyName()); - Assert.assertNotNull(token.getAddress()); - Assert.assertNotNull(token.getEmail()); - Assert.assertNotNull(token.getOtherClaims().get("user-session-note")); - Assert.assertNotNull(token.getOtherClaims().get("test-claim")); - Assert.assertNotNull(token.getOtherClaims().get("group-name")); - Assert.assertNotNull(token.getOtherClaims().get(IDToken.SESSION_STATE)); + Assertions.assertNotNull(token.getName()); + Assertions.assertNotNull(token.getGivenName()); + Assertions.assertNotNull(token.getFamilyName()); + Assertions.assertNotNull(token.getAddress()); + Assertions.assertNotNull(token.getEmail()); + Assertions.assertNotNull(token.getOtherClaims().get("user-session-note")); + Assertions.assertNotNull(token.getOtherClaims().get("test-claim")); + Assertions.assertNotNull(token.getOtherClaims().get("group-name")); + Assertions.assertNotNull(token.getOtherClaims().get(IDToken.SESSION_STATE)); } - Assert.assertNotNull(token.getAudience()); - Assert.assertNotNull(token.getAcr()); - Assert.assertNotNull(token.getAllowedOrigins()); - Assert.assertNotNull(token.getRealmAccess()); - Assert.assertNotNull(token.getResourceAccess()); - Assert.assertNotNull(token.getEmailVerified()); - Assert.assertNotNull(token.getPreferredUsername()); + Assertions.assertNotNull(token.getAudience()); + Assertions.assertNotNull(token.getAcr()); + Assertions.assertNotNull(token.getAllowedOrigins()); + Assertions.assertNotNull(token.getRealmAccess()); + Assertions.assertNotNull(token.getResourceAccess()); + Assertions.assertNotNull(token.getEmailVerified()); + Assertions.assertNotNull(token.getPreferredUsername()); } else { if (isAuthCodeFlow) { - Assert.assertNull(token.getName()); - Assert.assertNull(token.getGivenName()); - Assert.assertNull(token.getFamilyName()); - Assert.assertNull(token.getAddress()); - Assert.assertNull(token.getEmail()); - Assert.assertNull(token.getOtherClaims().get("user-session-note")); - Assert.assertNull(token.getOtherClaims().get("test-claim")); - Assert.assertNull(token.getOtherClaims().get("group-name")); - Assert.assertNull(token.getOtherClaims().get(IDToken.SESSION_STATE)); + Assertions.assertNull(token.getName()); + Assertions.assertNull(token.getGivenName()); + Assertions.assertNull(token.getFamilyName()); + Assertions.assertNull(token.getAddress()); + Assertions.assertNull(token.getEmail()); + Assertions.assertNull(token.getOtherClaims().get("user-session-note")); + Assertions.assertNull(token.getOtherClaims().get("test-claim")); + Assertions.assertNull(token.getOtherClaims().get("group-name")); + Assertions.assertNull(token.getOtherClaims().get(IDToken.SESSION_STATE)); } - Assert.assertNull(token.getAcr()); - Assert.assertNull(token.getAllowedOrigins()); - Assert.assertNull(token.getRealmAccess()); - Assert.assertTrue(token.getResourceAccess().isEmpty()); - Assert.assertNull(token.getEmailVerified()); - Assert.assertNull(token.getPreferredUsername()); + Assertions.assertNull(token.getAcr()); + Assertions.assertNull(token.getAllowedOrigins()); + Assertions.assertNull(token.getRealmAccess()); + Assertions.assertTrue(token.getResourceAccess().isEmpty()); + Assertions.assertNull(token.getEmailVerified()); + Assertions.assertNull(token.getPreferredUsername()); } } private void assertInitClaims(AccessToken token, boolean isAuthCodeFlow) { - Assert.assertNotNull(token.getExp()); - Assert.assertNotNull(token.getIat()); - Assert.assertNotNull(token.getId()); - Assert.assertNotNull(token.getType()); - Assert.assertNotNull(token.getIssuedFor()); - Assert.assertNotNull(token.getScope()); - Assert.assertNotNull(token.getIssuer()); + Assertions.assertNotNull(token.getExp()); + Assertions.assertNotNull(token.getIat()); + Assertions.assertNotNull(token.getId()); + Assertions.assertNotNull(token.getType()); + Assertions.assertNotNull(token.getIssuedFor()); + Assertions.assertNotNull(token.getScope()); + Assertions.assertNotNull(token.getIssuer()); if (isAuthCodeFlow) { - Assert.assertNotNull(token.getSessionId()); + Assertions.assertNotNull(token.getSessionId()); } else { - Assert.assertNull(token.getSessionId()); + Assertions.assertNull(token.getSessionId()); } } private void assertBasicClaims(AccessToken token, boolean isAuthCodeFlow, boolean missing) { if (missing) { - Assert.assertNull(token.getAuth_time()); - Assert.assertNull(token.getSubject()); + Assertions.assertNull(token.getAuth_time()); + Assertions.assertNull(token.getSubject()); } else { - Assert.assertNotNull(token.getSubject()); + Assertions.assertNotNull(token.getSubject()); if (isAuthCodeFlow) { - Assert.assertNotNull(token.getAuth_time()); + Assertions.assertNotNull(token.getAuth_time()); } else { - Assert.assertNull(token.getAuth_time()); + Assertions.assertNull(token.getAuth_time()); } } } private void assertIntrospectClaims(AccessToken token) { - Assert.assertNotNull(token.getOtherClaims().get("client_id")); - Assert.assertNotNull(token.getOtherClaims().get("active")); - Assert.assertNotNull(token.getOtherClaims().get("token_type")); + Assertions.assertNotNull(token.getOtherClaims().get("client_id")); + Assertions.assertNotNull(token.getOtherClaims().get("active")); + Assertions.assertNotNull(token.getOtherClaims().get("token_type")); } private void assertAccessToken(AccessToken token, boolean isAuthCodeFlow, boolean isAddToAccessToken, boolean missingBasicClaims) { - Assert.assertNull(token.getNonce()); + Assertions.assertNull(token.getNonce()); assertMapperClaims(token, isAddToAccessToken, isAuthCodeFlow); assertInitClaims(token, isAuthCodeFlow); assertBasicClaims(token, isAuthCodeFlow, missingBasicClaims); } private void assertTokenIntrospectionResponse(AccessToken token, boolean isAuthCodeFlow, boolean isAddToIntrospect, boolean missingBasicClaims) { - Assert.assertNull(token.getNonce()); + Assertions.assertNull(token.getNonce()); assertMapperClaims(token, isAddToIntrospect, isAuthCodeFlow); assertInitClaims(token, isAuthCodeFlow); assertIntrospectClaims(token); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/NonceBackwardsCompatibleMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/NonceBackwardsCompatibleMapperTest.java index 47aa347407da..3aa9a3446f86 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/NonceBackwardsCompatibleMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/NonceBackwardsCompatibleMapperTest.java @@ -48,9 +48,9 @@ import org.keycloak.util.TokenUtil; import com.fasterxml.jackson.databind.JsonNode; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @@ -118,16 +118,16 @@ private String createNonceMapper(ClientResource testApp) { ProtocolMapperModel nonceMapper = NonceBackwardsCompatibleMapper.create("nonce"); ProtocolMapperRepresentation nonceMapperRep = ModelToRepresentation.toRepresentation(nonceMapper); try (Response res = testApp.getProtocolMappers().createMapper(nonceMapperRep)) { - Assert.assertEquals(Response.Status.CREATED.getStatusCode(), res.getStatus()); + Assertions.assertEquals(Response.Status.CREATED.getStatusCode(), res.getStatus()); return ApiUtil.getCreatedId(res); } } private void checkNonce(String expectedNonce, String nonce, boolean expected) { if (expected) { - Assert.assertEquals(expectedNonce, nonce); + Assertions.assertEquals(expectedNonce, nonce); } else { - Assert.assertNull(nonce); + Assertions.assertNull(nonce); } } @@ -142,7 +142,7 @@ private void testNonceImplicit(boolean mapper) throws IOException { oauth.responseType(OIDCResponseType.TOKEN + " " + OIDCResponseType.ID_TOKEN); AuthorizationEndpointResponse response = oauth.loginForm().nonce(nonce).doLogin("test-user@localhost", "password"); - Assert.assertTrue(response.isRedirected()); + Assertions.assertTrue(response.isRedirected()); AuthorizationResponseToken responseToken = oauth.verifyAuthorizationResponseToken(response.getResponse()); String accessTokenString = (String) responseToken.getOtherClaims().get("access_token"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCAdvancedRequestParamsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCAdvancedRequestParamsTest.java index c1520b620277..0976851f3fde 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCAdvancedRequestParamsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCAdvancedRequestParamsTest.java @@ -73,7 +73,6 @@ import org.keycloak.services.util.CertificateInfoHelper; import org.keycloak.testsuite.AbstractAdminTest; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.broker.util.SimpleHttpDefault; @@ -101,6 +100,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.jose.jwe.JWEConstants.RSA_OAEP; import static org.keycloak.jose.jwe.JWEConstants.RSA_OAEP_256; @@ -108,11 +108,11 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Test for supporting advanced parameters of OIDC specs (max_age, prompt, ...) @@ -212,7 +212,7 @@ public void testMaxAge1() { // Check that authTime is available and set to current time long authTime = idToken.getAuth_time(); long currentTime = Time.currentTime(); - Assert.assertTrue(authTime <= currentTime && authTime + 3 >= currentTime); + Assertions.assertTrue(authTime <= currentTime && authTime + 3 >= currentTime); // Set time offset setTimeOffset(10); @@ -228,7 +228,7 @@ public void testMaxAge1() { // Assert that authTime was updated long authTimeUpdated = idToken.getAuth_time(); - Assert.assertTrue(authTime + 10 <= authTimeUpdated); + Assertions.assertTrue(authTime + 10 <= authTimeUpdated); } @Test @@ -242,7 +242,7 @@ public void testMaxAge10000() { // Check that authTime is available and set to current time long authTime = idToken.getAuth_time(); long currentTime = Time.currentTime(); - Assert.assertTrue(authTime <= currentTime && authTime + 3 >= currentTime); + Assertions.assertTrue(authTime <= currentTime && authTime + 3 >= currentTime); // Set time offset setTimeOffset(10); @@ -257,7 +257,7 @@ public void testMaxAge10000() { // Assert that authTime is still the same long authTimeUpdated = idToken.getAuth_time(); - Assert.assertEquals(authTime, authTimeUpdated); + Assertions.assertEquals(authTime, authTimeUpdated); } @@ -278,9 +278,9 @@ public void promptNoneNotLogged() { // Assert error response was sent because not logged in AuthorizationEndpointResponse resp = oauth.parseLoginResponse(); - Assert.assertEquals(expectedIssuer, resp.getIssuer()); - Assert.assertNull(resp.getCode()); - Assert.assertEquals(OAuthErrorException.LOGIN_REQUIRED, resp.getError()); + Assertions.assertEquals(expectedIssuer, resp.getIssuer()); + Assertions.assertNull(resp.getCode()); + Assertions.assertEquals(OAuthErrorException.LOGIN_REQUIRED, resp.getError()); } @@ -290,7 +290,7 @@ public void promptNoneSuccess() { // Login user oauth.openLoginForm(); loginPage.login("test-user@localhost", "password"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); EventRepresentation loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent(); IDToken idToken = sendTokenRequestAndGetIDToken(loginEvent); @@ -301,13 +301,13 @@ public void promptNoneSuccess() { // Assert user still logged with previous authTime oauth.loginForm().prompt("none").open(); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); loginEvent = events.expectLogin().removeDetail(Details.USERNAME).assertEvent(); idToken = sendTokenRequestAndGetIDToken(loginEvent); long authTime2 = idToken.getAuth_time(); - Assert.assertEquals(authTime, authTime2); + Assertions.assertEquals(authTime, authTime2); } @@ -321,11 +321,11 @@ public void promptNoneConsentRequired() { // Assert error shown when trying prompt=none and consent not yet granted oauth.loginForm().prompt("none").open(); assertTrue(appPage.isCurrent()); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); AuthorizationEndpointResponse resp = oauth.parseLoginResponse(); - Assert.assertNull(resp.getCode()); - Assert.assertEquals(OAuthErrorException.LOGIN_REQUIRED, resp.getError()); + Assertions.assertNull(resp.getCode()); + Assertions.assertEquals(OAuthErrorException.LOGIN_REQUIRED, resp.getError()); // Login and confirm consent oauth.openLoginForm(); @@ -341,11 +341,11 @@ public void promptNoneConsentRequired() { // Consent not required anymore. Login with prompt=none should success oauth.loginForm().prompt("none").open(); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); resp = oauth.parseLoginResponse(); - Assert.assertNotNull(resp.getCode()); - Assert.assertNull(resp.getError()); + Assertions.assertNotNull(resp.getCode()); + Assertions.assertNull(resp.getError()); events.expectLogin() .detail(Details.USERNAME, "test-user@localhost") @@ -369,7 +369,7 @@ public void promptLogin() { // Login user oauth.openLoginForm(); loginPage.login("test-user@localhost", "password"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); EventRepresentation loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent(); IDToken oldIdToken = sendTokenRequestAndGetIDToken(loginEvent); @@ -379,12 +379,12 @@ public void promptLogin() { // SSO login first WITHOUT prompt=login ( Tests KEYCLOAK-5248 ) oauth.openLoginForm(); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent(); IDToken newIdToken = sendTokenRequestAndGetIDToken(loginEvent); // Assert that authTime wasn't updated - Assert.assertEquals(oldIdToken.getAuth_time(), newIdToken.getAuth_time()); + Assertions.assertEquals(oldIdToken.getAuth_time(), newIdToken.getAuth_time()); // Set time offset setTimeOffset(20); @@ -394,17 +394,17 @@ public void promptLogin() { loginPage.assertCurrent(); assertThat(false, is(loginPage.isUsernameInputPresent())); loginPage.login("password"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent(); newIdToken = sendTokenRequestAndGetIDToken(loginEvent); // Assert that authTime was updated - Assert.assertTrue("Expected auth time to change. old auth time: " + oldIdToken.getAuth_time() + " , new auth time: " + newIdToken.getAuth_time(), - oldIdToken.getAuth_time() + 20 <= newIdToken.getAuth_time()); + Assertions.assertTrue(oldIdToken.getAuth_time() + 20 <= newIdToken.getAuth_time(), + "Expected auth time to change. old auth time: " + oldIdToken.getAuth_time() + " , new auth time: " + newIdToken.getAuth_time()); // Assert userSession didn't change - Assert.assertEquals(oldIdToken.getSessionState(), newIdToken.getSessionState()); + Assertions.assertEquals(oldIdToken.getSessionState(), newIdToken.getSessionState()); } // prompt=create @@ -452,7 +452,7 @@ public void promptConsent() { grantPage.accept(); appPage.assertCurrent(); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin() .detail(Details.USERNAME, "test-user@localhost") @@ -462,7 +462,7 @@ public void promptConsent() { // Re-login without prompt=consent. The previous persistent consent was used oauth.openLoginForm(); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin() .detail(Details.USERNAME, "test-user@localhost") .detail(Details.CONSENT, Details.CONSENT_VALUE_PERSISTED_CONSENT) @@ -478,7 +478,7 @@ public void promptConsent() { grantPage.accept(); appPage.assertCurrent(); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin() .detail(Details.USERNAME, "test-user@localhost") @@ -502,12 +502,12 @@ public void nonSupportedParams() { loginPage.assertCurrent(); loginPage.login("test-user@localhost", "password"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); EventRepresentation loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent(); IDToken idToken = sendTokenRequestAndGetIDToken(loginEvent); - Assert.assertNotNull(idToken); + Assertions.assertNotNull(idToken); } // REQUEST & REQUEST_URI @@ -522,8 +522,8 @@ public void requestObjectNotRequiredNotProvided() { // Send request without request object // Assert that the request is accepted AuthorizationEndpointResponse response = oauth.loginForm().state("mystate2").doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response.getCode()); - Assert.assertEquals("mystate2", response.getState()); + Assertions.assertNotNull(response.getCode()); + Assertions.assertEquals("mystate2", response.getState()); assertTrue(appPage.isCurrent()); } @@ -541,8 +541,8 @@ public void requestObjectNotRequiredProvidedInRequestParam() { // Assert that the request is accepted AuthorizationEndpointResponse response1 = oauth.loginForm().request(oidcClientEndpointsResource.getOIDCRequest()).state("mystate2").doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response1.getCode()); - Assert.assertEquals("mystate2", response1.getState()); + Assertions.assertNotNull(response1.getCode()); + Assertions.assertEquals("mystate2", response1.getState()); assertTrue(appPage.isCurrent()); } @@ -560,8 +560,8 @@ public void requestObjectNotRequiredProvidedInRequestUriParam() { // Assert that the request is accepted AuthorizationEndpointResponse response2 = oauth.loginForm().requestUri(TestApplicationResourceUrls.clientRequestUri()).state("mystate2").doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response2.getCode()); - Assert.assertEquals("mystate2", response2.getState()); + Assertions.assertNotNull(response2.getCode()); + Assertions.assertEquals("mystate2", response2.getState()); assertTrue(appPage.isCurrent()); } @@ -576,7 +576,7 @@ public void requestObjectRequiredNotProvided() { // Send request without request object // Assert that the request is not accepted oauth.loginForm().state("mystate2").open(); - Assert.assertTrue(errorPage.isCurrent()); + Assertions.assertTrue(errorPage.isCurrent()); assertEquals("Invalid Request", errorPage.getError()); // Revert requiring request object for client @@ -598,8 +598,8 @@ public void requestObjectRequiredProvidedInRequestParam() { // Assert that the request is accepted AuthorizationEndpointResponse response1 = oauth.loginForm().request(oidcClientEndpointsResource.getOIDCRequest()).state("mystate2").doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response1.getCode()); - Assert.assertEquals("mystate2", response1.getState()); + Assertions.assertNotNull(response1.getCode()); + Assertions.assertEquals("mystate2", response1.getState()); assertTrue(appPage.isCurrent()); // Revert requiring request object for client @@ -624,8 +624,8 @@ public void requestObjectSupersedesQueryParameter() { // Assert that the request is accepted AuthorizationEndpointResponse response1 = oauth.loginForm().request(oidcClientEndpointsResource.getOIDCRequest()).state(stateInQueryParameter).doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response1.getCode()); - Assert.assertEquals(stateInRequestObject, response1.getState()); + Assertions.assertNotNull(response1.getCode()); + Assertions.assertEquals(stateInRequestObject, response1.getState()); assertTrue(appPage.isCurrent()); // Revert requiring request object for client @@ -649,8 +649,8 @@ public void requestObjectClientIdAndResponseTypeTest() { oauth.loginForm().request(request).state("some-state").open(); appPage.assertCurrent(); AuthorizationEndpointResponse authorizationEndpointResponse = oauth.parseLoginResponse(); - Assert.assertEquals("invalid_request", authorizationEndpointResponse.getError()); - Assert.assertEquals("some-state", authorizationEndpointResponse.getState()); + Assertions.assertEquals("invalid_request", authorizationEndpointResponse.getError()); + Assertions.assertEquals("some-state", authorizationEndpointResponse.getState()); // Test that different "client_id" in the query and in the request object is disallowed oauth.clientId("test-app-scope"); @@ -666,8 +666,8 @@ public void requestObjectClientIdAndResponseTypeTest() { oauth.responseMode("query"); // Keycloak falls back to query in this case authorizationEndpointResponse = oauth.parseLoginResponse(); oauth.responseMode(null); - Assert.assertEquals("invalid_request", authorizationEndpointResponse.getError()); - Assert.assertEquals("some-state", authorizationEndpointResponse.getState()); + Assertions.assertEquals("invalid_request", authorizationEndpointResponse.getError()); + Assertions.assertEquals("some-state", authorizationEndpointResponse.getState()); // Test that "client_id" and "response_type" are not mandatory in the request object Map oidcRequest = new HashMap<>(); @@ -678,8 +678,8 @@ public void requestObjectClientIdAndResponseTypeTest() { oauth.clientId("test-app"); oauth.responseType(OAuth2Constants.CODE); AuthorizationEndpointResponse response1 = oauth.loginForm().request(requestObjectString).state("some-state").doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response1.getCode()); - Assert.assertEquals("request-state", response1.getState()); + Assertions.assertNotNull(response1.getCode()); + Assertions.assertEquals("request-state", response1.getState()); } @Test @@ -696,8 +696,8 @@ public void requestObjectRequiredProvidedInRequestUriParam() { // Assert that the request is accepted AuthorizationEndpointResponse response2 = oauth.loginForm().requestUri(TestApplicationResourceUrls.clientRequestUri()).state("mystate2").doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response2.getCode()); - Assert.assertEquals("mystate2", response2.getState()); + Assertions.assertNotNull(response2.getCode()); + Assertions.assertEquals("mystate2", response2.getState()); assertTrue(appPage.isCurrent()); // Revert requiring request object for client @@ -716,7 +716,7 @@ public void requestObjectRequiredAsRequestParamNotProvided() { // Send request without request object // Assert that the request is not accepted oauth.loginForm().state("mystate2").open(); - Assert.assertTrue(errorPage.isCurrent()); + Assertions.assertTrue(errorPage.isCurrent()); assertEquals("Invalid Request", errorPage.getError()); // Revert requiring request object for client @@ -738,8 +738,8 @@ public void requestObjectRequiredAsRequestParamProvidedInRequestParam() { // Assert that the request is accepted AuthorizationEndpointResponse response1 = oauth.loginForm().request(oidcClientEndpointsResource.getOIDCRequest()).state("mystate2").doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response1.getCode()); - Assert.assertEquals("mystate2", response1.getState()); + Assertions.assertNotNull(response1.getCode()); + Assertions.assertEquals("mystate2", response1.getState()); assertTrue(appPage.isCurrent()); // Revert requiring request object for client @@ -761,7 +761,7 @@ public void requestObjectRequiredAsRequestParamProvidedInRequestUriParam() { // Assert that the request is accepted oauth.loginForm().requestUri(TestApplicationResourceUrls.clientRequestUri()).state("mystate2").open(); - Assert.assertTrue(errorPage.isCurrent()); + Assertions.assertTrue(errorPage.isCurrent()); assertEquals("Invalid Request", errorPage.getError()); // Revert requiring request object for client @@ -780,7 +780,7 @@ public void requestObjectRequiredAsRequestUriParamNotProvided() { // Send request without request object // Assert that the request is not accepted oauth.loginForm().state("mystate2").open(); - Assert.assertTrue(errorPage.isCurrent()); + Assertions.assertTrue(errorPage.isCurrent()); assertEquals("Invalid Request", errorPage.getError()); // Revert requiring request object for client @@ -802,7 +802,7 @@ public void requestObjectRequiredAsRequestUriParamProvidedInRequestParam() { // Assert that the request is not accepted oauth.loginForm().request(oidcClientEndpointsResource.getOIDCRequest()).state("mystate2").open(); - Assert.assertTrue(errorPage.isCurrent()); + Assertions.assertTrue(errorPage.isCurrent()); assertEquals("Invalid Request", errorPage.getError()); // Revert requiring request object for client @@ -824,8 +824,8 @@ public void requestObjectRequiredAsRequestUriParamProvidedInRequestUriParam() { // Assert that the request is accepted AuthorizationEndpointResponse response1 = oauth.loginForm().requestUri(TestApplicationResourceUrls.clientRequestUri()).state("mystate2").doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response1.getCode()); - Assert.assertEquals("mystate2", response1.getState()); + Assertions.assertNotNull(response1.getCode()); + Assertions.assertEquals("mystate2", response1.getState()); assertTrue(appPage.isCurrent()); // Revert requiring request object for client @@ -843,7 +843,7 @@ public void requestParamUnsigned() { String requestStr = oidcClientEndpointsResource.getOIDCRequest(); oauth.loginForm().request(requestStr).state("mystate2").open(); - Assert.assertTrue(errorPage.isCurrent()); + Assertions.assertTrue(errorPage.isCurrent()); assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); // Assert the value from request object has bigger priority then from the query parameter. @@ -852,8 +852,8 @@ public void requestParamUnsigned() { requestStr = oidcClientEndpointsResource.getOIDCRequest(); AuthorizationEndpointResponse response = oauth.loginForm().request(requestStr).state("mystate2").doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response.getCode()); - Assert.assertEquals("mystate2", response.getState()); + Assertions.assertNotNull(response.getCode()); + Assertions.assertEquals("mystate2", response.getState()); assertTrue(appPage.isCurrent()); } @@ -868,7 +868,7 @@ public void requestUriParamUnsigned() { String requestUri = TestApplicationResourceUrls.clientRequestUri(); oauth.loginForm().requestUri(requestUri).open(); - Assert.assertTrue(errorPage.isCurrent()); + Assertions.assertTrue(errorPage.isCurrent()); assertEquals("Invalid parameter: redirect_uri", errorPage.getError()); // Assert the value from request object has bigger priority then from the query parameter. @@ -876,8 +876,8 @@ public void requestUriParamUnsigned() { oidcClientEndpointsResource.setOIDCRequest("test", "test-app", validRedirectUri, "10", "mystate1", "none"); AuthorizationEndpointResponse response = oauth.loginForm().requestUri(requestUri).doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response.getCode()); - Assert.assertEquals("mystate1", response.getState()); + Assertions.assertNotNull(response.getCode()); + Assertions.assertEquals("mystate1", response.getState()); assertTrue(appPage.isCurrent()); } @@ -896,7 +896,7 @@ public void requestUriParamWithAllowedRequestUris() { clientMgrBuilder.setRequestUris(requestUri); oauth.loginForm().requestUri(loginRequestUri).open(); - Assert.assertFalse(errorPage.isCurrent()); + Assertions.assertFalse(errorPage.isCurrent()); loginPage.assertCurrent(); // Test with the relative and star at the end - should pass @@ -904,7 +904,7 @@ public void requestUriParamWithAllowedRequestUris() { clientMgrBuilder.setRequestUris(requestUri); oauth.loginForm().requestUri(loginRequestUri).open(); - Assert.assertFalse(errorPage.isCurrent()); + Assertions.assertFalse(errorPage.isCurrent()); loginPage.assertCurrent(); // Test absolute and wildcard at the end - should pass @@ -912,21 +912,21 @@ public void requestUriParamWithAllowedRequestUris() { clientMgrBuilder.setRequestUris(requestUri); oauth.loginForm().requestUri(loginRequestUri).open(); - Assert.assertFalse(errorPage.isCurrent()); + Assertions.assertFalse(errorPage.isCurrent()); loginPage.assertCurrent(); // Test star only as wildcard - should pass clientMgrBuilder.setRequestUris("*"); oauth.loginForm().requestUri(loginRequestUri).open(); - Assert.assertFalse(errorPage.isCurrent()); + Assertions.assertFalse(errorPage.isCurrent()); loginPage.assertCurrent(); // Test with multiple request_uris - should pass clientMgrBuilder.setRequestUris("/foo", requestUri); oauth.loginForm().requestUri(loginRequestUri).open(); - Assert.assertFalse(errorPage.isCurrent()); + Assertions.assertFalse(errorPage.isCurrent()); loginPage.assertCurrent(); // Test invalid request_uris - should fail @@ -961,7 +961,7 @@ public void requestUriParamSigned() { // Verify unsigned request_uri will fail oidcClientEndpointsResource.setOIDCRequest("test", "test-app", validRedirectUri, "10", "none"); oauth.loginForm().requestUri(requestUri).open(); - Assert.assertTrue(errorPage.isCurrent()); + Assertions.assertTrue(errorPage.isCurrent()); assertEquals("Invalid Request", errorPage.getError()); // Generate keypair for client @@ -970,7 +970,7 @@ public void requestUriParamSigned() { // Verify signed request_uri will fail due to failed signature validation oidcClientEndpointsResource.setOIDCRequest("test", "test-app", validRedirectUri, "10", "mystate3", Algorithm.RS256); oauth.loginForm().requestUri(requestUri).open(); - Assert.assertTrue(errorPage.isCurrent()); + Assertions.assertTrue(errorPage.isCurrent()); assertEquals("Invalid Request", errorPage.getError()); @@ -986,8 +986,8 @@ public void requestUriParamSigned() { // Check signed request_uri will pass AuthorizationEndpointResponse response = oauth.loginForm().requestUri(requestUri).doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response.getCode()); - Assert.assertEquals("mystate3", response.getState()); + Assertions.assertNotNull(response.getCode()); + Assertions.assertEquals("mystate3", response.getState()); assertTrue(appPage.isCurrent()); // Revert requiring signature for client @@ -1035,13 +1035,13 @@ private void requestUriParamSignedIn(String expectedAlgorithm, String actualAlgo if (expectedAlgorithm == null || expectedAlgorithm.equals(actualAlgorithm)) { // Check signed request_uri will pass AuthorizationEndpointResponse response = oauth.loginForm().requestUri(requestUri).doLogin("test-user@localhost", "password"); - Assert.assertNotNull(response.getCode()); - Assert.assertEquals("mystate3", response.getState()); + Assertions.assertNotNull(response.getCode()); + Assertions.assertEquals("mystate3", response.getState()); appPage.assertCurrent(); } else { // Verify signed request_uri will fail due to failed signature validation oauth.loginForm().requestUri(requestUri).open(); - Assert.assertTrue(errorPage.isCurrent()); + Assertions.assertTrue(errorPage.isCurrent()); assertEquals("Invalid Request", errorPage.getError()); } @@ -1148,9 +1148,9 @@ public void loginHint() { oauth.loginForm().loginHint("test-user%40localhost").open(); loginPage.assertCurrent(); - Assert.assertEquals("test-user@localhost", loginPage.getUsername()); + Assertions.assertEquals("test-user@localhost", loginPage.getUsername()); loginPage.login("password"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent(); } @@ -1172,7 +1172,7 @@ public void processClaimsQueryParam() throws IOException { // need to login so session id can be read from event loginPage.assertCurrent(); loginPage.login("test-user@localhost", "password"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); EventRepresentation loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent(); String sessionId = loginEvent.getSessionId(); @@ -1211,7 +1211,7 @@ public void processClaimsRequestParam() throws Exception { // need to login so session id can be read from event loginPage.assertCurrent(); loginPage.login("test-user@localhost", "password"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); EventRepresentation loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent(); String sessionId = loginEvent.getSessionId(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCBackwardsCompatibilityTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCBackwardsCompatibilityTest.java index 87ecc6b02ff7..4b15988da0d3 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCBackwardsCompatibilityTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCBackwardsCompatibilityTest.java @@ -28,7 +28,6 @@ import org.keycloak.representations.idm.EventRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.pages.AppPage; @@ -42,9 +41,9 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertTrue; - +import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -90,8 +89,8 @@ public void testExcludeSessionStateParameter() { // Open login form and login successfully. Assert session_state is present AuthorizationEndpointResponse authzResponse = oauth.doLogin("test-user@localhost", "password"); EventRepresentation loginEvent = events.expectLogin().assertEvent(); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(authzResponse.getSessionState()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(authzResponse.getSessionState()); // Switch "exclude session_state" to on ClientResource client = AdminApiUtil.findClientByClientId(adminClient.realm("test"), "test-app"); @@ -102,11 +101,11 @@ public void testExcludeSessionStateParameter() { // Open login again and assert session_state not present oauth.openLoginForm(); - org.keycloak.testsuite.Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent(); authzResponse = oauth.parseLoginResponse(); - Assert.assertNull(authzResponse.getSessionState()); + Assertions.assertNull(authzResponse.getSessionState()); // Revert config.setExcludeSessionStateFromAuthResponse(false); @@ -118,8 +117,8 @@ public void testExcludeIssuerParameter() { // Open login form and login successfully. Assert iss parameter is present AuthorizationEndpointResponse authzResponse = oauth.doLogin("test-user@localhost", "password"); events.expectLogin().assertEvent(); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertEquals(oauth.AUTH_SERVER_ROOT + "/realms/test", authzResponse.getIssuer()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(oauth.AUTH_SERVER_ROOT + "/realms/test", authzResponse.getIssuer()); // Switch "exclude iss" to on ClientResource client = AdminApiUtil.findClientByClientId(adminClient.realm("test"), "test-app"); @@ -130,11 +129,11 @@ public void testExcludeIssuerParameter() { // Open login again and assert iss parameter is not present oauth.openLoginForm(); - org.keycloak.testsuite.Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent(); authzResponse = oauth.parseLoginResponse(); - Assert.assertNull(authzResponse.getIssuer()); + Assertions.assertNull(authzResponse.getIssuer()); // Revert config.setExcludeIssuerFromAuthResponse(false); @@ -149,8 +148,8 @@ public void testExcludeIssuerParameterOnError() throws IOException { AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); assertTrue(errorResponse.isRedirected()); - Assert.assertEquals(errorResponse.getError(), OAuthErrorException.UNSUPPORTED_RESPONSE_TYPE); - Assert.assertEquals(oauth.AUTH_SERVER_ROOT + "/realms/test", errorResponse.getIssuer()); + Assertions.assertEquals(errorResponse.getError(), OAuthErrorException.UNSUPPORTED_RESPONSE_TYPE); + Assertions.assertEquals(oauth.AUTH_SERVER_ROOT + "/realms/test", errorResponse.getIssuer()); events.expectLogin().error(Errors.INVALID_REQUEST).user((String) null).session((String) null).clearDetails().detail(Details.RESPONSE_TYPE, "tokenn").assertEvent(); @@ -166,8 +165,8 @@ public void testExcludeIssuerParameterOnError() throws IOException { errorResponse = oauth.parseLoginResponse(); assertTrue(errorResponse.isRedirected()); - Assert.assertEquals(errorResponse.getError(), OAuthErrorException.UNSUPPORTED_RESPONSE_TYPE); - Assert.assertNull(errorResponse.getIssuer()); + Assertions.assertEquals(errorResponse.getError(), OAuthErrorException.UNSUPPORTED_RESPONSE_TYPE); + Assertions.assertNull(errorResponse.getIssuer()); events.expectLogin().error(Errors.INVALID_REQUEST).user((String) null).session((String) null).clearDetails().detail(Details.RESPONSE_TYPE, "tokenn").assertEvent(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCPublicClientTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCPublicClientTest.java index 24c9b8854644..43e9f6f6feb7 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCPublicClientTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCPublicClientTest.java @@ -32,15 +32,15 @@ import org.keycloak.testsuite.util.ClientManager; import org.keycloak.testsuite.util.oauth.AccessTokenResponse; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Marek Posolda @@ -86,7 +86,7 @@ public void accessTokenRequest() throws Exception { // Switch client to public client now clientRep = clientResource.toRepresentation(); - Assert.assertEquals(JWTClientAuthenticator.PROVIDER_ID, clientRep.getClientAuthenticatorType()); + Assertions.assertEquals(JWTClientAuthenticator.PROVIDER_ID, clientRep.getClientAuthenticatorType()); clientRep.setPublicClient(true); clientResource.update(clientRep); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCScopeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCScopeTest.java index 10427aee1ae9..657eb8bd32ff 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCScopeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCScopeTest.java @@ -59,11 +59,12 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.OAuthErrorException.INVALID_SCOPE; import static org.keycloak.testsuite.auth.page.AuthRealm.TEST; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for OAuth2 'scope' parameter and for some other aspects of client scopes @@ -223,27 +224,27 @@ public void testBuiltinOptionalScopes() throws Exception { private void assertProfile(IDToken idToken, boolean claimsIn) { if (claimsIn) { - Assert.assertEquals("john", idToken.getPreferredUsername()); - Assert.assertEquals("John", idToken.getGivenName()); - Assert.assertEquals("Doe", idToken.getFamilyName()); - Assert.assertEquals("John Doe", idToken.getName()); - Assert.assertEquals(Long.valueOf(1643282255L),idToken.getUpdatedAt()); + Assertions.assertEquals("john", idToken.getPreferredUsername()); + Assertions.assertEquals("John", idToken.getGivenName()); + Assertions.assertEquals("Doe", idToken.getFamilyName()); + Assertions.assertEquals("John Doe", idToken.getName()); + Assertions.assertEquals(Long.valueOf(1643282255L),idToken.getUpdatedAt()); } else { - Assert.assertNull(idToken.getPreferredUsername()); - Assert.assertNull(idToken.getGivenName()); - Assert.assertNull(idToken.getFamilyName()); - Assert.assertNull(idToken.getName()); + Assertions.assertNull(idToken.getPreferredUsername()); + Assertions.assertNull(idToken.getGivenName()); + Assertions.assertNull(idToken.getFamilyName()); + Assertions.assertNull(idToken.getName()); } } private void assertEmail(IDToken idToken, boolean claimsIn) { if (claimsIn) { - Assert.assertEquals("john@email.cz", idToken.getEmail()); - Assert.assertEquals(true, idToken.getEmailVerified()); + Assertions.assertEquals("john@email.cz", idToken.getEmail()); + Assertions.assertEquals(true, idToken.getEmailVerified()); } else { - Assert.assertNull(idToken.getEmail()); - Assert.assertNull(idToken.getEmailVerified()); + Assertions.assertNull(idToken.getEmail()); + Assertions.assertNull(idToken.getEmailVerified()); } } @@ -251,36 +252,36 @@ private void assertEmail(IDToken idToken, boolean claimsIn) { private void assertAddress(IDToken idToken, boolean claimsIn) { AddressClaimSet address = idToken.getAddress(); if (claimsIn) { - Assert.assertNotNull(address); - Assert.assertEquals("Elm 5", address.getStreetAddress()); + Assertions.assertNotNull(address); + Assertions.assertEquals("Elm 5", address.getStreetAddress()); } else { - Assert.assertNull(address); + Assertions.assertNull(address); } } private void assertPhone(IDToken idToken, boolean claimsIn) { if (claimsIn) { - Assert.assertEquals("111-222-333", idToken.getPhoneNumber()); - Assert.assertEquals(true, idToken.getPhoneNumberVerified()); + Assertions.assertEquals("111-222-333", idToken.getPhoneNumber()); + Assertions.assertEquals(true, idToken.getPhoneNumberVerified()); } else { - Assert.assertNull(idToken.getPhoneNumber()); - Assert.assertNull(idToken.getPhoneNumberVerified()); + Assertions.assertNull(idToken.getPhoneNumber()); + Assertions.assertNull(idToken.getPhoneNumberVerified()); } } private void assertMicroprofile(IDToken idToken, boolean claimsIn) { if (claimsIn) { - Assert.assertTrue(idToken.getOtherClaims().containsKey("upn")); - Assert.assertEquals("john", idToken.getOtherClaims().get("upn")); - Assert.assertTrue(idToken.getOtherClaims().containsKey("groups")); + Assertions.assertTrue(idToken.getOtherClaims().containsKey("upn")); + Assertions.assertEquals("john", idToken.getOtherClaims().get("upn")); + Assertions.assertTrue(idToken.getOtherClaims().containsKey("groups")); List groups = (List) idToken.getOtherClaims().get("groups"); - Assert.assertNotNull(groups); - Assert.assertTrue(groups.containsAll(Arrays.asList("role-1", "role-2"))); + Assertions.assertNotNull(groups); + Assertions.assertTrue(groups.containsAll(Arrays.asList("role-1", "role-2"))); } else { - Assert.assertFalse(idToken.getOtherClaims().containsKey("upn")); - Assert.assertFalse(idToken.getOtherClaims().containsKey("groups")); + Assertions.assertFalse(idToken.getOtherClaims().containsKey("upn")); + Assertions.assertFalse(idToken.getOtherClaims().containsKey("groups")); } } @@ -498,7 +499,7 @@ public void testRefreshTokenWithConsentRequired() { // Ensure that I can refresh token AccessTokenResponse refreshResponse = oauth.doRefreshTokenRequest(tokens.refreshToken); - Assert.assertEquals(200, refreshResponse.getStatusCode()); + Assertions.assertEquals(200, refreshResponse.getStatusCode()); idToken = oauth.verifyIDToken(refreshResponse.getIdToken()); assertProfile(idToken, true); @@ -515,7 +516,7 @@ public void testRefreshTokenWithConsentRequired() { events.clear(); AccountHelper.revokeConsents(adminClient.realm(TEST), "john", "third-party"); List> userConsents = AccountHelper.getUserConsents(adminClient.realm(TEST), "john"); - Assert.assertEquals(userConsents.size(), 0); + Assertions.assertEquals(userConsents.size(), 0); // Ensure I can't refresh anymore refreshResponse = oauth.doRefreshTokenRequest(refreshResponse.getRefreshToken()); @@ -572,31 +573,31 @@ public void testTwoRefreshTokensWithDifferentScopes() { .assertEvent(); Tokens tokens1 = sendTokenRequest(loginEvent, userId,"openid email profile scope-role-1", "test-app"); - Assert.assertTrue(tokens1.accessToken.getRealmAccess().isUserInRole("role-1")); - Assert.assertFalse(tokens1.accessToken.getRealmAccess().isUserInRole("role-2")); + Assertions.assertTrue(tokens1.accessToken.getRealmAccess().isUserInRole("role-1")); + Assertions.assertFalse(tokens1.accessToken.getRealmAccess().isUserInRole("role-2")); //SSO login with scope-role-2. Save refresh token oauth.scope("scope-role-2"); oauth.openLoginForm(); loginEvent = events.expectLogin().user(userId).removeDetail(Details.USERNAME).client("test-app").assertEvent(); Tokens tokens2 = sendTokenRequest(loginEvent, userId,"openid email profile scope-role-2", "test-app"); - Assert.assertFalse(tokens2.accessToken.getRealmAccess().isUserInRole("role-1")); - Assert.assertTrue(tokens2.accessToken.getRealmAccess().isUserInRole("role-2")); + Assertions.assertFalse(tokens2.accessToken.getRealmAccess().isUserInRole("role-1")); + Assertions.assertTrue(tokens2.accessToken.getRealmAccess().isUserInRole("role-2")); // Ensure I can refresh refreshToken1. Just role1 is present oauth.scope(null); AccessTokenResponse refreshResponse1 = oauth.doRefreshTokenRequest(tokens1.refreshToken); - Assert.assertEquals(200, refreshResponse1.getStatusCode()); + Assertions.assertEquals(200, refreshResponse1.getStatusCode()); AccessToken accessToken1 = oauth.verifyToken(refreshResponse1.getAccessToken()); - Assert.assertTrue(accessToken1.getRealmAccess().isUserInRole("role-1")); - Assert.assertFalse(accessToken1.getRealmAccess().isUserInRole("role-2")); + Assertions.assertTrue(accessToken1.getRealmAccess().isUserInRole("role-1")); + Assertions.assertFalse(accessToken1.getRealmAccess().isUserInRole("role-2")); // Ensure I can refresh refreshToken2. Just role2 is present AccessTokenResponse refreshResponse2 = oauth.doRefreshTokenRequest(tokens2.refreshToken); - Assert.assertEquals(200, refreshResponse2.getStatusCode()); + Assertions.assertEquals(200, refreshResponse2.getStatusCode()); AccessToken accessToken2 = oauth.verifyToken(refreshResponse2.getAccessToken()); - Assert.assertFalse(accessToken2.getRealmAccess().isUserInRole("role-1")); - Assert.assertTrue(accessToken2.getRealmAccess().isUserInRole("role-2")); + Assertions.assertFalse(accessToken2.getRealmAccess().isUserInRole("role-1")); + Assertions.assertTrue(accessToken2.getRealmAccess().isUserInRole("role-2")); // Revert testAppRep.setFullScopeAllowed(true); @@ -665,7 +666,7 @@ public void testLengthyScopeParameter() { AccessTokenResponse response = oauth.doPasswordGrantRequest("john", "password"); assertEquals(200, response.getStatusCode()); AccessToken token = oauth.verifyToken(response.getAccessToken()); - Assert.assertFalse(TokenUtil.isOIDCRequest(token.getScope())); + Assertions.assertFalse(TokenUtil.isOIDCRequest(token.getScope())); // Scope parameter relatively long. Should not be ignored scope = getLongScopeParameter(800); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCWellKnownProviderTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCWellKnownProviderTest.java index 2838662ddddf..e578d18627c2 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCWellKnownProviderTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/OIDCWellKnownProviderTest.java @@ -30,7 +30,7 @@ import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Marek Posolda diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/UserInfoTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/UserInfoTest.java index aea8d78c4d7e..52bae67cf3d4 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/UserInfoTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/UserInfoTest.java @@ -105,6 +105,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.protocol.oidc.mappers.OIDCAttributeMapperHelper.INCLUDE_IN_USERINFO; import static org.keycloak.testsuite.AbstractAdminTest.loadJson; @@ -112,9 +113,9 @@ import static org.keycloak.testsuite.util.oauth.OAuthClient.AUTH_SERVER_ROOT; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author pedroigor @@ -375,14 +376,14 @@ private void testUserInfoSignatureAndEncryption(String sigAlgorithm, String curv AccessTokenResponse accessTokenResponse = executeGrantAccessTokenRequest(client); Response response = UserInfoClientUtil.executeUserInfoRequest_getMethod(client, accessTokenResponse.getToken()); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(response.getHeaderString(HttpHeaders.CONTENT_TYPE), MediaType.APPLICATION_JWT); + Assertions.assertEquals(200, response.getStatus()); + Assertions.assertEquals(response.getHeaderString(HttpHeaders.CONTENT_TYPE), MediaType.APPLICATION_JWT); String encryptedResponse = response.readEntity(String.class); response.close(); // parse JWE and JOSE Header String[] parts = encryptedResponse.split("\\."); - Assert.assertEquals(parts.length, 5); + Assertions.assertEquals(parts.length, 5); // get decryption key // not publickey , use privateKey @@ -391,15 +392,15 @@ private void testUserInfoSignatureAndEncryption(String sigAlgorithm, String curv // a nested JWT (signed and encrypted JWT) needs to set "JWT" to its JOSE Header's "cty" field JWEHeader jweHeader = (JWEHeader) getHeader(parts[0]); - Assert.assertEquals(algAlgorithm, jweHeader.getAlgorithm()); + Assertions.assertEquals(algAlgorithm, jweHeader.getAlgorithm()); if(encAlgorithm != null) { - Assert.assertEquals(encAlgorithm, jweHeader.getEncryptionAlgorithm()); + Assertions.assertEquals(encAlgorithm, jweHeader.getEncryptionAlgorithm()); } else { // if enc algorithm is not specified the default for this value is A128CBC-HS256 - Assert.assertEquals(JWEConstants.A128CBC_HS256, jweHeader.getEncryptionAlgorithm()); + Assertions.assertEquals(JWEConstants.A128CBC_HS256, jweHeader.getEncryptionAlgorithm()); } if(sigAlgorithm != null) { - Assert.assertEquals("JWT", jweHeader.getContentType()); + Assertions.assertEquals("JWT", jweHeader.getContentType()); } // verify and decrypt JWE @@ -420,12 +421,12 @@ private void testUserInfoSignatureAndEncryption(String sigAlgorithm, String curv } else { userInfo = JsonSerialization.readValue(jwePayload, UserInfo.class); } - Assert.assertNotNull(userInfo); - Assert.assertNotNull(userInfo.getSubject()); - Assert.assertEquals("test-user@localhost", userInfo.getEmail()); - Assert.assertEquals("test-user@localhost", userInfo.getPreferredUsername()); + Assertions.assertNotNull(userInfo); + Assertions.assertNotNull(userInfo.getSubject()); + Assertions.assertEquals("test-user@localhost", userInfo.getEmail()); + Assertions.assertEquals("test-user@localhost", userInfo.getPreferredUsername()); } catch (JWSInputException | JWEException | IOException e) { - Assert.fail(); + Assertions.fail(); } finally { clientResource = AdminApiUtil.findClientByClientId(adminClient.realm("test"), "test-app"); clientRep = clientResource.toRepresentation(); @@ -496,24 +497,24 @@ public void testSuccessSignedResponse() throws Exception { // Check signature and content PublicKey publicKey = PemUtils.decodePublicKey(KeyUtils.findActiveSigningKey(adminClient.realm("test")).getPublicKey()); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(response.getHeaderString(HttpHeaders.CONTENT_TYPE), MediaType.APPLICATION_JWT); + Assertions.assertEquals(200, response.getStatus()); + Assertions.assertEquals(response.getHeaderString(HttpHeaders.CONTENT_TYPE), MediaType.APPLICATION_JWT); String signedResponse = response.readEntity(String.class); response.close(); JWSInput jwsInput = new JWSInput(signedResponse); - Assert.assertTrue(RSAProvider.verify(jwsInput, publicKey)); + Assertions.assertTrue(RSAProvider.verify(jwsInput, publicKey)); UserInfo userInfo = JsonSerialization.readValue(jwsInput.getContent(), UserInfo.class); - Assert.assertNotNull(userInfo); - Assert.assertNotNull(userInfo.getSubject()); - Assert.assertEquals("test-user@localhost", userInfo.getEmail()); - Assert.assertEquals("test-user@localhost", userInfo.getPreferredUsername()); + Assertions.assertNotNull(userInfo); + Assertions.assertNotNull(userInfo.getSubject()); + Assertions.assertEquals("test-user@localhost", userInfo.getEmail()); + Assertions.assertEquals("test-user@localhost", userInfo.getPreferredUsername()); - Assert.assertTrue(userInfo.hasAudience("test-app")); + Assertions.assertTrue(userInfo.hasAudience("test-app")); String expectedIssuer = Urls.realmIssuer(new URI(AUTH_SERVER_ROOT), "test"); - Assert.assertEquals(expectedIssuer, userInfo.getIssuer()); + Assertions.assertEquals(expectedIssuer, userInfo.getIssuer()); } finally { client.close(); @@ -619,7 +620,7 @@ public void testAccessTokenAfterUserSessionLogoutAndLoginAgain() { oauth.fillLoginForm("test-user@localhost", "password"); events.expectLogin().assertEvent(); - Assert.assertFalse(loginPage.isCurrent()); + Assertions.assertFalse(loginPage.isCurrent()); events.clear(); @@ -1037,8 +1038,8 @@ private void testSuccessSignedResponse(String sigAlg, String acceptHeader) throw .detail(Details.SIGNATURE_ALGORITHM, sigAlg) .assertEvent(); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(response.getHeaderString(HttpHeaders.CONTENT_TYPE), MediaType.APPLICATION_JWT); + Assertions.assertEquals(200, response.getStatus()); + Assertions.assertEquals(response.getHeaderString(HttpHeaders.CONTENT_TYPE), MediaType.APPLICATION_JWT); String signedResponse = response.readEntity(String.class); response.close(); @@ -1048,14 +1049,14 @@ private void testSuccessSignedResponse(String sigAlg, String acceptHeader) throw UserInfo userInfo = JsonSerialization.readValue(jwsInput.getContent(), UserInfo.class); - Assert.assertNotNull(userInfo); - Assert.assertNotNull(userInfo.getSubject()); - Assert.assertEquals("test-user@localhost", userInfo.getEmail()); - Assert.assertEquals("test-user@localhost", userInfo.getPreferredUsername()); + Assertions.assertNotNull(userInfo); + Assertions.assertNotNull(userInfo.getSubject()); + Assertions.assertEquals("test-user@localhost", userInfo.getEmail()); + Assertions.assertEquals("test-user@localhost", userInfo.getPreferredUsername()); - Assert.assertTrue(userInfo.hasAudience("test-app")); + Assertions.assertTrue(userInfo.hasAudience("test-app")); String expectedIssuer = Urls.realmIssuer(new URI(AUTH_SERVER_ROOT), "test"); - Assert.assertEquals(expectedIssuer, userInfo.getIssuer()); + Assertions.assertEquals(expectedIssuer, userInfo.getIssuer()); } finally { client.close(); @@ -1139,8 +1140,8 @@ public void test_noContentType() throws Exception { .build("POST") .invoke(); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals("OK", response.getStatusInfo().toString()); + Assertions.assertEquals(200, response.getStatus()); + Assertions.assertEquals("OK", response.getStatusInfo().toString()); } finally { client.close(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/AbstractOIDCResponseTypeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/AbstractOIDCResponseTypeTest.java index 88339367e2f0..36ba1ec25f10 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/AbstractOIDCResponseTypeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/AbstractOIDCResponseTypeTest.java @@ -32,7 +32,6 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.AbstractAdminTest; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.pages.AppPage; @@ -45,11 +44,12 @@ import org.jboss.arquillian.graphene.page.Page; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Abstract test for various values of response_type @@ -84,13 +84,13 @@ public void nonceAndSessionStateMatches() { EventRepresentation loginEvent = loginUser("abcdef123456"); AuthorizationEndpointResponse authzResponse = oauth.parseLoginResponse(); - Assert.assertNotNull(authzResponse.getSessionState()); + Assertions.assertNotNull(authzResponse.getSessionState()); List idTokens = testAuthzResponseAndRetrieveIDTokens(authzResponse, loginEvent); for (IDToken idToken : idTokens) { - Assert.assertEquals("abcdef123456", idToken.getNonce()); - Assert.assertEquals(authzResponse.getSessionState(), idToken.getSessionState()); + Assertions.assertEquals("abcdef123456", idToken.getNonce()); + Assertions.assertEquals(authzResponse.getSessionState(), idToken.getSessionState()); } } @@ -100,12 +100,12 @@ public void initialSessionStateUsedInRedirect() { EventRepresentation loginEvent = loginUserWithRedirect("abcdef123456", OAuthClient.APP_ROOT + "/auth?session_state=foo"); AuthorizationEndpointResponse authzResponse = oauth.parseLoginResponse(); - Assert.assertNotNull(authzResponse.getSessionState()); + Assertions.assertNotNull(authzResponse.getSessionState()); List idTokens = testAuthzResponseAndRetrieveIDTokens(authzResponse, loginEvent); for (IDToken idToken : idTokens) { - Assert.assertEquals(authzResponse.getSessionState(), idToken.getSessionState()); + Assertions.assertEquals(authzResponse.getSessionState(), idToken.getSessionState()); } } @@ -117,8 +117,8 @@ public void authorizationRequestMissingResponseType() throws IOException { // Always read error from the "query" AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); - org.junit.Assert.assertTrue(errorResponse.isRedirected()); - org.junit.Assert.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); + Assertions.assertTrue(errorResponse.isRedirected()); + Assertions.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST); events.expectLogin().error(Errors.INVALID_REQUEST).user((String) null).session((String) null).clearDetails().assertEvent(); } @@ -135,10 +135,10 @@ protected void validateNonceNotUsedErrorExpected() { // Assert error response was sent because not logged in AuthorizationEndpointResponse resp = oauth.parseLoginResponse(); - Assert.assertNull(resp.getCode()); - Assert.assertNull(resp.getIdToken()); - Assert.assertEquals(OAuthErrorException.INVALID_REQUEST, resp.getError()); - Assert.assertEquals("Missing parameter: nonce", resp.getErrorDescription()); + Assertions.assertNull(resp.getCode()); + Assertions.assertNull(resp.getIdToken()); + Assertions.assertEquals(OAuthErrorException.INVALID_REQUEST, resp.getError()); + Assertions.assertEquals("Missing parameter: nonce", resp.getErrorDescription()); } @@ -149,9 +149,9 @@ protected void validateErrorImplicitFlowNotAllowed() throws Exception { oauth.openLoginForm(); AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); - Assert.assertTrue(errorResponse.isRedirected()); - Assert.assertEquals(errorResponse.getError(), OAuthErrorException.UNAUTHORIZED_CLIENT); - Assert.assertEquals(errorResponse.getErrorDescription(), "Client is not allowed to initiate browser login with given response_type. Implicit flow is disabled for the client."); + Assertions.assertTrue(errorResponse.isRedirected()); + Assertions.assertEquals(errorResponse.getError(), OAuthErrorException.UNAUTHORIZED_CLIENT); + Assertions.assertEquals(errorResponse.getErrorDescription(), "Client is not allowed to initiate browser login with given response_type. Implicit flow is disabled for the client."); events.expectLogin().error(Errors.NOT_ALLOWED).user((String) null).session((String) null).clearDetails().assertEvent(); @@ -167,9 +167,9 @@ protected void validateErrorStandardFlowNotAllowed() throws Exception { oauth.openLoginForm(); AuthorizationEndpointResponse errorResponse = oauth.parseLoginResponse(); - Assert.assertTrue(errorResponse.isRedirected()); - Assert.assertEquals(errorResponse.getError(), OAuthErrorException.UNAUTHORIZED_CLIENT); - Assert.assertEquals(errorResponse.getErrorDescription(), "Client is not allowed to initiate browser login with given response_type. Standard flow is disabled for the client."); + Assertions.assertTrue(errorResponse.isRedirected()); + Assertions.assertEquals(errorResponse.getError(), OAuthErrorException.UNAUTHORIZED_CLIENT); + Assertions.assertEquals(errorResponse.getErrorDescription(), "Client is not allowed to initiate browser login with given response_type. Standard flow is disabled for the client."); events.expectLogin().error(Errors.NOT_ALLOWED).user((String) null).session((String) null).clearDetails().assertEvent(); @@ -184,7 +184,7 @@ protected EventRepresentation loginUser(String nonce) { loginPage.assertCurrent(); loginPage.login("test-user@localhost", "password"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); return events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent(); } @@ -198,7 +198,7 @@ protected EventRepresentation loginUserWithRedirect(String nonce, String redirec loginPage.assertCurrent(); loginPage.login("test-user@localhost", "password"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); return events.expectLogin().detail(Details.REDIRECT_URI, redirectUri).detail(Details.USERNAME, "test-user@localhost").assertEvent(); } @@ -215,7 +215,7 @@ private void oidcFlow(String expectedAccessAlg, String expectedIdTokenAlg) throw EventRepresentation loginEvent = loginUser("abcdef123456"); AuthorizationEndpointResponse authzResponse = oauth.parseLoginResponse(); - Assert.assertNotNull(authzResponse.getSessionState()); + Assertions.assertNotNull(authzResponse.getSessionState()); JWSHeader header = null; String idToken = authzResponse.getIdToken(); @@ -236,8 +236,8 @@ private void oidcFlow(String expectedAccessAlg, String expectedIdTokenAlg) throw List idTokens = testAuthzResponseAndRetrieveIDTokens(authzResponse, loginEvent); for (IDToken idt : idTokens) { - Assert.assertEquals("abcdef123456", idt.getNonce()); - Assert.assertEquals(authzResponse.getSessionState(), idt.getSessionState()); + Assertions.assertEquals("abcdef123456", idt.getNonce()); + Assertions.assertEquals(authzResponse.getSessionState(), idt.getSessionState()); } } @@ -305,8 +305,8 @@ protected String getIdTokenSignatureAlgorithm() { */ protected void assertValidAccessTokenHash(String accessTokenHash, String accessToken) { - Assert.assertNotNull(accessTokenHash); - Assert.assertNotNull(accessToken); + Assertions.assertNotNull(accessTokenHash); + Assertions.assertNotNull(accessToken); assertEquals(accessTokenHash, HashUtils.accessTokenHash(getIdTokenSignatureAlgorithm(), accessToken)); } @@ -317,8 +317,8 @@ protected void assertValidAccessTokenHash(String accessTokenHash, String accessT */ protected void assertValidCodeHash(String codeHash, String code) { - Assert.assertNotNull(codeHash); - Assert.assertNotNull(code); - Assert.assertEquals(codeHash, HashUtils.accessTokenHash(getIdTokenSignatureAlgorithm(), code)); + Assertions.assertNotNull(codeHash); + Assertions.assertNotNull(code); + Assertions.assertEquals(codeHash, HashUtils.accessTokenHash(getIdTokenSignatureAlgorithm(), code)); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCBasicResponseTypeCodeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCBasicResponseTypeCodeTest.java index 00066f0455ac..d9e7f786bce0 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCBasicResponseTypeCodeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCBasicResponseTypeCodeTest.java @@ -24,12 +24,12 @@ import org.keycloak.protocol.oidc.utils.OIDCResponseType; import org.keycloak.representations.IDToken; import org.keycloak.representations.idm.EventRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.keycloak.testsuite.util.oauth.AuthorizationEndpointResponse; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * Test for response_type=code @@ -54,10 +54,10 @@ protected boolean isFragment() { @Override protected List testAuthzResponseAndRetrieveIDTokens(AuthorizationEndpointResponse authzResponse, EventRepresentation loginEvent) { - Assert.assertEquals(OIDCResponseType.CODE, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); + Assertions.assertEquals(OIDCResponseType.CODE, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); - Assert.assertNull(authzResponse.getAccessToken()); - Assert.assertNull(authzResponse.getIdToken()); + Assertions.assertNull(authzResponse.getAccessToken()); + Assertions.assertNull(authzResponse.getIdToken()); AccessTokenResponse authzResponse2 = sendTokenRequestAndGetResponse(loginEvent); IDToken idToken2 = oauth.verifyIDToken(authzResponse2.getIdToken()); @@ -66,10 +66,10 @@ protected List testAuthzResponseAndRetrieveIDTokens(AuthorizationEndpoi assertValidAccessTokenHash(idToken2.getAccessTokenHash(), authzResponse2.getAccessToken()); // Validate if token_type is null - Assert.assertNull(authzResponse.getTokenType()); + Assertions.assertNull(authzResponse.getTokenType()); // Validate if expires_in is null - Assert.assertNull(authzResponse.getExpiresIn()); + Assertions.assertNull(authzResponse.getExpiresIn()); return Collections.singletonList(idToken2); } @@ -82,7 +82,7 @@ public void nonceNotUsed() { AuthorizationEndpointResponse authzResponse = oauth.parseLoginResponse(); List idTokens = testAuthzResponseAndRetrieveIDTokens(authzResponse, loginEvent); for (IDToken idToken : idTokens) { - Assert.assertNull(idToken.getNonce()); + Assertions.assertNull(idToken.getNonce()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCBasicResponseTypeNoneTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCBasicResponseTypeNoneTest.java index 94f9bb7c3903..f320337fe3c1 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCBasicResponseTypeNoneTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCBasicResponseTypeNoneTest.java @@ -24,10 +24,10 @@ import org.keycloak.protocol.oidc.utils.OIDCResponseType; import org.keycloak.representations.IDToken; import org.keycloak.representations.idm.EventRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.oauth.AuthorizationEndpointResponse; import org.junit.Before; +import org.junit.jupiter.api.Assertions; /** * Test for response_type=none @@ -52,11 +52,11 @@ protected boolean isFragment() { @Override protected List testAuthzResponseAndRetrieveIDTokens(AuthorizationEndpointResponse authzResponse, EventRepresentation loginEvent) { - Assert.assertEquals(OIDCResponseType.NONE, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); + Assertions.assertEquals(OIDCResponseType.NONE, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); - Assert.assertNull(authzResponse.getCode()); - Assert.assertNull(authzResponse.getAccessToken()); - Assert.assertNull(authzResponse.getIdToken()); + Assertions.assertNull(authzResponse.getCode()); + Assertions.assertNull(authzResponse.getAccessToken()); + Assertions.assertNull(authzResponse.getIdToken()); return Collections.emptyList(); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeIDTokenAsDetachedSigTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeIDTokenAsDetachedSigTest.java index b40943a666ab..8b43d5e5b43a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeIDTokenAsDetachedSigTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeIDTokenAsDetachedSigTest.java @@ -26,11 +26,11 @@ import org.keycloak.protocol.oidc.utils.OIDCResponseType; import org.keycloak.representations.IDToken; import org.keycloak.representations.idm.EventRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.oauth.AuthorizationEndpointResponse; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * Tests with response_type=code id_token as detached signature @@ -55,22 +55,22 @@ protected boolean isFragment() { protected List testAuthzResponseAndRetrieveIDTokens(AuthorizationEndpointResponse authzResponse, EventRepresentation loginEvent) { - Assert.assertEquals(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); + Assertions.assertEquals(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); // IDToken from the authorization response - Assert.assertNull(authzResponse.getAccessToken()); + Assertions.assertNull(authzResponse.getAccessToken()); String idTokenStr = authzResponse.getIdToken(); IDToken idToken = oauth.verifyIDToken(idTokenStr); // confirm ID token as detached signature does not include authenticated user's claims - Assert.assertNull(idToken.getEmailVerified()); - Assert.assertNull(idToken.getName()); - Assert.assertNull(idToken.getPreferredUsername()); - Assert.assertNull(idToken.getGivenName()); - Assert.assertNull(idToken.getFamilyName()); - Assert.assertNull(idToken.getEmail()); + Assertions.assertNull(idToken.getEmailVerified()); + Assertions.assertNull(idToken.getName()); + Assertions.assertNull(idToken.getPreferredUsername()); + Assertions.assertNull(idToken.getGivenName()); + Assertions.assertNull(idToken.getFamilyName()); + Assertions.assertNull(idToken.getEmail()); // Validate "at_hash" - Assert.assertNull(idToken.getAccessTokenHash()); + Assertions.assertNull(idToken.getAccessTokenHash()); // Validate "c_hash" assertValidCodeHash(idToken.getCodeHash(), authzResponse.getCode()); @@ -78,25 +78,25 @@ protected List testAuthzResponseAndRetrieveIDTokens(AuthorizationEndpoi // Financial API - Part 2: Read and Write API Security Profile // http://openid.net/specs/openid-financial-api-part-2.html#authorization-server // Validate "s_hash" - Assert.assertNotNull(idToken.getStateHash()); + Assertions.assertNotNull(idToken.getStateHash()); - Assert.assertEquals(idToken.getStateHash(), HashUtils.accessTokenHash(getIdTokenSignatureAlgorithm(), authzResponse.getState())); + Assertions.assertEquals(idToken.getStateHash(), HashUtils.accessTokenHash(getIdTokenSignatureAlgorithm(), authzResponse.getState())); // Validate if token_type is null - Assert.assertNull(authzResponse.getTokenType()); + Assertions.assertNull(authzResponse.getTokenType()); // Validate if expires_in is null - Assert.assertNull(authzResponse.getExpiresIn()); + Assertions.assertNull(authzResponse.getExpiresIn()); // IDToken exchanged for the code IDToken idToken2 = sendTokenRequestAndGetIDToken(loginEvent); // confirm ordinal ID token includes authenticated user's claims - Assert.assertNotNull(idToken2.getEmailVerified()); - Assert.assertNotNull(idToken2.getName()); - Assert.assertNotNull(idToken2.getPreferredUsername()); - Assert.assertNotNull(idToken2.getGivenName()); - Assert.assertNotNull(idToken2.getFamilyName()); - Assert.assertNotNull(idToken2.getEmail()); + Assertions.assertNotNull(idToken2.getEmailVerified()); + Assertions.assertNotNull(idToken2.getName()); + Assertions.assertNotNull(idToken2.getPreferredUsername()); + Assertions.assertNotNull(idToken2.getGivenName()); + Assertions.assertNotNull(idToken2.getFamilyName()); + Assertions.assertNotNull(idToken2.getEmail()); return Arrays.asList(idToken, idToken2); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeIDTokenAsDetachedSigTokenTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeIDTokenAsDetachedSigTokenTest.java index fa5be38deaef..3629b5515df2 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeIDTokenAsDetachedSigTokenTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeIDTokenAsDetachedSigTokenTest.java @@ -26,11 +26,11 @@ import org.keycloak.protocol.oidc.utils.OIDCResponseType; import org.keycloak.representations.IDToken; import org.keycloak.representations.idm.EventRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.oauth.AuthorizationEndpointResponse; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * Tests with response_type=code id_token token as detached signature @@ -55,19 +55,19 @@ protected boolean isFragment() { protected List testAuthzResponseAndRetrieveIDTokens(AuthorizationEndpointResponse authzResponse, EventRepresentation loginEvent) { - Assert.assertEquals(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN + " " + OIDCResponseType.TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); + Assertions.assertEquals(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN + " " + OIDCResponseType.TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); // IDToken from the authorization response - Assert.assertNotNull(authzResponse.getAccessToken()); + Assertions.assertNotNull(authzResponse.getAccessToken()); String idTokenStr = authzResponse.getIdToken(); IDToken idToken = oauth.verifyIDToken(idTokenStr); // confirm ID token as detached signature does not include authenticated user's claims - Assert.assertNull(idToken.getEmailVerified()); - Assert.assertNull(idToken.getName()); - Assert.assertNull(idToken.getPreferredUsername()); - Assert.assertNull(idToken.getGivenName()); - Assert.assertNull(idToken.getFamilyName()); - Assert.assertNull(idToken.getEmail()); + Assertions.assertNull(idToken.getEmailVerified()); + Assertions.assertNull(idToken.getName()); + Assertions.assertNull(idToken.getPreferredUsername()); + Assertions.assertNull(idToken.getGivenName()); + Assertions.assertNull(idToken.getFamilyName()); + Assertions.assertNull(idToken.getEmail()); // Validate "at_hash" assertValidAccessTokenHash(idToken.getAccessTokenHash(), authzResponse.getAccessToken()); @@ -78,25 +78,25 @@ protected List testAuthzResponseAndRetrieveIDTokens(AuthorizationEndpoi // Financial API - Part 2: Read and Write API Security Profile // http://openid.net/specs/openid-financial-api-part-2.html#authorization-server // Validate "s_hash" - Assert.assertNotNull(idToken.getStateHash()); + Assertions.assertNotNull(idToken.getStateHash()); - Assert.assertEquals(idToken.getStateHash(), HashUtils.accessTokenHash(getIdTokenSignatureAlgorithm(), authzResponse.getState())); + Assertions.assertEquals(idToken.getStateHash(), HashUtils.accessTokenHash(getIdTokenSignatureAlgorithm(), authzResponse.getState())); // Validate if token_type is present - Assert.assertNotNull(authzResponse.getTokenType()); + Assertions.assertNotNull(authzResponse.getTokenType()); // Validate if expires_in is present - Assert.assertNotNull(authzResponse.getExpiresIn()); + Assertions.assertNotNull(authzResponse.getExpiresIn()); // IDToken exchanged for the code IDToken idToken2 = sendTokenRequestAndGetIDToken(loginEvent); // confirm ordinal ID token includes authenticated user's claims - Assert.assertNotNull(idToken2.getEmailVerified()); - Assert.assertNotNull(idToken2.getName()); - Assert.assertNotNull(idToken2.getPreferredUsername()); - Assert.assertNotNull(idToken2.getGivenName()); - Assert.assertNotNull(idToken2.getFamilyName()); - Assert.assertNotNull(idToken2.getEmail()); + Assertions.assertNotNull(idToken2.getEmailVerified()); + Assertions.assertNotNull(idToken2.getName()); + Assertions.assertNotNull(idToken2.getPreferredUsername()); + Assertions.assertNotNull(idToken2.getGivenName()); + Assertions.assertNotNull(idToken2.getFamilyName()); + Assertions.assertNotNull(idToken2.getEmail()); return Arrays.asList(idToken, idToken2); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeIDTokenTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeIDTokenTest.java index 93859298cd3f..76327b63384a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeIDTokenTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeIDTokenTest.java @@ -25,11 +25,11 @@ import org.keycloak.protocol.oidc.utils.OIDCResponseType; import org.keycloak.representations.IDToken; import org.keycloak.representations.idm.EventRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.oauth.AuthorizationEndpointResponse; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * Tests with response_type=code id_token @@ -54,15 +54,15 @@ protected boolean isFragment() { protected List testAuthzResponseAndRetrieveIDTokens(AuthorizationEndpointResponse authzResponse, EventRepresentation loginEvent) { - Assert.assertEquals(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); + Assertions.assertEquals(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); // IDToken from the authorization response - Assert.assertNull(authzResponse.getAccessToken()); + Assertions.assertNull(authzResponse.getAccessToken()); String idTokenStr = authzResponse.getIdToken(); IDToken idToken = oauth.verifyIDToken(idTokenStr); // Validate "at_hash" - Assert.assertNull(idToken.getAccessTokenHash()); + Assertions.assertNull(idToken.getAccessTokenHash()); // Validate "c_hash" assertValidCodeHash(idToken.getCodeHash(), authzResponse.getCode()); @@ -70,15 +70,15 @@ protected List testAuthzResponseAndRetrieveIDTokens(AuthorizationEndpoi // Financial API - Part 2: Read and Write API Security Profile // http://openid.net/specs/openid-financial-api-part-2.html#authorization-server // Validate "s_hash" - Assert.assertNotNull(idToken.getStateHash()); + Assertions.assertNotNull(idToken.getStateHash()); - Assert.assertEquals(idToken.getStateHash(), HashUtils.accessTokenHash(getIdTokenSignatureAlgorithm(), authzResponse.getState())); + Assertions.assertEquals(idToken.getStateHash(), HashUtils.accessTokenHash(getIdTokenSignatureAlgorithm(), authzResponse.getState())); // Validate if token_type is null - Assert.assertNull(authzResponse.getTokenType()); + Assertions.assertNull(authzResponse.getTokenType()); // Validate if expires_in is null - Assert.assertNull(authzResponse.getExpiresIn()); + Assertions.assertNull(authzResponse.getExpiresIn()); // IDToken exchanged for the code IDToken idToken2 = sendTokenRequestAndGetIDToken(loginEvent); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeIDTokenTokenTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeIDTokenTokenTest.java index de0c5ee7c38b..aa34dfcc3eb0 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeIDTokenTokenTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeIDTokenTokenTest.java @@ -25,11 +25,11 @@ import org.keycloak.protocol.oidc.utils.OIDCResponseType; import org.keycloak.representations.IDToken; import org.keycloak.representations.idm.EventRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.oauth.AuthorizationEndpointResponse; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * Tests with response_type=code id_token token @@ -54,10 +54,10 @@ protected boolean isFragment() { protected List testAuthzResponseAndRetrieveIDTokens(AuthorizationEndpointResponse authzResponse, EventRepresentation loginEvent) { - Assert.assertEquals(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN + " " + OIDCResponseType.TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); + Assertions.assertEquals(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN + " " + OIDCResponseType.TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); // IDToken from the authorization response - Assert.assertNotNull(authzResponse.getAccessToken()); + Assertions.assertNotNull(authzResponse.getAccessToken()); String idTokenStr = authzResponse.getIdToken(); IDToken idToken = oauth.verifyIDToken(idTokenStr); @@ -70,15 +70,15 @@ protected List testAuthzResponseAndRetrieveIDTokens(AuthorizationEndpoi // Financial API - Part 2: Read and Write API Security Profile // http://openid.net/specs/openid-financial-api-part-2.html#authorization-server // Validate "s_hash" - Assert.assertNotNull(idToken.getStateHash()); + Assertions.assertNotNull(idToken.getStateHash()); - Assert.assertEquals(idToken.getStateHash(), HashUtils.accessTokenHash(getIdTokenSignatureAlgorithm(), authzResponse.getState())); + Assertions.assertEquals(idToken.getStateHash(), HashUtils.accessTokenHash(getIdTokenSignatureAlgorithm(), authzResponse.getState())); // Validate if token_type is present - Assert.assertNotNull(authzResponse.getTokenType()); + Assertions.assertNotNull(authzResponse.getTokenType()); // Validate if expires_in is present - Assert.assertNotNull(authzResponse.getExpiresIn()); + Assertions.assertNotNull(authzResponse.getExpiresIn()); // IDToken exchanged for the code IDToken idToken2 = sendTokenRequestAndGetIDToken(loginEvent); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeTokenTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeTokenTest.java index ff9d2e1eece0..27aa1dfc1014 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeTokenTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCHybridResponseTypeCodeTokenTest.java @@ -24,12 +24,12 @@ import org.keycloak.protocol.oidc.utils.OIDCResponseType; import org.keycloak.representations.IDToken; import org.keycloak.representations.idm.EventRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.keycloak.testsuite.util.oauth.AuthorizationEndpointResponse; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * Tests with response_type=code token @@ -54,10 +54,10 @@ protected boolean isFragment() { protected List testAuthzResponseAndRetrieveIDTokens(AuthorizationEndpointResponse authzResponse, EventRepresentation loginEvent) { - Assert.assertEquals(OIDCResponseType.CODE + " " + OIDCResponseType.TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); + Assertions.assertEquals(OIDCResponseType.CODE + " " + OIDCResponseType.TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); - Assert.assertNotNull(authzResponse.getAccessToken()); - Assert.assertNull(authzResponse.getIdToken()); + Assertions.assertNotNull(authzResponse.getAccessToken()); + Assertions.assertNull(authzResponse.getIdToken()); // IDToken exchanged for the code AccessTokenResponse authzResponse2 = sendTokenRequestAndGetResponse(loginEvent); @@ -67,10 +67,10 @@ protected List testAuthzResponseAndRetrieveIDTokens(AuthorizationEndpoi assertValidAccessTokenHash(idToken2.getAccessTokenHash(), authzResponse2.getAccessToken()); // Validate if token_type is present - Assert.assertNotNull(authzResponse.getTokenType()); + Assertions.assertNotNull(authzResponse.getTokenType()); // Validate if expires_in is present - Assert.assertNotNull(authzResponse.getExpiresIn()); + Assertions.assertNotNull(authzResponse.getExpiresIn()); return Collections.singletonList(idToken2); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCImplicitResponseTypeIDTokenTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCImplicitResponseTypeIDTokenTest.java index 2626c375ac06..a1b69f27ab10 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCImplicitResponseTypeIDTokenTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCImplicitResponseTypeIDTokenTest.java @@ -24,11 +24,11 @@ import org.keycloak.protocol.oidc.utils.OIDCResponseType; import org.keycloak.representations.IDToken; import org.keycloak.representations.idm.EventRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.oauth.AuthorizationEndpointResponse; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * Tests with response_type=id_token @@ -53,20 +53,20 @@ protected boolean isFragment() { protected List testAuthzResponseAndRetrieveIDTokens(AuthorizationEndpointResponse authzResponse, EventRepresentation loginEvent) { - Assert.assertEquals(OIDCResponseType.ID_TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); + Assertions.assertEquals(OIDCResponseType.ID_TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); - Assert.assertNull(authzResponse.getAccessToken()); + Assertions.assertNull(authzResponse.getAccessToken()); String idTokenStr = authzResponse.getIdToken(); IDToken idToken = oauth.verifyIDToken(idTokenStr); - Assert.assertNull(idToken.getAccessTokenHash()); - Assert.assertNull(idToken.getCodeHash()); + Assertions.assertNull(idToken.getAccessTokenHash()); + Assertions.assertNull(idToken.getCodeHash()); // Validate if token_type is null - Assert.assertNull(authzResponse.getTokenType()); + Assertions.assertNull(authzResponse.getTokenType()); // Validate if expires_in is null - Assert.assertNull(authzResponse.getExpiresIn()); + Assertions.assertNull(authzResponse.getExpiresIn()); return Collections.singletonList(idToken); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCImplicitResponseTypeIDTokenTokenTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCImplicitResponseTypeIDTokenTokenTest.java index 86e041f0a87b..613d48ed8ed9 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCImplicitResponseTypeIDTokenTokenTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oidc/flows/OIDCImplicitResponseTypeIDTokenTokenTest.java @@ -24,11 +24,11 @@ import org.keycloak.protocol.oidc.utils.OIDCResponseType; import org.keycloak.representations.IDToken; import org.keycloak.representations.idm.EventRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.oauth.AuthorizationEndpointResponse; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * Tests with response_type=id_token token @@ -53,9 +53,9 @@ protected boolean isFragment() { protected List testAuthzResponseAndRetrieveIDTokens(AuthorizationEndpointResponse authzResponse, EventRepresentation loginEvent) { - Assert.assertEquals(OIDCResponseType.ID_TOKEN + " " + OIDCResponseType.TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); + Assertions.assertEquals(OIDCResponseType.ID_TOKEN + " " + OIDCResponseType.TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE)); - Assert.assertNotNull(authzResponse.getAccessToken()); + Assertions.assertNotNull(authzResponse.getAccessToken()); String idTokenStr = authzResponse.getIdToken(); IDToken idToken = oauth.verifyIDToken(idTokenStr); @@ -63,13 +63,13 @@ protected List testAuthzResponseAndRetrieveIDTokens(AuthorizationEndpoi assertValidAccessTokenHash(idToken.getAccessTokenHash(), authzResponse.getAccessToken()); // Validate "c_hash" - Assert.assertNull(idToken.getCodeHash()); + Assertions.assertNull(idToken.getCodeHash()); // Validate if token_type is present - Assert.assertNotNull(authzResponse.getTokenType()); + Assertions.assertNotNull(authzResponse.getTokenType()); // Validate if expires_in is present - Assert.assertNotNull(authzResponse.getExpiresIn()); + Assertions.assertNotNull(authzResponse.getExpiresIn()); return Collections.singletonList(idToken); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/account/OrganizationAccountTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/account/OrganizationAccountTest.java index 527b219439da..307826e4863b 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/account/OrganizationAccountTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/account/OrganizationAccountTest.java @@ -40,10 +40,10 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; public class OrganizationAccountTest extends AbstractOrganizationTest { @@ -76,17 +76,17 @@ public void testFailUnlinkIdentityProvider() throws IOException { AdminApiUtil.resetUserPassword(realmsResouce().realm(bc.consumerRealmName()).users().get(user.getId()), bc.getUserPassword(), false); LinkedAccountRepresentation link = findLinkedAccount(bc.getIDPAlias()); - Assert.assertNotNull(link); + Assertions.assertNotNull(link); try (SimpleHttpResponse response = SimpleHttpDefault.doDelete(getAccountUrl("linked-accounts/" + link.getProviderAlias()), client).auth(tokenUtil.getToken()).acceptJson().asResponse()) { - Assert.assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + Assertions.assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus()); ErrorRepresentation error = response.asJson(ErrorRepresentation.class); - Assert.assertEquals("You cannot remove the link to an identity provider associated with an organization.", error.getErrorMessage()); + Assertions.assertEquals("You cannot remove the link to an identity provider associated with an organization.", error.getErrorMessage()); } // broker no longer linked to the organization organization.identityProviders().get(bc.getIDPAlias()).delete().close(); try (SimpleHttpResponse response = SimpleHttpDefault.doDelete(getAccountUrl("linked-accounts/" + link.getProviderAlias()), client).auth(tokenUtil.getToken()).acceptJson().asResponse()) { - Assert.assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus()); + Assertions.assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus()); } } @@ -99,18 +99,18 @@ public void testGetOrganizations() throws Exception { testRealm().organizations().get(orgB.getId()).members().addMember(member.getId()).close(); List organizations = getOrganizations(); - Assert.assertEquals(2, organizations.size()); + Assertions.assertEquals(2, organizations.size()); OrganizationRepresentation organization = organizations.stream() .filter(o -> orgA.getId().equals(o.getId())) .findAny() .orElse(null); - Assert.assertNotNull(organization); - Assert.assertEquals(orgA.getId(), organization.getId()); - Assert.assertEquals(orgA.getAlias(), organization.getAlias()); - Assert.assertEquals(orgA.getName(), organization.getName()); - Assert.assertEquals(orgA.getDescription(), organization.getDescription()); - Assert.assertEquals(orgA.getDomains().size(), organization.getDomains().size()); - Assert.assertTrue(organization.getDomains().containsAll(orgA.getDomains().stream().map(OrganizationDomainRepresentation::getName).toList())); + Assertions.assertNotNull(organization); + Assertions.assertEquals(orgA.getId(), organization.getId()); + Assertions.assertEquals(orgA.getAlias(), organization.getAlias()); + Assertions.assertEquals(orgA.getName(), organization.getName()); + Assertions.assertEquals(orgA.getDescription(), organization.getDescription()); + Assertions.assertEquals(orgA.getDomains().size(), organization.getDomains().size()); + Assertions.assertTrue(organization.getDomains().containsAll(orgA.getDomains().stream().map(OrganizationDomainRepresentation::getName).toList())); } private SortedSet linkedAccountsRep() throws IOException { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/AbstractOrganizationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/AbstractOrganizationTest.java index fb6af510a5a4..14e8ee4cb472 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/AbstractOrganizationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/AbstractOrganizationTest.java @@ -41,7 +41,6 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.testsuite.AbstractAdminTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.admin.Users; import org.keycloak.testsuite.broker.BrokerConfiguration; @@ -57,16 +56,17 @@ import org.hamcrest.Matchers; import org.jboss.arquillian.graphene.page.Page; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Pedro Igor @@ -245,8 +245,8 @@ protected void loginOrgIdp(String username, String email, boolean firstTimeLogin if (firstTimeLogin) { waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); - assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); assertFalse(driver.getPageSource().contains("kc.org")); updateAccountInformationPage.updateAccountInformation(username, email, "Firstname", "Lastname"); @@ -267,7 +267,7 @@ protected void loginOrgIdp(String username, String email, boolean firstTimeLogin protected void assertIsMember(String userEmail, OrganizationResource organization) { UserRepresentation account = getUserRepresentation(userEmail); UserRepresentation member = organization.members().member(account.getId()).toRepresentation(); - Assert.assertEquals(account.getId(), member.getId()); + Assertions.assertEquals(account.getId(), member.getId()); } protected UserRepresentation getUserRepresentation(String userEmail) { @@ -278,7 +278,7 @@ protected UserRepresentation getUserRepresentation(String realm, String userEmai UsersResource users = adminClient.realm(realm).users(); List reps = users.searchByEmail(userEmail, true); assertFalse(reps.isEmpty()); - Assert.assertEquals(1, reps.size()); + Assertions.assertEquals(1, reps.size()); return reps.get(0); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/IdentityProviderThemeConfigTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/IdentityProviderThemeConfigTest.java index 76b084484b90..03375b50667e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/IdentityProviderThemeConfigTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/IdentityProviderThemeConfigTest.java @@ -5,9 +5,9 @@ import org.keycloak.testsuite.AbstractAdminTest; import org.keycloak.testsuite.util.IdentityProviderBuilder; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; public class IdentityProviderThemeConfigTest extends AbstractAdminTest { @@ -32,7 +32,7 @@ public void testIdentityProviderThemeConfigs() { oauth.realm(TEST_REALM_NAME); oauth.openLoginForm(); String pageSource = driver.getPageSource(); - Assert.assertTrue(pageSource.contains("This value is shown in the Keycloak theme")); - Assert.assertFalse(pageSource.contains("This value is not shown in the Keycloak theme")); + Assertions.assertTrue(pageSource.contains("This value is shown in the Keycloak theme")); + Assertions.assertFalse(pageSource.contains("This value is not shown in the Keycloak theme")); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/OrganizationInvitationLinkTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/OrganizationInvitationLinkTest.java index c211f3e5c60c..cb5e5ff03d11 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/OrganizationInvitationLinkTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/OrganizationInvitationLinkTest.java @@ -49,7 +49,6 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.testsuite.AbstractAuthenticationTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.authentication.PushButtonAuthenticatorFactory; import org.keycloak.testsuite.pages.InfoPage; @@ -71,6 +70,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import static org.keycloak.representations.idm.OrganizationInvitationRepresentation.Status.EXPIRED; @@ -236,7 +236,7 @@ public void testInviteNewUserRegistrationWithAccountClientCustomBaseUrl() throws List users = testRealm().users().searchByEmail(email, true); assertThat(users, not(empty())); MemberRepresentation member = organization.members().member(users.get(0).getId()).toRepresentation(); - Assert.assertNotNull(member); + Assertions.assertNotNull(member); assertThat(member.getMembershipType(), equalTo(MembershipType.MANAGED)); getCleanup().addCleanup(() -> testRealm().users().get(users.get(0).getId()).remove()); @@ -259,13 +259,13 @@ public void testInviteNewUserRegistration() throws IOException, MessagingExcepti assertThat(users, not(empty())); // user is a member MemberRepresentation member = organization.members().member(users.get(0).getId()).toRepresentation(); - Assert.assertNotNull(member); + Assertions.assertNotNull(member); assertThat(member.getMembershipType(), equalTo(MembershipType.MANAGED)); getCleanup().addCleanup(() -> testRealm().users().get(users.get(0).getId()).remove()); // authenticated to the account console - Assert.assertTrue(driver.getPageSource().contains("Account Management")); - Assert.assertNotNull(driver.manage().getCookieNamed(CookieType.IDENTITY.getName())); + Assertions.assertTrue(driver.getPageSource().contains("Account Management")); + Assertions.assertNotNull(driver.manage().getCookieNamed(CookieType.IDENTITY.getName())); } @Test @@ -336,13 +336,13 @@ public void testInviteNewUserRegistrationCustomRegistrationFlow() throws IOExcep assertThat(users, not(empty())); // user is a member MemberRepresentation member = organization.members().member(users.get(0).getId()).toRepresentation(); - Assert.assertNotNull(member); + Assertions.assertNotNull(member); assertThat(member.getMembershipType(), equalTo(MembershipType.MANAGED)); getCleanup().addCleanup(() -> testRealm().users().get(users.get(0).getId()).remove()); // authenticated to the account console - Assert.assertTrue(driver.getPageSource().contains("Account Management")); - Assert.assertNotNull(driver.manage().getCookieNamed(CookieType.IDENTITY.getName())); + Assertions.assertTrue(driver.getPageSource().contains("Account Management")); + Assertions.assertNotNull(driver.manage().getCookieNamed(CookieType.IDENTITY.getName())); } @Test @@ -364,7 +364,7 @@ public void testInviteNewUserRegistrationCustomRedirectUrl() throws IOException, assertThat(users, not(empty())); // user is a member MemberRepresentation member = organization.members().member(users.get(0).getId()).toRepresentation(); - Assert.assertNotNull(member); + Assertions.assertNotNull(member); assertThat(member.getMembershipType(), equalTo(MembershipType.MANAGED)); getCleanup().addCleanup(() -> testRealm().users().get(users.get(0).getId()).remove()); @@ -387,8 +387,8 @@ public void testRegistrationEnabledWhenInvitingNewUser() throws Exception { registerUser(organization, email); // authenticated to the account console - Assert.assertTrue(driver.getPageSource().contains("Account Management")); - Assert.assertNotNull(driver.manage().getCookieNamed(CookieType.IDENTITY.getName())); + Assertions.assertTrue(driver.getPageSource().contains("Account Management")); + Assertions.assertNotNull(driver.manage().getCookieNamed(CookieType.IDENTITY.getName())); List memberByEmail = organization.members().search(email, Boolean.TRUE, null, null); assertThat(memberByEmail, Matchers.hasSize(1)); @@ -419,15 +419,15 @@ public void testRegistrationEnabledWhenInvitingNewUserWithLocalization() throws String link = getInvitationLinkFromEmail(); driver.navigate().to(link); - Assert.assertFalse(organization.members().list(-1, -1).stream().anyMatch(actual -> email.equals(actual.getEmail()))); + Assertions.assertFalse(organization.members().list(-1, -1).stream().anyMatch(actual -> email.equals(actual.getEmail()))); registerPage.assertCurrent(organizationName); registerPage.openLanguage("Portuguese"); - Assert.assertTrue(driver.getPageSource().contains("Campos obrigatórios")); + Assertions.assertTrue(driver.getPageSource().contains("Campos obrigatórios")); registerPage.register("firstName", "lastName", email, "invitedUser", "password", "password", null, false, null); // authenticated to the account console - Assert.assertTrue(driver.getPageSource().contains("Account Management")); - Assert.assertNotNull(driver.manage().getCookieNamed(CookieType.IDENTITY.getName())); + Assertions.assertTrue(driver.getPageSource().contains("Account Management")); + Assertions.assertNotNull(driver.manage().getCookieNamed(CookieType.IDENTITY.getName())); List memberByEmail = organization.members().search(email, Boolean.TRUE, null, null); assertThat(memberByEmail, Matchers.hasSize(1)); @@ -464,8 +464,8 @@ private UserRepresentation createUser(String invitedWithMatchingEmail, String ma private String getInvitationLinkFromEmail(String ...parameters) throws MessagingException, IOException { MimeMessage message = greenMail.getLastReceivedMessage(); - Assert.assertNotNull(message); - Assert.assertEquals("Invitation to join the " + organizationName + " organization", message.getSubject()); + Assertions.assertNotNull(message); + Assertions.assertEquals("Invitation to join the " + organizationName + " organization", message.getSubject()); EmailBody body = MailUtils.getBody(message); String text = body.getHtml(); @@ -482,7 +482,7 @@ private String getInvitationLinkFromEmail(String ...parameters) throws Messaging assertThat(text, Matchers.containsString(("

If you don't want to join the organization, just ignore this message.

"))); String orgToken = UriUtils.parseQueryParameters(link, false).values().stream().map(strings -> strings.get(0)).findFirst().orElse(null); - Assert.assertNotNull(orgToken); + Assertions.assertNotNull(orgToken); return link; } @@ -519,7 +519,7 @@ private void registerUser(OrganizationResource organization, String email) throw private void registerUser(OrganizationResource organization, String expectedEmail, String email) throws MessagingException, IOException { String link = getInvitationLinkFromEmail(); driver.navigate().to(link); - Assert.assertFalse(organization.members().list(-1, -1).stream().anyMatch(actual -> email.equals(actual.getEmail()))); + Assertions.assertFalse(organization.members().list(-1, -1).stream().anyMatch(actual -> email.equals(actual.getEmail()))); registerPage.assertCurrent(organizationName); assertThat(registerPage.getEmail(), equalTo(expectedEmail)); registerPage.register("firstName", "lastName", email, @@ -534,7 +534,7 @@ private void acceptInvitation(OrganizationResource organization, UserRepresentat String link = getInvitationLinkFromEmail(user.getFirstName(), user.getLastName()); driver.navigate().to(link); // not yet a member - Assert.assertFalse(organization.members().list(-1, -1).stream().anyMatch(actual -> user.getId().equals(actual.getId()))); + Assertions.assertFalse(organization.members().list(-1, -1).stream().anyMatch(actual -> user.getId().equals(actual.getId()))); // confirm the intent of membership assertThat(driver.getPageSource(), containsString("You are about to join organization " + organizationName)); assertThat(infoPage.getInfo(), containsString("By clicking on the link below, you will become a member of the " + organizationName + " organization:")); @@ -542,7 +542,7 @@ private void acceptInvitation(OrganizationResource organization, UserRepresentat // redirect to the redirectUrl and eventually force the user to authenticate if not already assertThat(driver.getTitle(), containsString(pageTitle)); // now a member - Assert.assertNotNull(organization.members().member(user.getId()).toRepresentation()); + Assertions.assertNotNull(organization.members().member(user.getId()).toRepresentation()); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/OrganizationInvitationManagementTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/OrganizationInvitationManagementTest.java index 358e1959f069..2e1b566ac1a1 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/OrganizationInvitationManagementTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/OrganizationInvitationManagementTest.java @@ -46,7 +46,7 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Integration tests for Organization Invitation Management functionality diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/OrganizationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/OrganizationTest.java index 73cd596c6111..8b8c306c704c 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/OrganizationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/OrganizationTest.java @@ -50,8 +50,8 @@ import org.keycloak.testsuite.updaters.RealmAttributeUpdater; import org.keycloak.testsuite.util.RealmBuilder; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; @@ -64,12 +64,12 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class OrganizationTest extends AbstractOrganizationTest { @@ -135,7 +135,7 @@ public void testGetAll() { List existing = testRealm().organizations().list(-1, -1); assertFalse(existing.isEmpty()); assertThat(existing, containsInAnyOrder(expected.toArray())); - Assert.assertTrue(existing.stream().map(OrganizationRepresentation::getAttributes).filter(Objects::nonNull).findAny().isEmpty()); + Assertions.assertTrue(existing.stream().map(OrganizationRepresentation::getAttributes).filter(Objects::nonNull).findAny().isEmpty()); List concatenatedList = Stream.of( testRealm().organizations().list(0, 5), @@ -508,8 +508,8 @@ public void testWithoutDomains() { .filter(org -> org.getId().equals(orgWithoutDomainsId)) .findFirst(); - assertTrue("Organization with domains should be in the list", foundOrgWithDomains.isPresent()); - assertTrue("Organization without domains should be in the list", foundOrgWithoutDomains.isPresent()); + assertTrue(foundOrgWithDomains.isPresent(), "Organization with domains should be in the list"); + assertTrue(foundOrgWithoutDomains.isPresent(), "Organization without domains should be in the list"); assertThat("Organization with domains should have domains", foundOrgWithDomains.get().getDomains(), is(notNullValue())); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/OrganizationThemeTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/OrganizationThemeTest.java index 9a6628e10424..64ce892e9c28 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/OrganizationThemeTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/admin/OrganizationThemeTest.java @@ -40,9 +40,9 @@ import org.hamcrest.Matchers; import org.jboss.arquillian.graphene.page.Page; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; @@ -87,10 +87,10 @@ public void testOrganizationOnRegularLogin() { // organization available to regular login page loginPage.open(bc.consumerRealmName()); - Assert.assertTrue(driver.getPageSource().contains("Sign-in to the realm")); + Assertions.assertTrue(driver.getPageSource().contains("Sign-in to the realm")); loginPage.loginUsername("tom@myorg.com"); - Assert.assertTrue(driver.getPageSource().contains("Sign-in to myorg organization")); - Assert.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(driver.getPageSource().contains("Sign-in to myorg organization")); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); } @Test @@ -102,11 +102,11 @@ public void testOrganizationOnIdentityFirstLogin() { // organization available to identity-first login page loginPage.open(bc.consumerRealmName()); - Assert.assertTrue(driver.getPageSource().contains("Sign-in to the realm")); - Assert.assertFalse(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(driver.getPageSource().contains("Sign-in to the realm")); + Assertions.assertFalse(loginPage.isPasswordInputPresent()); loginPage.loginUsername("non-user@myorg.com"); - Assert.assertTrue(driver.getPageSource().contains("Sign-in to myorg organization")); - Assert.assertFalse(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(driver.getPageSource().contains("Sign-in to myorg organization")); + Assertions.assertFalse(loginPage.isPasswordInputPresent()); } @Test @@ -127,13 +127,13 @@ public void testOrganizationOnIdPReview() { loginPage.open(bc.consumerRealmName()); loginPage.loginUsername("tom@myorg.com"); waitForPage(driver, "sign in to", true); - Assert.assertTrue("Driver should be on the provider realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"), + "Driver should be on the provider realm page right now"); loginPage.login(user.getUsername(), "password"); waitForPage(driver, "update account information", false); - Assert.assertTrue("Driver should be on the consumer realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); - Assert.assertTrue(driver.getPageSource().contains("Sign-in to myorg organization")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "Driver should be on the consumer realm page right now"); + Assertions.assertTrue(driver.getPageSource().contains("Sign-in to myorg organization")); } @Test @@ -154,12 +154,12 @@ public void testOrganizationOnUpdateProfile() { oauth.clientId("broker-app"); loginPage.open(bc.consumerRealmName()); loginPage.loginUsername("tom"); - Assert.assertTrue(driver.getPageSource().contains("Sign-in to myorg organization")); + Assertions.assertTrue(driver.getPageSource().contains("Sign-in to myorg organization")); loginPage.login("password"); waitForPage(driver, "update account information", false); - Assert.assertTrue("Driver should be on the consumer realm page right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); - Assert.assertTrue(driver.getPageSource().contains("Sign-in to myorg organization")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "Driver should be on the consumer realm page right now"); + Assertions.assertTrue(driver.getPageSource().contains("Sign-in to myorg organization")); } @Test @@ -172,14 +172,14 @@ public void testOrganizationAttributes() { // organization available to identity-first login page loginPage.open(bc.consumerRealmName()); - Assert.assertTrue(driver.getPageSource().contains("Sign-in to the realm")); - Assert.assertFalse(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(driver.getPageSource().contains("Sign-in to the realm")); + Assertions.assertFalse(loginPage.isPasswordInputPresent()); loginPage.loginUsername("non-user@myorg.com"); - Assert.assertTrue(driver.getPageSource().contains("Sign-in to myorg organization")); + Assertions.assertTrue(driver.getPageSource().contains("Sign-in to myorg organization")); for (Entry> attribute : orgRep.getAttributes().entrySet()) { assertThat(driver.getPageSource(), Matchers.containsString("The " + attribute.getKey() + " is " + String.join(", ", attribute.getValue()))); } - Assert.assertFalse(loginPage.isPasswordInputPresent()); + Assertions.assertFalse(loginPage.isPasswordInputPresent()); } @Test @@ -208,8 +208,8 @@ public void testUserIsMember() { // organization available to identity-first login page loginPage.open(bc.consumerRealmName()); loginPage.loginUsername(user.getEmail()); - Assert.assertTrue(driver.getPageSource().contains("Sign-in to myorg organization")); - Assert.assertTrue(driver.getPageSource().contains("User is member of " + orgRep.getName())); - Assert.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(driver.getPageSource().contains("Sign-in to myorg organization")); + Assertions.assertTrue(driver.getPageSource().contains("User is member of " + orgRep.getName())); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/authentication/OrganizationAuthenticationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/authentication/OrganizationAuthenticationTest.java index f45c75033cef..743ad816a620 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/authentication/OrganizationAuthenticationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/authentication/OrganizationAuthenticationTest.java @@ -32,7 +32,6 @@ import org.keycloak.representations.idm.OrganizationRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.organization.admin.AbstractOrganizationTest; @@ -44,12 +43,13 @@ import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class OrganizationAuthenticationTest extends AbstractOrganizationTest { @@ -61,9 +61,9 @@ public void testAuthenticateUnmanagedMember() { // first try to log in using only the email openIdentityFirstLoginPage(member.getEmail(), false, null, false, false); - Assert.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); // no idp should be shown because there is only a single idp that is bound to an organization - Assert.assertFalse(loginPage.isSocialButtonPresent(bc.getIDPAlias())); + Assertions.assertFalse(loginPage.isSocialButtonPresent(bc.getIDPAlias())); // the member should be able to log in using the credentials loginPage.login(memberPassword); @@ -78,7 +78,7 @@ public void testTryLoginWithUsernameNotAnEmail() { // check if the login page is shown loginPage.assertAttemptedUsernameAvailability(true); - Assert.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); } @Test @@ -87,7 +87,7 @@ public void testEmptyUserNameValidation() { oauth.clientId("broker-app"); loginPage.open(bc.consumerRealmName()); - Assert.assertFalse(loginPage.isPasswordInputPresent()); + Assertions.assertFalse(loginPage.isPasswordInputPresent()); loginPage.loginUsername(""); assertEquals("Invalid username.", loginPage.getUsernameInputError()); @@ -101,7 +101,7 @@ public void testDefaultAuthenticationMechanismIfNotOrganizationMember() { // check if the login page is shown loginPage.assertAttemptedUsernameAvailability(true); - Assert.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); } @Test @@ -112,8 +112,8 @@ public void testAuthenticateUnmanagedMemberWhenProviderDisabled() throws IOExcep // first try to access login page oauth.clientId("broker-app"); loginPage.open(bc.consumerRealmName()); - Assert.assertFalse(loginPage.isPasswordInputPresent()); - Assert.assertFalse(loginPage.isSocialButtonPresent(bc.getIDPAlias())); + Assertions.assertFalse(loginPage.isPasswordInputPresent()); + Assertions.assertFalse(loginPage.isSocialButtonPresent(bc.getIDPAlias())); // disable the organization provider try (RealmAttributeUpdater rau = new RealmAttributeUpdater(testRealm()) @@ -126,9 +126,9 @@ public void testAuthenticateUnmanagedMemberWhenProviderDisabled() throws IOExcep waitForPage(driver, "sign in to", true); assertThat("Driver should be on the consumer realm page right now", driver.getCurrentUrl(), Matchers.containsString("/auth/realms/" + bc.consumerRealmName() + "/")); - Assert.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); // no idp should be shown because there is only a single idp that is bound to an organization - Assert.assertFalse(loginPage.isSocialButtonPresent(bc.getIDPAlias())); + Assertions.assertFalse(loginPage.isSocialButtonPresent(bc.getIDPAlias())); // the member should be able to log in using the credentials loginPage.login(member.getEmail(), memberPassword); @@ -292,11 +292,11 @@ public void testRestartLogin() { // check if the login page is shown loginPage.assertAttemptedUsernameAvailability(true); - Assert.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); loginPage.clickResetLogin(); - Assert.assertTrue(loginPage.isUsernameInputPresent()); - Assert.assertFalse(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(loginPage.isUsernameInputPresent()); + Assertions.assertFalse(loginPage.isPasswordInputPresent()); } @Test @@ -307,13 +307,13 @@ public void testAttemptedUsernameKeptAfterPasswordFailures() { // check if the login page is shown loginPage.assertAttemptedUsernameAvailability(true); - Assert.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); for (int i = 0; i < 3; i++) { loginPage.login("wrong-password"); loginPage.assertAttemptedUsernameAvailability(true); - Assert.assertFalse(loginPage.isEmailInputPresent()); - Assert.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertFalse(loginPage.isEmailInputPresent()); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); } } @@ -339,26 +339,26 @@ public void testHideUsernameKeptAfterPasswordFailuresBruteForceEnabled() { createUser(realm.getRealm(), "existing-user", memberPassword, "John", "Doe", email); openIdentityFirstLoginPage(email, false, null, false, false); loginPage.assertAttemptedUsernameAvailability(true); - Assert.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); loginPage.login("wrong-password"); loginPage.assertAttemptedUsernameAvailability(true); - Assert.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); loginPage.login("wrong-password"); loginPage.assertAttemptedUsernameAvailability(true); - Assert.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); openIdentityFirstLoginPage(email, false, null, false, false); realm.setRegistrationEmailAsUsername(true); testRealm().update(realm); loginPage.login("wrong-password"); loginPage.assertAttemptedUsernameAvailability(true); - Assert.assertFalse(loginPage.isEmailInputPresent()); - Assert.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertFalse(loginPage.isEmailInputPresent()); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); loginPage.login("wrong-password"); loginPage.assertAttemptedUsernameAvailability(true); - Assert.assertFalse(loginPage.isEmailInputPresent()); - Assert.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertFalse(loginPage.isEmailInputPresent()); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); } @Test @@ -384,7 +384,7 @@ public void testUsernameExposureWhenEnteringEmail() { loginPage.assertAttemptedUsernameAvailability(true); String displayedUsername = loginPage.getAttemptedUsername(); - assertEquals("Entering email should not expose actual username", member.getEmail(), displayedUsername); + assertEquals(member.getEmail(), displayedUsername, "Entering email should not expose actual username"); // Enter email with different case (should still work with case-insensitive comparison) String upperCaseEmail = member.getEmail().toUpperCase(); @@ -392,9 +392,9 @@ public void testUsernameExposureWhenEnteringEmail() { loginPage.assertAttemptedUsernameAvailability(true); String displayedUsernameUpper = loginPage.getAttemptedUsername(); - assertEquals("Should show what user entered (uppercase email)", upperCaseEmail, displayedUsernameUpper); + assertEquals(upperCaseEmail, displayedUsernameUpper, "Should show what user entered (uppercase email)"); - Assert.assertTrue("Password input should be present", loginPage.isPasswordInputPresent()); + Assertions.assertTrue(loginPage.isPasswordInputPresent(), "Password input should be present"); // Clean up testRealm().users().get(memberId).remove(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/broker/AbstractBrokerSelfRegistrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/broker/AbstractBrokerSelfRegistrationTest.java index a5b65260d992..02e6d2b7f2be 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/broker/AbstractBrokerSelfRegistrationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/broker/AbstractBrokerSelfRegistrationTest.java @@ -39,7 +39,6 @@ import org.keycloak.representations.idm.OrganizationDomainRepresentation; import org.keycloak.representations.idm.OrganizationRepresentation; import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.organization.admin.AbstractOrganizationTest; @@ -49,17 +48,18 @@ import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.models.OrganizationDomainModel.ANY_DOMAIN; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public abstract class AbstractBrokerSelfRegistrationTest extends AbstractOrganizationTest { @@ -78,7 +78,7 @@ public void testLoginHintSentToBrokerWhenEnabled() { openIdentityFirstLoginPage(bc.getUserEmail(), true, null, false,false); // check if the username is automatically filled - Assert.assertEquals(bc.getUserEmail(), loginPage.getUsername()); + Assertions.assertEquals(bc.getUserEmail(), loginPage.getUsername()); } @Test @@ -114,12 +114,12 @@ public void testIdentityFirstIfUserNotExistsAndEmailMatchOrgDomain() { openIdentityFirstLoginPage("user@neworg.org", false, null, false, false); - Assert.assertTrue(loginPage.isUsernameInputPresent()); + Assertions.assertTrue(loginPage.isUsernameInputPresent()); // registration link shown - Assert.assertTrue(loginPage.isRegisterLinkPresent()); + Assertions.assertTrue(loginPage.isRegisterLinkPresent()); // no need for password because the user does not exist - Assert.assertFalse(loginPage.isPasswordInputPresent()); - Assert.assertFalse(loginPage.isSocialButtonPresent(idpRep.getAlias())); + Assertions.assertFalse(loginPage.isPasswordInputPresent()); + Assertions.assertFalse(loginPage.isSocialButtonPresent(idpRep.getAlias())); } @Test @@ -132,13 +132,13 @@ public void testIdentityFirstUserNotExistEmailMatchBrokerDomainAndBrokerIsPublic openIdentityFirstLoginPage("user@neworg.org", false, null, false, false); - Assert.assertEquals("Your email domain matches an organization but you don't have an account yet.", loginPage.getError()); - Assert.assertTrue(loginPage.isUsernameInputPresent()); - Assert.assertFalse(loginPage.isPasswordInputPresent()); - Assert.assertTrue(loginPage.isSocialButtonPresent(idpRep.getAlias())); + Assertions.assertEquals("Your email domain matches an organization but you don't have an account yet.", loginPage.getError()); + Assertions.assertTrue(loginPage.isUsernameInputPresent()); + Assertions.assertFalse(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(loginPage.isSocialButtonPresent(idpRep.getAlias())); // no self-registration link because the user should register through the broker - Assert.assertFalse(loginPage.isRegisterLinkPresent()); + Assertions.assertFalse(loginPage.isRegisterLinkPresent()); } @Test @@ -151,11 +151,11 @@ public void testIdentityFirstUserNotExistEmailMatchBrokerDomainNoPublicBroker() openIdentityFirstLoginPage("user@neworg.org", false, null, false, false); - Assert.assertTrue(driver.getPageSource().contains("Your email domain matches an organization but you don't have an account yet.")); - Assert.assertTrue(loginPage.isUsernameInputPresent()); - Assert.assertFalse(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(driver.getPageSource().contains("Your email domain matches an organization but you don't have an account yet.")); + Assertions.assertTrue(loginPage.isUsernameInputPresent()); + Assertions.assertFalse(loginPage.isPasswordInputPresent()); // self-registration link shown because there is no public broker and user can choose to register - Assert.assertTrue(loginPage.isRegisterLinkPresent()); + Assertions.assertTrue(loginPage.isRegisterLinkPresent()); } @Test @@ -182,16 +182,16 @@ public void testDefaultAuthenticationShowsPublicOrganizationBrokers() { openIdentityFirstLoginPage("external@user.org", false, idp.getAlias(), false, false); - Assert.assertTrue(loginPage.isPasswordInputPresent()); - Assert.assertFalse(loginPage.isSocialButtonPresent(bc.getIDPAlias())); - Assert.assertTrue(loginPage.isSocialButtonPresent(idp.getAlias())); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertFalse(loginPage.isSocialButtonPresent(bc.getIDPAlias())); + Assertions.assertTrue(loginPage.isSocialButtonPresent(idp.getAlias())); idp.setHideOnLogin(true); testRealm().identityProviders().get(idp.getAlias()).update(idp); driver.navigate().refresh(); - Assert.assertTrue(loginPage.isPasswordInputPresent()); - Assert.assertFalse(loginPage.isSocialButtonPresent(bc.getIDPAlias())); - Assert.assertFalse(loginPage.isSocialButtonPresent(idp.getAlias())); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertFalse(loginPage.isSocialButtonPresent(bc.getIDPAlias())); + Assertions.assertFalse(loginPage.isSocialButtonPresent(idp.getAlias())); } @Test @@ -210,7 +210,7 @@ public void testDefaultAuthenticationWhenUserExistEmailMatchOrgDomain() { openIdentityFirstLoginPage("user@neworg.org", false, null, false, false); - Assert.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); } @Test @@ -221,8 +221,8 @@ public void testRealmLevelBrokersAvailableIfEmailDoesNotMatchOrganization() { // check if the login page is shown loginPage.assertAttemptedUsernameAvailability(true); - Assert.assertTrue(loginPage.isPasswordInputPresent()); - Assert.assertFalse(loginPage.isSocialButtonPresent(bc.getIDPAlias())); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertFalse(loginPage.isSocialButtonPresent(bc.getIDPAlias())); IdentityProviderRepresentation idp = bc.setUpIdentityProvider(); idp.setAlias("realm-level-idp"); @@ -232,9 +232,9 @@ public void testRealmLevelBrokersAvailableIfEmailDoesNotMatchOrganization() { driver.navigate().refresh(); loginPage.assertAttemptedUsernameAvailability(true); - Assert.assertTrue(loginPage.isPasswordInputPresent()); - Assert.assertTrue(loginPage.isSocialButtonPresent(idp.getAlias())); - Assert.assertFalse(loginPage.isSocialButtonPresent(bc.getIDPAlias())); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(loginPage.isSocialButtonPresent(idp.getAlias())); + Assertions.assertFalse(loginPage.isSocialButtonPresent(bc.getIDPAlias())); } @Test @@ -423,7 +423,7 @@ public void testRedirectManagedMemberUsingUnManagedMemberAllOrganizationsScope() updateAccountInformationPage.assertCurrent(); // should enforce a email with the same domain as the organization updateAccountInformationPage.updateAccountInformation(email, email, "f", "l"); - Assert.assertTrue(driver.getPageSource().contains("Email domain does not match any domain from the organization")); + Assertions.assertTrue(driver.getPageSource().contains("Email domain does not match any domain from the organization")); updateAccountInformationPage.updateAccountInformation(email, orgBEmail, "f", "l"); // user is asked to link accounts @@ -539,7 +539,7 @@ private void assertOrganizationBrokerVisibilityWhenUserIsLinkedElsewhere(boolean String email = bc.getUserEmail(); loginPage.loginUsername(email); // second-idp shown because user is not linked yet to any broker - Assert.assertTrue(loginPage.isSocialButtonPresent(secondIdp.getAlias())); + Assertions.assertTrue(loginPage.isSocialButtonPresent(secondIdp.getAlias())); brokerRep.getConfig().put(IdentityProviderRedirectMode.EMAIL_MATCH.getKey(), Boolean.TRUE.toString()); testRealm().identityProviders().get(brokerRep.getAlias()).update(brokerRep); @@ -560,10 +560,11 @@ private void assertOrganizationBrokerVisibilityWhenUserIsLinkedElsewhere(boolean loginPage.open(bc.consumerRealmName()); log.debug("Logging in"); loginPage.loginUsername(email); - Assert.assertFalse(loginPage.isUsernameInputPresent()); - Assert.assertTrue(loginPage.isPasswordInputPresent()); - Assert.assertTrue(loginPage.isSocialButtonPresent(bc.getIDPAlias())); - Assert.assertEquals(showWhenLinkedElsewhere, loginPage.isSocialButtonPresent(secondIdp.getAlias())); + + Assertions.assertFalse(loginPage.isUsernameInputPresent()); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(loginPage.isSocialButtonPresent(bc.getIDPAlias())); + Assertions.assertEquals(showWhenLinkedElsewhere, loginPage.isSocialButtonPresent(secondIdp.getAlias())); } @Test @@ -613,9 +614,9 @@ public void testShowWhenLinkedElsewhereEdgeCases() { oauth.clientId("broker-app"); loginPage.open(bc.consumerRealmName()); loginPage.loginUsername(username); - Assert.assertTrue(loginPage.isSocialButtonPresent(orgABroker.getAlias())); - Assert.assertTrue(loginPage.isSocialButtonPresent(orgBBroker.getAlias())); - Assert.assertFalse(loginPage.isSocialButtonPresent(hideUnknownAlias)); + Assertions.assertTrue(loginPage.isSocialButtonPresent(orgABroker.getAlias())); + Assertions.assertTrue(loginPage.isSocialButtonPresent(orgBBroker.getAlias())); + Assertions.assertFalse(loginPage.isSocialButtonPresent(hideUnknownAlias)); String resolvedEmail = username + "@org-a.org"; UserRepresentation updatedAccount = testRealm().users().get(account.getId()).toRepresentation(); updatedAccount.setEmail(resolvedEmail); @@ -644,9 +645,9 @@ public void testShowWhenLinkedElsewhereEdgeCases() { orgA.identityProviders().addIdentityProvider(linkOnlyAlias).close(); loginPage.open(bc.consumerRealmName()); loginPage.loginUsername(resolvedEmail); - Assert.assertTrue(loginPage.isSocialButtonPresent(hideUnknownAlias)); - Assert.assertFalse(loginPage.isSocialButtonPresent(disabledAlias)); - Assert.assertFalse(loginPage.isSocialButtonPresent(linkOnlyAlias)); + Assertions.assertTrue(loginPage.isSocialButtonPresent(hideUnknownAlias)); + Assertions.assertFalse(loginPage.isSocialButtonPresent(disabledAlias)); + Assertions.assertFalse(loginPage.isSocialButtonPresent(linkOnlyAlias)); } @Test @@ -672,9 +673,9 @@ public void testNoIDPRedirectWhenUserHasCredentialsSet() { loginPage.loginUsername(bc.getUserEmail()); // after providing username/email, user can pick to authenticate by password or by org IDP - Assert.assertFalse(loginPage.isUsernameInputPresent()); - Assert.assertTrue(loginPage.isPasswordInputPresent()); - Assert.assertTrue(loginPage.isSocialButtonPresent(bc.getIDPAlias())); + Assertions.assertFalse(loginPage.isUsernameInputPresent()); + Assertions.assertTrue(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(loginPage.isSocialButtonPresent(bc.getIDPAlias())); // log in by password loginPage.login("updated-password"); @@ -850,18 +851,18 @@ public void testDoNotRedirectToIdentityProviderAssociatedWithOrganizationDomain( openIdentityFirstLoginPage(bc.getUserEmail(), false, idp.getAlias(), false, false); - Assert.assertFalse(loginPage.isPasswordInputPresent()); - Assert.assertTrue(driver.getPageSource().contains("Your email domain matches an organization but you don't have an account yet.")); - Assert.assertTrue(loginPage.isSocialButtonPresent(bc.getIDPAlias())); + Assertions.assertFalse(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(driver.getPageSource().contains("Your email domain matches an organization but you don't have an account yet.")); + Assertions.assertTrue(loginPage.isSocialButtonPresent(bc.getIDPAlias())); idp.getConfig().put(OrganizationModel.ORGANIZATION_DOMAIN_ATTRIBUTE, ANY_DOMAIN); testRealm().identityProviders().get(bc.getIDPAlias()).update(idp); openIdentityFirstLoginPage(bc.getUserEmail(), false, idp.getAlias(), false, false); - Assert.assertFalse(loginPage.isPasswordInputPresent()); - Assert.assertTrue(driver.getPageSource().contains("Your email domain matches an organization but you don't have an account yet.")); - Assert.assertTrue(loginPage.isSocialButtonPresent(bc.getIDPAlias())); + Assertions.assertFalse(loginPage.isPasswordInputPresent()); + Assertions.assertTrue(driver.getPageSource().contains("Your email domain matches an organization but you don't have an account yet.")); + Assertions.assertTrue(loginPage.isSocialButtonPresent(bc.getIDPAlias())); } @Test @@ -883,15 +884,15 @@ public void testOnlyShowBrokersAssociatedWithResolvedOrganization() { oauth.clientId("broker-app"); loginPage.open(bc.consumerRealmName()); loginPage.loginUsername("user@org-0.org"); - Assert.assertTrue(driver.getPageSource().contains("Your email domain matches an organization but you don't have an account yet.")); - Assert.assertTrue(loginPage.isSocialButtonPresent(org0Broker.getAlias())); - Assert.assertFalse(loginPage.isSocialButtonPresent(org1Broker.getAlias())); + Assertions.assertTrue(driver.getPageSource().contains("Your email domain matches an organization but you don't have an account yet.")); + Assertions.assertTrue(loginPage.isSocialButtonPresent(org0Broker.getAlias())); + Assertions.assertFalse(loginPage.isSocialButtonPresent(org1Broker.getAlias())); loginPage.open(bc.consumerRealmName()); loginPage.loginUsername("user@org-1.org"); - Assert.assertTrue(driver.getPageSource().contains("Your email domain matches an organization but you don't have an account yet.")); - Assert.assertTrue(loginPage.isSocialButtonPresent(org1Broker.getAlias())); - Assert.assertFalse(loginPage.isSocialButtonPresent(org0Broker.getAlias())); + Assertions.assertTrue(driver.getPageSource().contains("Your email domain matches an organization but you don't have an account yet.")); + Assertions.assertTrue(loginPage.isSocialButtonPresent(org1Broker.getAlias())); + Assertions.assertFalse(loginPage.isSocialButtonPresent(org0Broker.getAlias())); } @Test @@ -908,32 +909,32 @@ public void testDoNotShowBrokersIfOrganizationNotResolved() { oauth.clientId("broker-app"); loginPage.open(bc.consumerRealmName()); loginPage.loginUsername("user@unknowndomain.org"); - Assert.assertFalse(loginPage.isSocialButtonPresent(org0Broker.getAlias())); + Assertions.assertFalse(loginPage.isSocialButtonPresent(org0Broker.getAlias())); // show if organization can be resolved loginPage.open(bc.consumerRealmName()); loginPage.loginUsername("user@org-0.org"); - Assert.assertTrue(loginPage.isSocialButtonPresent(org0Broker.getAlias())); + Assertions.assertTrue(loginPage.isSocialButtonPresent(org0Broker.getAlias())); // show if the config is set to false org0Broker.getConfig().put(OrganizationModel.HIDE_IDP_ON_LOGIN_WHEN_ORGANIZATION_UNKNOWN, Boolean.FALSE.toString()); testRealm().identityProviders().get(org0Broker.getAlias()).update(org0Broker); loginPage.open(bc.consumerRealmName()); loginPage.loginUsername("user@unknowndomain.org"); - Assert.assertTrue(loginPage.isSocialButtonPresent(org0Broker.getAlias())); + Assertions.assertTrue(loginPage.isSocialButtonPresent(org0Broker.getAlias())); loginPage.open(bc.consumerRealmName()); loginPage.loginUsername("user@org-0.org"); - Assert.assertTrue(loginPage.isSocialButtonPresent(org0Broker.getAlias())); + Assertions.assertTrue(loginPage.isSocialButtonPresent(org0Broker.getAlias())); // hide if hide on login is set to true org0Broker.setHideOnLogin(true); testRealm().identityProviders().get(org0Broker.getAlias()).update(org0Broker); loginPage.open(bc.consumerRealmName()); loginPage.loginUsername("user@unknowndomain.org"); - Assert.assertFalse(loginPage.isSocialButtonPresent(org0Broker.getAlias())); + Assertions.assertFalse(loginPage.isSocialButtonPresent(org0Broker.getAlias())); loginPage.open(bc.consumerRealmName()); loginPage.loginUsername("user@org-0.org"); - Assert.assertFalse(loginPage.isSocialButtonPresent(org0Broker.getAlias())); + Assertions.assertFalse(loginPage.isSocialButtonPresent(org0Broker.getAlias())); } @Test @@ -995,7 +996,7 @@ public void testEmailDomainDoesNotMatchBrokerDomain() { loginOrgIdp(email, email, true, false); - Assert.assertTrue(driver.getPageSource().contains("Email domain does not match any domain from the organization")); + Assertions.assertTrue(driver.getPageSource().contains("Email domain does not match any domain from the organization")); assertIsNotMember(email, organization); updateAccountInformationPage.updateAccountInformation("external@other.org", "external@other.org", "Firstname", "Lastname"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/broker/OrganizationIdentityProviderTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/broker/OrganizationIdentityProviderTest.java index b82630b089b7..8f3c54a8f324 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/broker/OrganizationIdentityProviderTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/broker/OrganizationIdentityProviderTest.java @@ -35,8 +35,8 @@ import org.keycloak.representations.idm.OrganizationRepresentation; import org.keycloak.testsuite.organization.admin.AbstractOrganizationTest; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.models.OrganizationModel.ORGANIZATION_DOMAIN_ATTRIBUTE; @@ -44,8 +44,8 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; public class OrganizationIdentityProviderTest extends AbstractOrganizationTest { @@ -57,15 +57,15 @@ public void testUpdate() { IdentityProviderRepresentation expected = orgIdPResource.toRepresentation(); // organization link set - Assert.assertEquals(expected.getOrganizationId(), organization.getId()); + Assertions.assertEquals(expected.getOrganizationId(), organization.getId()); IdentityProviderResource idpResource = testRealm().identityProviders().get(expected.getAlias()); IdentityProviderRepresentation actual = idpResource.toRepresentation(); - Assert.assertEquals(actual.getOrganizationId(), organization.getId()); + Assertions.assertEquals(actual.getOrganizationId(), organization.getId()); actual.setOrganizationId("somethingelse"); try { idpResource.update(actual); - Assert.fail("Should fail because it maps to an invalid org"); + Assertions.fail("Should fail because it maps to an invalid org"); } catch (BadRequestException ignore) { } @@ -73,16 +73,16 @@ public void testUpdate() { actual.setOrganizationId(secondOrg.getId()); idpResource.update(actual); actual = idpResource.toRepresentation(); - Assert.assertEquals(actual.getOrganizationId(), organization.getId()); + Assertions.assertEquals(actual.getOrganizationId(), organization.getId()); actual = idpResource.toRepresentation(); // the link to the organization should not change - Assert.assertEquals(actual.getOrganizationId(), organization.getId()); + Assertions.assertEquals(actual.getOrganizationId(), organization.getId()); actual.setOrganizationId(null); idpResource.update(actual); actual = idpResource.toRepresentation(); // the link to the organization should not change - Assert.assertEquals(actual.getOrganizationId(), organization.getId()); + Assertions.assertEquals(actual.getOrganizationId(), organization.getId()); String domain = actual.getConfig().get(ORGANIZATION_DOMAIN_ATTRIBUTE); @@ -91,19 +91,19 @@ public void testUpdate() { idpResource.update(actual); actual = idpResource.toRepresentation(); // domain removed - Assert.assertNull(actual.getConfig().get(ORGANIZATION_DOMAIN_ATTRIBUTE)); + Assertions.assertNull(actual.getConfig().get(ORGANIZATION_DOMAIN_ATTRIBUTE)); actual.getConfig().put(ORGANIZATION_DOMAIN_ATTRIBUTE, domain); idpResource.update(actual); actual = idpResource.toRepresentation(); // domain set again - Assert.assertNotNull(actual.getConfig().get(ORGANIZATION_DOMAIN_ATTRIBUTE)); + Assertions.assertNotNull(actual.getConfig().get(ORGANIZATION_DOMAIN_ATTRIBUTE)); actual.getConfig().remove(ORGANIZATION_DOMAIN_ATTRIBUTE); idpResource.update(actual); actual = idpResource.toRepresentation(); // domain removed - Assert.assertNull(actual.getConfig().get(ORGANIZATION_DOMAIN_ATTRIBUTE)); + Assertions.assertNull(actual.getConfig().get(ORGANIZATION_DOMAIN_ATTRIBUTE)); } @Test @@ -128,7 +128,7 @@ public void testDelete() { } } - Assert.assertEquals(6, organization.identityProviders().getIdentityProviders().size()); + Assertions.assertEquals(6, organization.identityProviders().getIdentityProviders().size()); for (int i = 0; i < 5; i++) { String alias = "idp-" + i; @@ -140,7 +140,7 @@ public void testDelete() { try { idpResource.toRepresentation(); - Assert.fail("should be removed"); + Assertions.fail("should be removed"); } catch (NotFoundException expected) { } @@ -149,7 +149,7 @@ public void testDelete() { } organization.identityProviders().get(bc.getIDPAlias()).delete().close(); - Assert.assertFalse(testRealm().identityProviders().findAll().isEmpty()); + Assertions.assertFalse(testRealm().identityProviders().findAll().isEmpty()); } @Test @@ -192,8 +192,8 @@ public void testRemovingOrgShouldRemoveIdP() { // broker not removed from realm IdentityProviderRepresentation idpRep = testRealm().identityProviders().get(bc.getIDPAlias()).toRepresentation(); // broker no longer linked to the org - Assert.assertNull(idpRep.getOrganizationId()); - Assert.assertNull(idpRep.getConfig().get(ORGANIZATION_DOMAIN_ATTRIBUTE)); + Assertions.assertNull(idpRep.getOrganizationId()); + Assertions.assertNull(idpRep.getConfig().get(ORGANIZATION_DOMAIN_ATTRIBUTE)); } @Test @@ -225,7 +225,7 @@ public void testAssignDomainNotBoundToOrganization() { try { testRealm().identityProviders().get(idpRep.getAlias()).update(idpRep); - Assert.fail("Domain set to broker is invalid"); + Assertions.fail("Domain set to broker is invalid"); } catch (BadRequestException ignore) { } @@ -233,7 +233,7 @@ public void testAssignDomainNotBoundToOrganization() { idpRep.setAlias("newbroker"); idpRep.setInternalId(null); try (Response response = testRealm().identityProviders().create(idpRep)) { - Assert.assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + Assertions.assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/broker/OrganizationOIDCBrokerSelfRegistrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/broker/OrganizationOIDCBrokerSelfRegistrationTest.java index d7d92524c616..fc879ddbd9a9 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/broker/OrganizationOIDCBrokerSelfRegistrationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/broker/OrganizationOIDCBrokerSelfRegistrationTest.java @@ -24,7 +24,7 @@ import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class OrganizationOIDCBrokerSelfRegistrationTest extends AbstractBrokerSelfRegistrationTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/exportimport/OrganizationExportTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/exportimport/OrganizationExportTest.java index 81c5ae956096..73fb1b9a836c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/exportimport/OrganizationExportTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/exportimport/OrganizationExportTest.java @@ -61,8 +61,8 @@ import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class OrganizationExportTest extends AbstractOrganizationTest { @@ -266,7 +266,7 @@ private void validateGroupIds(List groups, Map values = groupsAttribute.getAttributeValue(); assertThat(values, hasSize(2)); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/mapper/OrganizationGroupOidcIdpMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/mapper/OrganizationGroupOidcIdpMapperTest.java index 7263fc12acc4..eca24b852048 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/mapper/OrganizationGroupOidcIdpMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/mapper/OrganizationGroupOidcIdpMapperTest.java @@ -44,9 +44,9 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; public class OrganizationGroupOidcIdpMapperTest extends AbstractOrganizationTest { @@ -94,8 +94,8 @@ public void testAdvancedClaimToGroupMapperWithOrganizationGroup() { .get(idp.getAlias()) .getMapperById(mapperId); - assertNotNull("Mapper should be created", createdMapper); - assertEquals("Mapper should reference org group", groupPath, createdMapper.getConfig().get(ConfigConstants.GROUP)); + assertNotNull(createdMapper, "Mapper should be created"); + assertEquals(groupPath, createdMapper.getConfig().get(ConfigConstants.GROUP), "Mapper should reference org group"); } @Test @@ -122,7 +122,7 @@ public void testCreateMapperWithOrganizationSubgroup() { // Get the subgroup from the parent's children List children = orgResource.groups().group(parentId).getSubGroups(null, null, null, null); - assertNotNull("Parent should have subgroups", children); + assertNotNull(children, "Parent should have subgroups"); assertThat("Parent should have 1 subgroup", children.size(), is(1)); String childGroupPath = children.get(0).getPath(); @@ -150,8 +150,8 @@ public void testCreateMapperWithOrganizationSubgroup() { .get(idp.getAlias()) .getMapperById(mapperId); - assertNotNull("Mapper should be created", createdMapper); - assertEquals("Mapper should reference org subgroup", childGroupPath, createdMapper.getConfig().get(ConfigConstants.GROUP)); + assertNotNull(createdMapper, "Mapper should be created"); + assertEquals(childGroupPath, createdMapper.getConfig().get(ConfigConstants.GROUP), "Mapper should reference org subgroup"); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/mapper/OrganizationGroupSamlIdpMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/mapper/OrganizationGroupSamlIdpMapperTest.java index 7cb753ede6ff..2b93a48dfabc 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/mapper/OrganizationGroupSamlIdpMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/mapper/OrganizationGroupSamlIdpMapperTest.java @@ -48,7 +48,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; public class OrganizationGroupSamlIdpMapperTest extends AbstractOrganizationTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/mapper/OrganizationOIDCProtocolMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/mapper/OrganizationOIDCProtocolMapperTest.java index d35a7cfc0851..279c82c09881 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/mapper/OrganizationOIDCProtocolMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/mapper/OrganizationOIDCProtocolMapperTest.java @@ -63,9 +63,9 @@ import org.keycloak.testsuite.util.oauth.OAuthClient; import org.keycloak.testsuite.util.oauth.UserInfoResponse; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; @@ -78,9 +78,9 @@ import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.oneOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class OrganizationOIDCProtocolMapperTest extends AbstractOrganizationTest { @@ -101,8 +101,8 @@ public void testPasswordGrantType() throws Exception { orgb.members().addMember(member.getId()).close(); - Assert.assertTrue(orga.members().list(-1, -1).stream().map(UserRepresentation::getId).anyMatch(member.getId()::equals)); - Assert.assertTrue(orgb.members().list(-1, -1).stream().map(UserRepresentation::getId).anyMatch(member.getId()::equals)); + Assertions.assertTrue(orga.members().list(-1, -1).stream().map(UserRepresentation::getId).anyMatch(member.getId()::equals)); + Assertions.assertTrue(orgb.members().list(-1, -1).stream().map(UserRepresentation::getId).anyMatch(member.getId()::equals)); oauth.client("direct-grant", "password"); oauth.scope("openid organization:*"); @@ -133,40 +133,40 @@ public void testMultipleOrganizationScopes() throws Exception { orgb.members().addMember(member.getId()).close(); - Assert.assertTrue(orga.members().list(-1, -1).stream().map(UserRepresentation::getId).anyMatch(member.getId()::equals)); - Assert.assertTrue(orgb.members().list(-1, -1).stream().map(UserRepresentation::getId).anyMatch(member.getId()::equals)); + Assertions.assertTrue(orga.members().list(-1, -1).stream().map(UserRepresentation::getId).anyMatch(member.getId()::equals)); + Assertions.assertTrue(orgb.members().list(-1, -1).stream().map(UserRepresentation::getId).anyMatch(member.getId()::equals)); oauth.clientId("test-app"); // Test multiple specific organization scopes - should return both organizations oauth.scope("openid organization:org-a organization:org-b"); AccessTokenResponse response = oauth.doPasswordGrantRequest(memberEmail, memberPassword); - Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode()); + Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode()); AccessToken accessToken = TokenVerifier.create(response.getAccessToken(), AccessToken.class).getToken(); List organizations = (List) accessToken.getOtherClaims().get(OAuth2Constants.ORGANIZATION); - Assert.assertNotNull(organizations); - Assert.assertTrue(organizations.contains("org-a")); - Assert.assertTrue(organizations.contains("org-b")); + Assertions.assertNotNull(organizations); + Assertions.assertTrue(organizations.contains("org-a")); + Assertions.assertTrue(organizations.contains("org-b")); // Test organization + specific organization scope - should still fail (mixing ANY with SPECIFIC) oauth.scope("openid organization organization:org-a"); response = oauth.doPasswordGrantRequest(memberEmail, memberPassword); - Assert.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode()); + Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode()); // Test organization + wildcard scope - should still fail (mixing ANY with ALL) oauth.scope("openid organization organization:*"); response = oauth.doPasswordGrantRequest(memberEmail, memberPassword); - Assert.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode()); + Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode()); // Test specific organization + wildcard scope - should still fail (mixing SPECIFIC with ALL) oauth.scope("openid organization:org-a organization:*"); response = oauth.doPasswordGrantRequest(memberEmail, memberPassword); - Assert.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode()); + Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode()); // Test nonexistent org alias - should fail (nonexistent alias is not a valid scope) oauth.scope("openid organization:org-a organization:nonexistent"); response = oauth.doPasswordGrantRequest(memberEmail, memberPassword); - Assert.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode()); + Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode()); } @Test @@ -198,7 +198,7 @@ public void testOrganizationScopeMapsSpecificOrganization() { oauth.client("broker-app", "broker-app-secret"); oauth.scope("organization:" + orgA.getAlias()); loginPage.open(bc.consumerRealmName()); - org.keycloak.testsuite.Assert.assertFalse(loginPage.isPasswordInputPresent()); + Assertions.assertFalse(loginPage.isPasswordInputPresent()); assertTrue(loginPage.isSocialButtonPresent(orgA.getAlias() + "-identity-provider")); assertFalse(loginPage.isSocialButtonPresent(orgB.getAlias() + "-identity-provider")); assertFalse(driver.getPageSource().contains("Your email domain matches")); @@ -1434,8 +1434,8 @@ public void testCustomOrganizationScopeNameAllOrganizations() { orgb.members().addMember(member.getId()).close(); - Assert.assertTrue(orga.members().list(-1, -1).stream().map(UserRepresentation::getId).anyMatch(member.getId()::equals)); - Assert.assertTrue(orgb.members().list(-1, -1).stream().map(UserRepresentation::getId).anyMatch(member.getId()::equals)); + Assertions.assertTrue(orga.members().list(-1, -1).stream().map(UserRepresentation::getId).anyMatch(member.getId()::equals)); + Assertions.assertTrue(orgb.members().list(-1, -1).stream().map(UserRepresentation::getId).anyMatch(member.getId()::equals)); ClientScopeRepresentation orgScope = testRealm().clientScopes().findAll().stream() .filter(s -> OIDCLoginProtocolFactory.ORGANIZATION.equals(s.getName())) diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/mapper/OrganizationSAMLProtocolMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/mapper/OrganizationSAMLProtocolMapperTest.java index 30a4c9b0ed28..2f669ee20d82 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/mapper/OrganizationSAMLProtocolMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/mapper/OrganizationSAMLProtocolMapperTest.java @@ -41,8 +41,8 @@ import org.keycloak.testsuite.util.SamlClient; import org.keycloak.testsuite.util.SamlClientBuilder; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.util.SamlStreams.assertionsUnencrypted; import static org.keycloak.testsuite.util.SamlStreams.attributeStatements; @@ -81,9 +81,9 @@ public void testAttribute() { .filter(attribute -> OrganizationMembershipMapper.ORGANIZATION_ATTRIBUTE_NAME.equals(attribute.getName())) .findAny() .orElse(null); - Assert.assertNotNull(orgAttribute); + Assertions.assertNotNull(orgAttribute); List values = orgAttribute.getAttributeValue(); - Assert.assertEquals(1, values.size()); - Assert.assertEquals(organizationName, values.get(0)); + Assertions.assertEquals(1, values.size()); + Assertions.assertEquals(organizationName, values.get(0)); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/member/OrganizationMemberTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/member/OrganizationMemberTest.java index 7d714a9afe9b..e82c8b76637b 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/member/OrganizationMemberTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/member/OrganizationMemberTest.java @@ -47,7 +47,6 @@ import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.representations.userprofile.config.UPConfig; import org.keycloak.representations.userprofile.config.UPConfig.UnmanagedAttributePolicy; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.organization.admin.AbstractOrganizationTest; import org.keycloak.testsuite.pages.AppPage; @@ -57,6 +56,7 @@ import org.hamcrest.Matchers; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.models.OrganizationDomainModel.ANY_DOMAIN; import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage; @@ -70,12 +70,12 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class OrganizationMemberTest extends AbstractOrganizationTest { @@ -576,8 +576,8 @@ public void testMemberInMultipleOrganizations() { orgb.members().addMember(member.getId()).close(); - Assert.assertTrue(orga.members().list(-1, -1).stream().map(UserRepresentation::getId).anyMatch(member.getId()::equals)); - Assert.assertTrue(orgb.members().list(-1, -1).stream().map(UserRepresentation::getId).anyMatch(member.getId()::equals)); + Assertions.assertTrue(orga.members().list(-1, -1).stream().map(UserRepresentation::getId).anyMatch(member.getId()::equals)); + Assertions.assertTrue(orgb.members().list(-1, -1).stream().map(UserRepresentation::getId).anyMatch(member.getId()::equals)); String orgbId = orgb.toRepresentation().getId(); String orgaId = orga.toRepresentation().getId(); List memberOfOrgs = orga.members().member(member.getId()).getOrganizations(true).stream().map(OrganizationRepresentation::getId).toList(); @@ -677,7 +677,7 @@ public void testGetMemberOrganizationsBriefVsFullRepresentation() { assertEquals(orgRep.getDescription(), briefRep.getDescription()); assertEquals(orgRep.getRedirectUrl(), briefRep.getRedirectUrl()); assertEquals(orgRep.isEnabled(), briefRep.isEnabled()); - assertNull("Brief representation should not include attributes", briefRep.getAttributes()); + assertNull(briefRep.getAttributes(), "Brief representation should not include attributes"); // Test full representation (briefRepresentation=false) List fullOrgs = organization.members().member(member.getId()).getOrganizations(false); @@ -690,23 +690,23 @@ public void testGetMemberOrganizationsBriefVsFullRepresentation() { assertEquals(orgRep.getDescription(), fullRep.getDescription()); assertEquals(orgRep.getRedirectUrl(), fullRep.getRedirectUrl()); assertEquals(orgRep.isEnabled(), fullRep.isEnabled()); - assertNotNull("Full representation should include attributes", fullRep.getAttributes()); - assertTrue("Full representation should include the test attribute", - fullRep.getAttributes().containsKey("testAttribute")); + assertNotNull(fullRep.getAttributes(), "Full representation should include attributes"); + assertTrue(fullRep.getAttributes().containsKey("testAttribute"), + "Full representation should include the test attribute"); assertEquals("testValue", fullRep.getAttributes().get("testAttribute").get(0)); // Test the global members API endpoint as well List briefOrgsGlobal = testRealm().organizations().members().getOrganizations(member.getId(), true); assertNotNull(briefOrgsGlobal); assertEquals(1, briefOrgsGlobal.size()); - assertNull("Brief representation should not include attributes", briefOrgsGlobal.get(0).getAttributes()); + assertNull(briefOrgsGlobal.get(0).getAttributes(), "Brief representation should not include attributes"); List fullOrgsGlobal = testRealm().organizations().members().getOrganizations(member.getId(), false); assertNotNull(fullOrgsGlobal); assertEquals(1, fullOrgsGlobal.size()); - assertNotNull("Full representation should include attributes", fullOrgsGlobal.get(0).getAttributes()); - assertTrue("Full representation should include the test attribute", - fullOrgsGlobal.get(0).getAttributes().containsKey("testAttribute")); + assertNotNull(fullOrgsGlobal.get(0).getAttributes(), "Full representation should include attributes"); + assertTrue(fullOrgsGlobal.get(0).getAttributes().containsKey("testAttribute"), + "Full representation should include the test attribute"); } @Test @@ -759,8 +759,8 @@ private void loginViaNonOrgIdP(String idpAlias) { waitForPage(driver, "update account information", false); updateAccountInformationPage.assertCurrent(); - Assert.assertTrue("We must be on correct realm right now", - driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/")); + Assertions.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"), + "We must be on correct realm right now"); log.debug("Updating info on updateAccount page"); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/member/OrganizationMemberWithLdapTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/member/OrganizationMemberWithLdapTest.java index 0172466d1ddd..e17a7fb3ba31 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/member/OrganizationMemberWithLdapTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/member/OrganizationMemberWithLdapTest.java @@ -48,7 +48,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class OrganizationMemberWithLdapTest extends AbstractOrganizationTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/policy/PasswordAgePolicyTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/policy/PasswordAgePolicyTest.java index 94fbb23added..bac7784cbe45 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/policy/PasswordAgePolicyTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/policy/PasswordAgePolicyTest.java @@ -42,9 +42,9 @@ import org.jboss.arquillian.graphene.page.Page; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.representations.idm.CredentialRepresentation.PASSWORD; import static org.keycloak.testsuite.admin.ApiUtil.getCreatedId; @@ -318,10 +318,10 @@ public void testRegistration() throws IOException { registerPage.register("firstName", "lastName", "registration-user@localhost", "registration-user", "password", "password"); - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); AuthorizationEndpointResponse response = oauth.parseLoginResponse(); - Assert.assertNull(response.getError()); - Assert.assertNotNull(response.getCode()); + Assertions.assertNull(response.getError()); + Assertions.assertNotNull(response.getCode()); AdminApiUtil.findUserByUsernameId(testRealmResource(), "registration-user").remove(); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/policy/PasswordPolicyTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/policy/PasswordPolicyTest.java index 8e56ed697ad6..af3898eed1d1 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/policy/PasswordPolicyTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/policy/PasswordPolicyTest.java @@ -33,17 +33,17 @@ import org.keycloak.testsuite.AbstractKeycloakTest; import org.keycloak.testsuite.util.RealmBuilder; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.endsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Stian Thorgersen @@ -58,14 +58,14 @@ public void testLength() { realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "length")); - Assert.assertEquals("invalidPasswordMinLengthMessage", policyManager.validate("jdoe", "1234567").getMessage()); - Assert.assertArrayEquals(new Object[]{8}, policyManager.validate("jdoe", "1234567").getParameters()); + Assertions.assertEquals("invalidPasswordMinLengthMessage", policyManager.validate("jdoe", "1234567").getMessage()); + Assertions.assertArrayEquals(new Object[]{8}, policyManager.validate("jdoe", "1234567").getParameters()); assertNull(policyManager.validate("jdoe", "12345678")); realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "length(4)")); - Assert.assertEquals("invalidPasswordMinLengthMessage", policyManager.validate("jdoe", "123").getMessage()); - Assert.assertArrayEquals(new Object[]{4}, policyManager.validate("jdoe", "123").getParameters()); + Assertions.assertEquals("invalidPasswordMinLengthMessage", policyManager.validate("jdoe", "123").getMessage()); + Assertions.assertArrayEquals(new Object[]{4}, policyManager.validate("jdoe", "123").getParameters()); assertNull(policyManager.validate("jdoe", "1234")); }); } @@ -78,17 +78,17 @@ public void testMaximumLength() { realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "maxLength")); - Assert.assertEquals("invalidPasswordMaxLengthMessage", + Assertions.assertEquals("invalidPasswordMaxLengthMessage", policyManager.validate("jdoe", "12345678901234567890123456789012345678901234567890123456789012345").getMessage()); - Assert.assertArrayEquals(new Object[]{MaximumLengthPasswordPolicyProviderFactory.DEFAULT_MAX_LENGTH}, + Assertions.assertArrayEquals(new Object[]{MaximumLengthPasswordPolicyProviderFactory.DEFAULT_MAX_LENGTH}, policyManager.validate("jdoe", "12345678901234567890123456789012345678901234567890123456789012345").getParameters()); assertNull(policyManager.validate("jdoe", "1234567890123456789012345678901234567890123456789012345678901234")); realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "maxLength(24)")); - Assert.assertEquals("invalidPasswordMaxLengthMessage", + Assertions.assertEquals("invalidPasswordMaxLengthMessage", policyManager.validate("jdoe", "1234567890123456789012345").getMessage()); - Assert.assertArrayEquals(new Object[]{24}, + Assertions.assertArrayEquals(new Object[]{24}, policyManager.validate("jdoe", "1234567890123456789012345").getParameters()); assertNull(policyManager.validate("jdoe", "123456789012345678901234")); }); @@ -101,13 +101,13 @@ public void testDigits() { PasswordPolicyManagerProvider policyManager = session.getProvider(PasswordPolicyManagerProvider.class); realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "digits")); - Assert.assertEquals("invalidPasswordMinDigitsMessage", policyManager.validate("jdoe", "abcd").getMessage()); - Assert.assertArrayEquals(new Object[]{1}, policyManager.validate("jdoe", "abcd").getParameters()); + Assertions.assertEquals("invalidPasswordMinDigitsMessage", policyManager.validate("jdoe", "abcd").getMessage()); + Assertions.assertArrayEquals(new Object[]{1}, policyManager.validate("jdoe", "abcd").getParameters()); assertNull(policyManager.validate("jdoe", "abcd1")); realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "digits(2)")); - Assert.assertEquals("invalidPasswordMinDigitsMessage", policyManager.validate("jdoe", "abcd1").getMessage()); - Assert.assertArrayEquals(new Object[]{2}, policyManager.validate("jdoe", "abcd1").getParameters()); + Assertions.assertEquals("invalidPasswordMinDigitsMessage", policyManager.validate("jdoe", "abcd1").getMessage()); + Assertions.assertArrayEquals(new Object[]{2}, policyManager.validate("jdoe", "abcd1").getParameters()); assertNull(policyManager.validate("jdoe", "abcd12")); }); } @@ -119,13 +119,13 @@ public void testLowerCase() { PasswordPolicyManagerProvider policyManager = session.getProvider(PasswordPolicyManagerProvider.class); realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "lowerCase")); - Assert.assertEquals("invalidPasswordMinLowerCaseCharsMessage", policyManager.validate("jdoe", "ABCD1234").getMessage()); - Assert.assertArrayEquals(new Object[]{1}, policyManager.validate("jdoe", "ABCD1234").getParameters()); + Assertions.assertEquals("invalidPasswordMinLowerCaseCharsMessage", policyManager.validate("jdoe", "ABCD1234").getMessage()); + Assertions.assertArrayEquals(new Object[]{1}, policyManager.validate("jdoe", "ABCD1234").getParameters()); assertNull(policyManager.validate("jdoe", "ABcD1234")); realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "lowerCase(2)")); - Assert.assertEquals("invalidPasswordMinLowerCaseCharsMessage", policyManager.validate("jdoe", "ABcD1234").getMessage()); - Assert.assertArrayEquals(new Object[]{2}, policyManager.validate("jdoe", "ABcD1234").getParameters()); + Assertions.assertEquals("invalidPasswordMinLowerCaseCharsMessage", policyManager.validate("jdoe", "ABcD1234").getMessage()); + Assertions.assertArrayEquals(new Object[]{2}, policyManager.validate("jdoe", "ABcD1234").getParameters()); assertNull(policyManager.validate("jdoe", "aBcD1234")); }); } @@ -137,13 +137,13 @@ public void testUpperCase() { PasswordPolicyManagerProvider policyManager = session.getProvider(PasswordPolicyManagerProvider.class); realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "upperCase")); - Assert.assertEquals("invalidPasswordMinUpperCaseCharsMessage", policyManager.validate("jdoe", "abcd1234").getMessage()); - Assert.assertArrayEquals(new Object[]{1}, policyManager.validate("jdoe", "abcd1234").getParameters()); + Assertions.assertEquals("invalidPasswordMinUpperCaseCharsMessage", policyManager.validate("jdoe", "abcd1234").getMessage()); + Assertions.assertArrayEquals(new Object[]{1}, policyManager.validate("jdoe", "abcd1234").getParameters()); assertNull(policyManager.validate("jdoe", "abCd1234")); realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "upperCase(2)")); - Assert.assertEquals("invalidPasswordMinUpperCaseCharsMessage", policyManager.validate("jdoe", "abCd1234").getMessage()); - Assert.assertArrayEquals(new Object[]{2}, policyManager.validate("jdoe", "abCd1234").getParameters()); + Assertions.assertEquals("invalidPasswordMinUpperCaseCharsMessage", policyManager.validate("jdoe", "abCd1234").getMessage()); + Assertions.assertArrayEquals(new Object[]{2}, policyManager.validate("jdoe", "abCd1234").getParameters()); assertNull(policyManager.validate("jdoe", "AbCd1234")); }); } @@ -155,13 +155,13 @@ public void testSpecialChars() { PasswordPolicyManagerProvider policyManager = session.getProvider(PasswordPolicyManagerProvider.class); realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "specialChars")); - Assert.assertEquals("invalidPasswordMinSpecialCharsMessage", policyManager.validate("jdoe", "abcd1234").getMessage()); - Assert.assertArrayEquals(new Object[]{1}, policyManager.validate("jdoe", "abcd1234").getParameters()); + Assertions.assertEquals("invalidPasswordMinSpecialCharsMessage", policyManager.validate("jdoe", "abcd1234").getMessage()); + Assertions.assertArrayEquals(new Object[]{1}, policyManager.validate("jdoe", "abcd1234").getParameters()); assertNull(policyManager.validate("jdoe", "ab&d1234")); realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "specialChars(2)")); - Assert.assertEquals("invalidPasswordMinSpecialCharsMessage", policyManager.validate("jdoe", "ab&d1234").getMessage()); - Assert.assertArrayEquals(new Object[]{2}, policyManager.validate("jdoe", "ab&d1234").getParameters()); + Assertions.assertEquals("invalidPasswordMinSpecialCharsMessage", policyManager.validate("jdoe", "ab&d1234").getMessage()); + Assertions.assertArrayEquals(new Object[]{2}, policyManager.validate("jdoe", "ab&d1234").getParameters()); assertNull(policyManager.validate("jdoe", "ab&d-234")); }); } @@ -178,9 +178,9 @@ public void testBlacklistPasswordPolicyWithTestBlacklist() throws Exception { realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "passwordBlacklist(test-password-blacklist.txt)")); - Assert.assertEquals(BlacklistPasswordPolicyProvider.ERROR_MESSAGE, policyManager.validate("jdoe", "blacklisted1").getMessage()); - Assert.assertEquals(BlacklistPasswordPolicyProvider.ERROR_MESSAGE, policyManager.validate("jdoe", "blacklisted2").getMessage()); - Assert.assertEquals(BlacklistPasswordPolicyProvider.ERROR_MESSAGE, policyManager.validate("jdoe", "bLaCkLiSteD2").getMessage()); + Assertions.assertEquals(BlacklistPasswordPolicyProvider.ERROR_MESSAGE, policyManager.validate("jdoe", "blacklisted1").getMessage()); + Assertions.assertEquals(BlacklistPasswordPolicyProvider.ERROR_MESSAGE, policyManager.validate("jdoe", "blacklisted2").getMessage()); + Assertions.assertEquals(BlacklistPasswordPolicyProvider.ERROR_MESSAGE, policyManager.validate("jdoe", "bLaCkLiSteD2").getMessage()); assertNull(policyManager.validate("jdoe", "notblacklisted")); }); } @@ -205,7 +205,7 @@ public void testNotUsername() { PasswordPolicyManagerProvider policyManager = session.getProvider(PasswordPolicyManagerProvider.class); realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "notUsername")); - Assert.assertEquals("invalidPasswordNotUsernameMessage", policyManager.validate("jdoe", "jdoe").getMessage()); + Assertions.assertEquals("invalidPasswordNotUsernameMessage", policyManager.validate("jdoe", "jdoe").getMessage()); assertNull(policyManager.validate("jdoe", "ab&d1234")); }); } @@ -218,7 +218,7 @@ public void testInvalidPolicyName() { try { realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "noSuchPolicy")); - Assert.fail("Expected exception"); + Assertions.fail("Expected exception"); } catch (ModelException e) { assertEquals("Password policy not found", e.getMessage()); } @@ -255,14 +255,14 @@ public void testRegexPatterns() { //Fails to match one of the regex pattern realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "regexPattern(jdoe) and regexPattern(j*d)")); - Assert.assertEquals("invalidPasswordRegexPatternMessage", policyManager.validate("jdoe", "jdoe").getMessage()); + Assertions.assertEquals("invalidPasswordRegexPatternMessage", policyManager.validate("jdoe", "jdoe").getMessage()); ////Fails to match all of the regex patterns realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "regexPattern(j*p) and regexPattern(j*d) and regexPattern(adoe)")); - Assert.assertEquals("invalidPasswordRegexPatternMessage", policyManager.validate("jdoe", "jdoe").getMessage()); + Assertions.assertEquals("invalidPasswordRegexPatternMessage", policyManager.validate("jdoe", "jdoe").getMessage()); realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "regexPattern([a-z][a-z][a-z][a-z][0-9])")); - Assert.assertEquals("invalidPasswordRegexPatternMessage", policyManager.validate("jdoe", "jdoe").getMessage()); + Assertions.assertEquals("invalidPasswordRegexPatternMessage", policyManager.validate("jdoe", "jdoe").getMessage()); realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "regexPattern(jdoe)")); assertNull(policyManager.validate("jdoe", "jdoe")); @@ -279,13 +279,13 @@ public void testComplex() { PasswordPolicyManagerProvider policyManager = session.getProvider(PasswordPolicyManagerProvider.class); realmModel.setPasswordPolicy(PasswordPolicy.parse(session, "length(8) and maxLength(32) and digits(2) and lowerCase(2) and upperCase(2) and specialChars(2) and notUsername()")); - Assert.assertNotNull(policyManager.validate("jdoe", "12aaBB&")); - Assert.assertNotNull(policyManager.validate("jdoe", "aaaaBB&-")); - Assert.assertNotNull(policyManager.validate("jdoe", "12AABB&-")); - Assert.assertNotNull(policyManager.validate("jdoe", "12aabb&-")); - Assert.assertNotNull(policyManager.validate("jdoe", "12aaBBcc")); - Assert.assertNotNull(policyManager.validate("12aaBB&-", "12aaBB&-")); - Assert.assertNotNull(policyManager.validate("jdoe", "12aaBB&-12aaBB&-12aaBB&-12aaBB&-1")); + Assertions.assertNotNull(policyManager.validate("jdoe", "12aaBB&")); + Assertions.assertNotNull(policyManager.validate("jdoe", "aaaaBB&-")); + Assertions.assertNotNull(policyManager.validate("jdoe", "12AABB&-")); + Assertions.assertNotNull(policyManager.validate("jdoe", "12aabb&-")); + Assertions.assertNotNull(policyManager.validate("jdoe", "12aaBBcc")); + Assertions.assertNotNull(policyManager.validate("12aaBB&-", "12aaBB&-")); + Assertions.assertNotNull(policyManager.validate("jdoe", "12aaBB&-12aaBB&-12aaBB&-12aaBB&-1")); assertNull(policyManager.validate("jdoe", "12aaBB&-")); }); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/providers/ProvidersOverrideTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/providers/ProvidersOverrideTest.java index c0eaaa81e0d4..2473a25dc47c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/providers/ProvidersOverrideTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/providers/ProvidersOverrideTest.java @@ -34,9 +34,9 @@ import org.keycloak.provider.Provider; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.AbstractKeycloakTest; -import org.keycloak.testsuite.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * Test for having multiple providerFactory of smae SPI with same providerId @@ -72,6 +72,6 @@ public void testDefaultProvidersOverride() { private void testProviderImplementationClass(Class providerClass, String providerId, Class expectedProviderImplClass) { String providerImplClass = getTestingClient().testing().getProviderClassName(providerClass.getName(), providerId); - Assert.assertEquals(expectedProviderImplClass.getName(), providerImplClass); + Assertions.assertEquals(expectedProviderImplClass.getName(), providerImplClass); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/AudienceProtocolMappersTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/AudienceProtocolMappersTest.java index 68797cffedb5..c9436a7bd763 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/AudienceProtocolMappersTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/AudienceProtocolMappersTest.java @@ -41,9 +41,9 @@ import org.keycloak.testsuite.util.SamlClientBuilder; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.saml.RoleMapperTest.createSamlProtocolMapper; import static org.keycloak.testsuite.util.ServerURLs.AUTH_SERVER_PORT; @@ -82,20 +82,20 @@ public void testExpectedAudiences(String... audiences) { .login().user(bburkeUser).build() .getSamlResponse(SamlClient.Binding.POST); - Assert.assertNotNull(document.getSamlObject()); + Assertions.assertNotNull(document.getSamlObject()); assertThat(document.getSamlObject(), Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS)); - Assert.assertNotNull(((ResponseType) document.getSamlObject()).getAssertions()); + Assertions.assertNotNull(((ResponseType) document.getSamlObject()).getAssertions()); assertThat(((ResponseType) document.getSamlObject()).getAssertions().size(), greaterThan(0)); - Assert.assertNotNull(((ResponseType) document.getSamlObject()).getAssertions().get(0)); - Assert.assertNotNull(((ResponseType) document.getSamlObject()).getAssertions().get(0).getAssertion()); + Assertions.assertNotNull(((ResponseType) document.getSamlObject()).getAssertions().get(0)); + Assertions.assertNotNull(((ResponseType) document.getSamlObject()).getAssertions().get(0).getAssertion()); AudienceRestrictionType audience = ((ResponseType) document.getSamlObject()) .getAssertions().get(0).getAssertion().getConditions().getConditions() .stream() .filter(AudienceRestrictionType.class::isInstance) .map(AudienceRestrictionType.class::cast) .findFirst().orElse(null); - Assert.assertNotNull(audience); - Assert.assertNotNull(audience.getAudience()); + Assertions.assertNotNull(audience); + Assertions.assertNotNull(audience.getAudience()); List values = audience.getAudience().stream().map(uri -> uri.toString()).collect(Collectors.toList()); assertThat(values, containsInAnyOrder(audiences)); } @@ -148,7 +148,7 @@ public void testAudienceResolveFullScope() throws Exception { this.testExpectedAudiences(SAML_CLIENT_ID_EMPLOYEE_2, "http://localhost:8280/employee/", "http://localhost:8280/employee-role-mapping/"); // remove one of the groups (employee) and check the employee audience is removed String employeeId = adminClient.realm(REALM_NAME).clients().findByClientId("http://localhost:8280/employee/").get(0).getId(); - Assert.assertNotNull(employeeId); + Assertions.assertNotNull(employeeId); try (RoleScopeUpdater rsc = UserAttributeUpdater.forUserByUsername(adminClient, REALM_NAME, bburkeUser.getUsername()) .clientRoleScope(employeeId) .removeByName("employee") @@ -169,9 +169,9 @@ public void testAudienceResolveNoFullScope() throws Exception { // add another client in the scope String employee2Id = adminClient.realm(REALM_NAME).clients().findByClientId("http://localhost:8280/employee2/").get(0).getId(); - Assert.assertNotNull(employee2Id); + Assertions.assertNotNull(employee2Id); String employeeId = adminClient.realm(REALM_NAME).clients().findByClientId("http://localhost:8280/employee/").get(0).getId(); - Assert.assertNotNull(employeeId); + Assertions.assertNotNull(employeeId); List availables = adminClient.realm(REALM_NAME).clients().get(employee2Id).getScopeMappings().clientLevel(employeeId).listAvailable(); assertThat(availables.size(), greaterThan(0)); // assign scope to only employee2 (employee-role-mapping should not be there) @@ -191,15 +191,15 @@ public void testAudienceResolveNoFullScopeClientScopes() throws Exception { clientScope.setProtocol("saml"); clientScope.setProtocolMappers(Collections.singletonList(createSamlProtocolMapper(SAMLAudienceResolveProtocolMapper.PROVIDER_ID))); Response res = adminClient.realm(REALM_NAME).clientScopes().create(clientScope); - Assert.assertEquals(Response.Status.CREATED.getStatusCode(), res.getStatus()); + Assertions.assertEquals(Response.Status.CREATED.getStatusCode(), res.getStatus()); String clientScopeId = ApiUtil.getCreatedId(res); try { // add a mapping to the client scope to employee2.employee role (this way employee should be in the audience) String employee2Id = adminClient.realm(REALM_NAME).clients().findByClientId("http://localhost:8280/employee2/").get(0).getId(); - Assert.assertNotNull(employee2Id); + Assertions.assertNotNull(employee2Id); String employeeId = adminClient.realm(REALM_NAME).clients().findByClientId("http://localhost:8280/employee/").get(0).getId(); - Assert.assertNotNull(employeeId); + Assertions.assertNotNull(employeeId); List availables = adminClient.realm(REALM_NAME).clientScopes().get(clientScopeId).getScopeMappings().clientLevel(employeeId).listAvailable(); assertThat(availables.size(), greaterThan(0)); adminClient.realm(REALM_NAME).clientScopes().get(clientScopeId).getScopeMappings().clientLevel(employeeId).add(availables); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/BasicSamlTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/BasicSamlTest.java index 588f9810859b..75d096e46e8c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/BasicSamlTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/BasicSamlTest.java @@ -79,7 +79,7 @@ import static org.hamcrest.Matchers.matchesRegex; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author mhajas @@ -419,7 +419,7 @@ private void testEncryption(String algorithm, String keyAlgorithm, String digest // check document is encrypted ResponseType responseType = (ResponseType) holder.getSamlObject(); - assertTrue("Assertion is not encrypted", AssertionUtil.isAssertionEncrypted(responseType)); + assertTrue(AssertionUtil.isAssertionEncrypted(responseType), "Assertion is not encrypted"); SamlDeployment deployment = SamlUtils.getSamlDeploymentForClient("sales-post-enc"); AssertionUtil.decryptAssertion(responseType, (EncryptedData encryptedData) -> Collections.singletonList(deployment.getDecryptionKey())); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/BrokerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/BrokerTest.java index de801cab8339..d4ff8d442db6 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/BrokerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/BrokerTest.java @@ -69,8 +69,8 @@ import org.apache.http.Header; import org.apache.http.HttpHeaders; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -84,7 +84,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @@ -156,7 +156,7 @@ public void testLogoutPropagatesToSamlIdentityProvider() throws IOException { reviewProfileAuthenticator = executions.stream() .filter(ex -> Objects.equals(ex.getProviderId(), IdpReviewProfileAuthenticatorFactory.PROVIDER_ID)) .findFirst() - .orElseGet(() -> { Assert.fail("Could not find update profile in first broker login flow"); return null; }); + .orElseGet(() -> { Assertions.fail("Could not find update profile in first broker login flow"); return null; }); reviewProfileAuthenticator.setRequirement(Requirement.DISABLED.name()); realm.flows().updateExecutions(firstBrokerLoginFlowAlias, reviewProfileAuthenticator); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/LevelOfAssuranceFlowSamlTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/LevelOfAssuranceFlowSamlTest.java index 61dc499a50a3..0690aa692b5c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/LevelOfAssuranceFlowSamlTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/LevelOfAssuranceFlowSamlTest.java @@ -42,7 +42,6 @@ import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.saml.common.constants.JBossSAMLURIConstants; import org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.Users; import org.keycloak.testsuite.arquillian.annotation.EnableFeature; import org.keycloak.testsuite.forms.LevelOfAssuranceFlowTest; @@ -66,6 +65,7 @@ import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @@ -757,8 +757,8 @@ private void assertErrorSamlResponse(CloseableHttpResponse response, SamlClient. MatcherAssert.assertThat(holder.getSamlObject(), Matchers.isSamlStatusResponse( JBossSAMLURIConstants.STATUS_RESPONDER, JBossSAMLURIConstants.STATUS_NOAUTHN_CTX)); ResponseType responseType = (ResponseType) holder.getSamlObject(); - Assert.assertNotNull(responseType.getInResponseTo()); - Assert.assertNotNull(responseType.getID()); + Assertions.assertNotNull(responseType.getInResponseTo()); + Assertions.assertNotNull(responseType.getID()); } catch (IOException e) { throw new RuntimeException(e); } @@ -785,8 +785,8 @@ private void assertResponse(CloseableHttpResponse response, String classRef, Sam SAMLDocumentHolder holder = binding.extractResponse(response); MatcherAssert.assertThat(holder.getSamlObject(), Matchers.isSamlStatusResponse(JBossSAMLURIConstants.STATUS_SUCCESS)); ResponseType responseType = (ResponseType) holder.getSamlObject(); - Assert.assertNotNull(responseType.getInResponseTo()); - Assert.assertNotNull(responseType.getID()); + Assertions.assertNotNull(responseType.getInResponseTo()); + Assertions.assertNotNull(responseType.getID()); Optional authContextClassRefOpt = responseType.getAssertions().stream() .map(ResponseType.RTChoiceType::getAssertion) .map(AssertionType::getStatements) @@ -801,8 +801,8 @@ private void assertResponse(CloseableHttpResponse response, String classRef, Sam .map(AuthnContextType.AuthnContextTypeSequence::getClassRef) .filter(Objects::nonNull) .map(AuthnContextClassRefType::getValue); - Assert.assertTrue(authContextClassRefOpt.isPresent()); - Assert.assertEquals(classRef, authContextClassRefOpt.get().toString()); + Assertions.assertTrue(authContextClassRefOpt.isPresent()); + Assertions.assertEquals(classRef, authContextClassRefOpt.get().toString()); } catch (IOException e) { throw new RuntimeException(e); } @@ -816,7 +816,7 @@ public HttpUriRequest perform(CloseableHttpClient client, URI currentURI, Closea String pageContent = EntityUtils.toString(currentResponse.getEntity(), StandardCharsets.UTF_8); org.jsoup.nodes.Document page = Jsoup.parse(pageContent); Elements forms = page.getElementsByTag("form"); - Assert.assertEquals(1, forms.size()); + Assertions.assertEquals(1, forms.size()); Element form = forms.get(0); HttpPost res = new HttpPost(form.attr("action")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(Collections.emptyList(), StandardCharsets.UTF_8); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/LogoutTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/LogoutTest.java index fc1d9c039ab2..b4b8c63feae1 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/LogoutTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/LogoutTest.java @@ -75,11 +75,11 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/NameIdMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/NameIdMapperTest.java index ca08b1b06314..3febe307ed58 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/NameIdMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/NameIdMapperTest.java @@ -24,7 +24,7 @@ import static org.keycloak.testsuite.util.ServerURLs.AUTH_SERVER_SCHEME; import static org.keycloak.testsuite.util.ServerURLs.AUTH_SERVER_SSL_REQUIRED; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class NameIdMapperTest extends AbstractSamlTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SamlClientTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SamlClientTest.java index 10ba18f953a0..92d53402f538 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SamlClientTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SamlClientTest.java @@ -22,8 +22,8 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.w3c.dom.Document; import static org.hamcrest.MatcherAssert.assertThat; @@ -49,7 +49,7 @@ public void testLoginWithOIDCClient() throws ParsingException, ConfigurationExce try (CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(strategy).build()) { HttpUriRequest post = SamlClient.Binding.POST.createSamlUnsignedRequest(samlEndpoint, null, samlRequest); CloseableHttpResponse response = sendPost(post, client); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 400); + Assertions.assertEquals(response.getStatusLine().getStatusCode(), 400); String s = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); assertThat(s, Matchers.containsString("Wrong client protocol.")); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SessionNotOnOrAfterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SessionNotOnOrAfterTest.java index 4c8b410cdf55..ace8cc7cdb0f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SessionNotOnOrAfterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/saml/SessionNotOnOrAfterTest.java @@ -19,8 +19,8 @@ import org.keycloak.testsuite.util.SamlClient; import org.keycloak.testsuite.util.SamlClientBuilder; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; @@ -41,14 +41,14 @@ private SAML2Object checkSessionNotOnOrAfter(SAML2Object ob, int ssoMaxLifespan, assertThat(ob, Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS)); ResponseType resp = (ResponseType) ob; - Assert.assertNotNull(resp); - Assert.assertNotNull(resp.getAssertions()); + Assertions.assertNotNull(resp); + Assertions.assertNotNull(resp.getAssertions()); assertThat(resp.getAssertions().size(), greaterThan(0)); - Assert.assertNotNull(resp.getAssertions().get(0)); - Assert.assertNotNull(resp.getAssertions().get(0).getAssertion()); + Assertions.assertNotNull(resp.getAssertions().get(0)); + Assertions.assertNotNull(resp.getAssertions().get(0).getAssertion()); // session lifespan - Assert.assertNotNull(resp.getAssertions().get(0).getAssertion().getStatements()); + Assertions.assertNotNull(resp.getAssertions().get(0).getAssertion().getStatements()); Set statements = resp.getAssertions().get(0).getAssertion().getStatements(); AuthnStatementType authType = statements.stream() .filter(statement -> statement instanceof AuthnStatementType) @@ -60,15 +60,15 @@ private SAML2Object checkSessionNotOnOrAfter(SAML2Object ob, int ssoMaxLifespan, assertThat(authType.getSessionNotOnOrAfter(), is(XMLTimeUtil.add(authType.getAuthnInstant(), ssoMaxLifespan * 1000L))); // Conditions - Assert.assertNotNull(resp.getAssertions().get(0).getAssertion().getConditions()); - Assert.assertNotNull(resp.getAssertions().get(0).getAssertion().getConditions()); + Assertions.assertNotNull(resp.getAssertions().get(0).getAssertion().getConditions()); + Assertions.assertNotNull(resp.getAssertions().get(0).getAssertion().getConditions()); ConditionsType condition = resp.getAssertions().get(0).getAssertion().getConditions(); - Assert.assertEquals(XMLTimeUtil.add(condition.getNotBefore(), accessCodeLifespan * 1000L), condition.getNotOnOrAfter()); + Assertions.assertEquals(XMLTimeUtil.add(condition.getNotBefore(), accessCodeLifespan * 1000L), condition.getNotOnOrAfter()); // SubjectConfirmation (confirmationData has no NotBefore, using the previous one because it's the same) - Assert.assertNotNull(resp.getAssertions().get(0).getAssertion().getSubject()); - Assert.assertNotNull(resp.getAssertions().get(0).getAssertion().getSubject().getConfirmation()); + Assertions.assertNotNull(resp.getAssertions().get(0).getAssertion().getSubject()); + Assertions.assertNotNull(resp.getAssertions().get(0).getAssertion().getSubject().getConfirmation()); List confirmations = resp.getAssertions().get(0).getAssertion().getSubject().getConfirmation(); SubjectConfirmationDataType confirmationData = confirmations.stream() @@ -77,8 +77,8 @@ private SAML2Object checkSessionNotOnOrAfter(SAML2Object ob, int ssoMaxLifespan, .findFirst() .orElse(null); - Assert.assertNotNull(confirmationData); - Assert.assertEquals(XMLTimeUtil.add(condition.getNotBefore(), accessTokenLifespan * 1000L), confirmationData.getNotOnOrAfter()); + Assertions.assertNotNull(confirmationData); + Assertions.assertEquals(XMLTimeUtil.add(condition.getNotBefore(), accessTokenLifespan * 1000L), confirmationData.getNotOnOrAfter()); return null; } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/DeployedSAMLScriptMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/DeployedSAMLScriptMapperTest.java index ac1a9c242e31..c891848597d8 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/DeployedSAMLScriptMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/DeployedSAMLScriptMapperTest.java @@ -33,10 +33,10 @@ import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; -import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.common.Profile.Feature.SCRIPTS; import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT; @@ -46,7 +46,7 @@ import static org.keycloak.testsuite.util.SamlStreams.attributesUnecrypted; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author Marek Posolda @@ -107,7 +107,7 @@ public void testScriptMapperNotAvailableThroughAdminRest() { ); Response response = pmu.getResource().createMapper(mapperRep); - Assert.assertEquals(404, response.getStatus()); + Assertions.assertEquals(404, response.getStatus()); response.close(); } @@ -144,7 +144,7 @@ private void assertLoginSuccessWithAttributeAvailable() { .map(attribute -> attribute.getAttributeValue().get(0).toString()) .findFirst().orElseThrow(() -> new AssertionError("Attribute SCRIPT_ATTRIBUTE was not available in SAML assertion")); - Assert.assertEquals("hello_bburke", scriptAttrValue); + Assertions.assertEquals("hello_bburke", scriptAttrValue); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/DeployedScriptAuthenticatorTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/DeployedScriptAuthenticatorTest.java index f4d494bd7cea..4907b7009639 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/DeployedScriptAuthenticatorTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/DeployedScriptAuthenticatorTest.java @@ -58,15 +58,15 @@ import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; -import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.common.Profile.Feature.SCRIPTS; import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author Pedro Igor @@ -143,7 +143,7 @@ public void configureFlows() throws Exception { .build(); Response createFlowResponse = adminClient.realm(TEST_REALM_NAME).flows().createFlow(scriptBrowserFlow); - Assert.assertEquals(201, createFlowResponse.getStatus()); + Assertions.assertEquals(201, createFlowResponse.getStatus()); RealmRepresentation realm = adminClient.realm(TEST_REALM_NAME).toRepresentation(); realm.setBrowserFlow(scriptFlow); @@ -167,11 +167,11 @@ public void configureFlows() throws Exception { .build(); Response addExecutionResponse = testRealm().flows().addExecution(usernamePasswordFormExecution); - Assert.assertEquals(201, addExecutionResponse.getStatus()); + Assertions.assertEquals(201, addExecutionResponse.getStatus()); addExecutionResponse.close(); addExecutionResponse = testRealm().flows().addExecution(authScriptExecution); - Assert.assertEquals(201, addExecutionResponse.getStatus()); + Assertions.assertEquals(201, addExecutionResponse.getStatus()); addExecutionResponse.close(); testContext.setInitialized(true); @@ -210,9 +210,9 @@ public void testManyScriptAuthenticatorInstances() throws Exception { .collect(Collectors.toList()); // Both executions refers to same config of deployed script provider - Assert.assertEquals(2, scriptExecutions.size()); + Assertions.assertEquals(2, scriptExecutions.size()); for (AuthenticationExecutionInfoRepresentation execution : scriptExecutions) { - Assert.assertEquals(execution.getAuthenticationConfig(), "script-authenticator-a.js"); + Assertions.assertEquals(execution.getAuthenticationConfig(), "script-authenticator-a.js"); } // Assert updating config should fail due it's read-only @@ -220,7 +220,7 @@ public void testManyScriptAuthenticatorInstances() throws Exception { configRep.getConfig().put("scriptCode", "Something"); try { authMgmtResource.updateAuthenticatorConfig("script-authenticator-a.js", configRep); - Assert.fail("Update of configuration should have failed"); + Assertions.fail("Update of configuration should have failed"); } catch (BadRequestException bre) { // Expected } @@ -229,7 +229,7 @@ public void testManyScriptAuthenticatorInstances() throws Exception { Map newFlow = new HashMap<>(); newFlow.put("newName", "Copy of script flow"); Response resp = authMgmtResource.copy("scriptBrowser", newFlow); - Assert.assertEquals(201, resp.getStatus()); + Assertions.assertEquals(201, resp.getStatus()); resp.close(); AuthenticationFlowRepresentation copiedFlow = AbstractAuthenticationTest.findFlowByAlias("Copy of script flow", authMgmtResource.getFlows()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/DeployedScriptMapperTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/DeployedScriptMapperTest.java index 7980cfae7208..22ffb31ce4dc 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/DeployedScriptMapperTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/DeployedScriptMapperTest.java @@ -46,8 +46,8 @@ import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT; import static org.keycloak.testsuite.util.ProtocolMapperUtil.createScriptMapper; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/DeployedScriptPolicyTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/DeployedScriptPolicyTest.java index d0014dfc588f..25059527b71e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/DeployedScriptPolicyTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/DeployedScriptPolicyTest.java @@ -59,8 +59,8 @@ import static org.keycloak.common.Profile.Feature.SCRIPTS; import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/UndeployedScriptMapperNotAvailableTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/UndeployedScriptMapperNotAvailableTest.java index 99d59370e6a7..f05a62c7611a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/UndeployedScriptMapperNotAvailableTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/script/UndeployedScriptMapperNotAvailableTest.java @@ -44,7 +44,7 @@ import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT; import static org.keycloak.testsuite.util.ProtocolMapperUtil.createScriptMapper; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/sessionlimits/AbstractUserSessionLimitsBrokerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/sessionlimits/AbstractUserSessionLimitsBrokerTest.java index 7eb00551779c..81d75cb5d4c6 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/sessionlimits/AbstractUserSessionLimitsBrokerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/sessionlimits/AbstractUserSessionLimitsBrokerTest.java @@ -12,8 +12,8 @@ import static org.keycloak.testsuite.sessionlimits.UserSessionLimitsUtil.assertSessionCount; import static org.keycloak.testsuite.sessionlimits.UserSessionLimitsUtil.configureSessionLimits; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; public abstract class AbstractUserSessionLimitsBrokerTest extends AbstractInitializedBaseBrokerTest { @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/sessionlimits/UserSessionLimitsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/sessionlimits/UserSessionLimitsTest.java index f56bfaca55a5..1fe628656cc1 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/sessionlimits/UserSessionLimitsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/sessionlimits/UserSessionLimitsTest.java @@ -57,7 +57,7 @@ import static org.keycloak.testsuite.sessionlimits.UserSessionLimitsUtil.assertSessionCount; import static org.keycloak.testsuite.sessionlimits.UserSessionLimitsUtil.configureSessionLimits; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class UserSessionLimitsTest extends AbstractTestRealmKeycloakTest { private String realmName = "test"; diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/sessionlimits/UserSessionLimitsUtil.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/sessionlimits/UserSessionLimitsUtil.java index 292734cd7eee..c88096741526 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/sessionlimits/UserSessionLimitsUtil.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/sessionlimits/UserSessionLimitsUtil.java @@ -11,7 +11,7 @@ import org.keycloak.models.UserModel; import org.keycloak.testsuite.runonserver.RunOnServer; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class UserSessionLimitsUtil { protected static final String ERROR_TO_DISPLAY = "This account has too many sessions"; diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/ssl/TLSTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/ssl/TLSTest.java index d29ce105a381..ee76ee1f47f2 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/ssl/TLSTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/ssl/TLSTest.java @@ -5,12 +5,12 @@ import org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.oauth.OpenIDProviderConfigurationResponse; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.util.ServerURLs.AUTH_SERVER_SSL_REQUIRED; @@ -47,7 +47,7 @@ public void testTurningTLSOn() throws Exception { OIDCConfigurationRepresentation config = oauth.doWellKnownRequest(); //then - Assert.assertTrue(config.getAuthorizationEndpoint().startsWith(AUTH_SERVER_ROOT_WITHOUT_TLS)); + Assertions.assertTrue(config.getAuthorizationEndpoint().startsWith(AUTH_SERVER_ROOT_WITHOUT_TLS)); } @Test @@ -61,13 +61,13 @@ public void testSSLAlwaysRequired() throws Exception { // Try access "WellKnown" endpoint unsecured. It should fail oauth.baseUrl(AUTH_SERVER_ROOT_WITHOUT_TLS); OpenIDProviderConfigurationResponse providerConfigurationResponse = oauth.wellknownRequest().send(); - Assert.assertFalse(providerConfigurationResponse.isSuccess()); - Assert.assertEquals("HTTPS required", providerConfigurationResponse.getErrorDescription()); + Assertions.assertFalse(providerConfigurationResponse.isSuccess()); + Assertions.assertEquals("HTTPS required", providerConfigurationResponse.getErrorDescription()); // Try access "JWKS URL" unsecured. It should fail try { JSONWebKeySet keySet = oauth.keys().getRealmKeys(); - Assert.fail("This should not be successful"); + Assertions.fail("This should not be successful"); } catch (Exception e) { // Expected } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/ssl/TrustStoreEmailTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/ssl/TrustStoreEmailTest.java index 1a8ef6295cf9..58ef670f1ab5 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/ssl/TrustStoreEmailTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/ssl/TrustStoreEmailTest.java @@ -25,7 +25,6 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.AdminApiUtil; import org.keycloak.testsuite.auth.page.AuthRealm; @@ -43,12 +42,13 @@ import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runners.MethodSorters; import static org.keycloak.testsuite.util.MailAssert.assertEmailAndGetUrl; import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlStartsWith; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @@ -171,7 +171,7 @@ public void test01VerifyEmailWithSslWrongCertificate() throws Exception { .assertEvent(); // Email wasn't send - Assert.assertNull(SslMailServer.getLastReceivedMessage()); + Assertions.assertNull(SslMailServer.getLastReceivedMessage()); // Email wasn't sent, and we notify end user about that. assertEquals("Failed to send email, please try again later.", @@ -209,7 +209,7 @@ public void test03erifyEmailWithSslWrongHostname() throws Exception { .assertEvent(); // Email wasn't send - Assert.assertNull(SslMailServer.getLastReceivedMessage()); + Assertions.assertNull(SslMailServer.getLastReceivedMessage()); // Email wasn't sent, and we notify end user about that. assertEquals("Failed to send email, please try again later.", diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/CustomAccountResourceProviderTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/CustomAccountResourceProviderTest.java index 778d72fd0e92..e759d5c6314a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/CustomAccountResourceProviderTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/CustomAccountResourceProviderTest.java @@ -4,8 +4,8 @@ import org.keycloak.services.resource.AccountResourceProvider; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; public class CustomAccountResourceProviderTest extends AbstractTestRealmKeycloakTest { @@ -18,7 +18,7 @@ public void configureTestRealm(RealmRepresentation testRealm) { public void testProviderOverride() { testingClient.server().run(session -> { AccountResourceProvider arp = session.getProvider(AccountResourceProvider.class, "ext-custom-account-console"); - Assert.assertTrue(arp instanceof CustomAccountResourceProviderFactory); + Assertions.assertTrue(arp instanceof CustomAccountResourceProviderFactory); }); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/CustomRegistrationTemplateTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/CustomRegistrationTemplateTest.java index 4dfe5b2b11fd..4406cef830b4 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/CustomRegistrationTemplateTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/CustomRegistrationTemplateTest.java @@ -41,10 +41,10 @@ import static org.keycloak.userprofile.config.UPConfigUtils.ROLE_ADMIN; import static org.keycloak.userprofile.config.UPConfigUtils.ROLE_USER; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; public class CustomRegistrationTemplateTest extends AbstractTestRealmKeycloakTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/CustomUpdateProfileTemplateTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/CustomUpdateProfileTemplateTest.java index 79f5e6bc445f..067fb1ef27bf 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/CustomUpdateProfileTemplateTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/CustomUpdateProfileTemplateTest.java @@ -50,10 +50,10 @@ import static org.keycloak.userprofile.config.UPConfigUtils.ROLE_ADMIN; import static org.keycloak.userprofile.config.UPConfigUtils.ROLE_USER; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; public class CustomUpdateProfileTemplateTest extends AbstractTestRealmKeycloakTest { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/DefaultThemeManagerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/DefaultThemeManagerTest.java index 95bca9652425..5d84dbcc32ba 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/DefaultThemeManagerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/DefaultThemeManagerTest.java @@ -10,9 +10,9 @@ import org.keycloak.theme.Theme; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.hamcrest.MatcherAssert.assertThat; @@ -41,12 +41,12 @@ public void systemPropertiesSubstitutionInThemeProperties() { testingClient.server().run(session -> { try { Theme theme = session.theme().getTheme(THEME_NAME, Theme.Type.LOGIN); - Assert.assertEquals("getTheme(...) returns default theme when no matching theme found, but we need " + THEME_NAME + " theme deployed.",THEME_NAME, theme.getName()); - Assert.assertEquals("Keycloak is awesome", theme.getProperties().getProperty("system.property.found")); - Assert.assertEquals("${missing_system_property}", theme.getProperties().getProperty("system.property.missing")); - Assert.assertEquals("defaultValue", theme.getProperties().getProperty("system.property.missing.with.default")); + Assertions.assertEquals(THEME_NAME, theme.getName(), "getTheme(...) returns default theme when no matching theme found, but we need " + THEME_NAME + " theme deployed."); + Assertions.assertEquals("Keycloak is awesome", theme.getProperties().getProperty("system.property.found")); + Assertions.assertEquals("${missing_system_property}", theme.getProperties().getProperty("system.property.missing")); + Assertions.assertEquals("defaultValue", theme.getProperties().getProperty("system.property.missing.with.default")); } catch (IOException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } }); } @@ -61,7 +61,7 @@ public void verifyLocaleNames() { assertThat(messages.getProperty("locale_zh-TW"), Matchers.containsString("Chinese (Traditional)")); assertThat(messages.getProperty("locale_zh-CN"), Matchers.containsString("Chinese (Simplified)")); } catch (IOException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } }); } @@ -72,20 +72,20 @@ public void environmentVariablesSubstitutionInThemeProperties() { testingClient.server().run(session -> { try { Theme theme = session.theme().getTheme(THEME_NAME, Theme.Type.LOGIN); - Assert.assertEquals("getTheme(...) returns default theme when no matching theme found, but we need " + THEME_NAME + " theme deployed.",THEME_NAME, theme.getName()); - Assert.assertEquals("${env.MISSING_ENVIRONMENT_VARIABLE}", theme.getProperties().getProperty("env.missing")); - Assert.assertEquals("defaultValue", theme.getProperties().getProperty("env.missingWithDefault")); + Assertions.assertEquals(THEME_NAME, theme.getName(), "getTheme(...) returns default theme when no matching theme found, but we need " + THEME_NAME + " theme deployed."); + Assertions.assertEquals("${env.MISSING_ENVIRONMENT_VARIABLE}", theme.getProperties().getProperty("env.missing")); + Assertions.assertEquals("defaultValue", theme.getProperties().getProperty("env.missingWithDefault")); if (System.getenv().containsKey("HOMEPATH")) { // Windows - Assert.assertEquals(System.getenv().get("HOMEPATH"), theme.getProperties().getProperty("env.windowsHome")); + Assertions.assertEquals(System.getenv().get("HOMEPATH"), theme.getProperties().getProperty("env.windowsHome")); } else if (System.getenv().containsKey("HOME")) { // Unix - Assert.assertEquals(System.getenv().get("HOME"), theme.getProperties().getProperty("env.unixHome")); + Assertions.assertEquals(System.getenv().get("HOME"), theme.getProperties().getProperty("env.unixHome")); } else { - Assert.fail("No default env variable found, can't verify"); + Assertions.fail("No default env variable found, can't verify"); } } catch (IOException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } }); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/ThemeResourceProviderTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/ThemeResourceProviderTest.java index e530f5a3ddb6..81017dcd6a12 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/ThemeResourceProviderTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/theme/ThemeResourceProviderTest.java @@ -24,13 +24,13 @@ import org.apache.http.util.EntityUtils; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ThemeResourceProviderTest extends AbstractTestRealmKeycloakTest { @@ -44,9 +44,9 @@ public void getTheme() { testingClient.server().run(session -> { try { Theme theme = session.theme().getTheme("base", Theme.Type.LOGIN); - Assert.assertNotNull(theme.getTemplate("test.ftl")); + Assertions.assertNotNull(theme.getTemplate("test.ftl")); } catch (IOException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } }); } @@ -57,10 +57,10 @@ public void testThemeFallback() { try { // Fallback to default theme when requested theme don't exists Theme theme = session.theme().getTheme("address", Theme.Type.ADMIN); - Assert.assertNotNull(theme); - Assert.assertEquals("keycloak.v2", theme.getName()); + Assertions.assertNotNull(theme); + Assertions.assertEquals("keycloak.v2", theme.getName()); } catch (IOException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } }); } @@ -70,9 +70,9 @@ public void getResourceAsStream() { testingClient.server().run(session -> { try { Theme theme = session.theme().getTheme("base", Theme.Type.LOGIN); - Assert.assertNotNull(theme.getResourceAsStream("test.js")); + Assertions.assertNotNull(theme.getResourceAsStream("test.js")); } catch (IOException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } }); } @@ -82,10 +82,10 @@ public void getMessages() { testingClient.server().run(session -> { try { Theme theme = session.theme().getTheme("base", Theme.Type.LOGIN); - Assert.assertNotNull(theme.getMessages("messages", Locale.ENGLISH).get("test.keycloak-8818")); - Assert.assertNotEquals("Full name (Theme-resources)", theme.getMessages("messages", Locale.ENGLISH).get("fullName")); + Assertions.assertNotNull(theme.getMessages("messages", Locale.ENGLISH).get("test.keycloak-8818")); + Assertions.assertNotEquals("Full name (Theme-resources)", theme.getMessages("messages", Locale.ENGLISH).get("fullName")); } catch (IOException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } }); } @@ -95,9 +95,9 @@ public void getResourceIllegalTraversal() { testingClient.server().run(session -> { try { Theme theme = session.theme().getTheme("base", Theme.Type.LOGIN); - Assert.assertNull(theme.getResourceAsStream("../templates/test.ftl")); + Assertions.assertNull(theme.getResourceAsStream("../templates/test.ftl")); } catch (IOException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } }); } @@ -318,7 +318,7 @@ public void getMessagesLocaleResolving() { assertNull(theme.getMessages("messages", Locale.ENGLISH).get("fallback en")); } catch (IOException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } }); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/url/HostnameV2Test.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/url/HostnameV2Test.java index 7a4f840eabc7..f0d12a6ab0c7 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/url/HostnameV2Test.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/url/HostnameV2Test.java @@ -33,8 +33,8 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.jboss.arquillian.container.spi.client.container.DeployableContainer; import org.junit.After; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.util.ServerURLs.AUTH_SERVER_PORT; import static org.keycloak.testsuite.util.ServerURLs.AUTH_SERVER_SCHEME; @@ -42,7 +42,7 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * This is testing just the V2 implementation of Hostname SPI. It is NOT testing if the Hostname SPI as such is used correctly. @@ -207,7 +207,7 @@ private void testStartupFailure(String expectedError, String hostname, String ho try { updateServerHostnameSettings(hostname, hostnameAdmin, hostnameBackchannelDynamic, hostnameStrict); - Assert.fail("Server didn't fail"); + Assertions.fail("Server didn't fail"); } catch (Exception e) { if (container instanceof RemoteContainer) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/CustomUserProfileTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/CustomUserProfileTest.java index eebf409bb7de..7b46885e1e27 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/CustomUserProfileTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/CustomUserProfileTest.java @@ -35,9 +35,9 @@ import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Jörg Matysiak diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/UIRealmResourceTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/UIRealmResourceTest.java index 2fe12b7b7d45..bcdff5771ebf 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/UIRealmResourceTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/UIRealmResourceTest.java @@ -60,16 +60,16 @@ import org.hamcrest.Matchers; import org.jboss.arquillian.graphene.page.Page; import org.junit.AfterClass; -import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.testsuite.util.ServerURLs.getAuthServerContextRoot; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @@ -173,7 +173,7 @@ public void testUpdateUserProfileModification() throws IOException { updateRealmExt(toUIRealmRepresentation(rep, upConfig)); AdminEventRepresentation adminEvent = assertAdminEvents.assertEvent(TEST_REALM_NAME, OperationType.UPDATE, Matchers.nullValue(String.class), ResourceType.REALM); - Assert.assertNotNull(adminEvent.getRepresentation()); + Assertions.assertNotNull(adminEvent.getRepresentation()); adminEvent = assertAdminEvents.assertEvent(TEST_REALM_NAME, OperationType.UPDATE, "ui-ext", ResourceType.USER_PROFILE); assertEquals(upConfig, toUpConfig(adminEvent.getRepresentation())); @@ -230,12 +230,12 @@ public void testRegistrationFormWithNotReadableOrWritableRequiredEmail() throws loginPage.form().register(); registerPage.assertCurrent(); - Assert.assertTrue("Email is missing on the registration page.", registerPage.isEmailPresent()); + Assertions.assertTrue(registerPage.isEmailPresent(), "Email is missing on the registration page."); registerPage.registerWithEmailAsUsername("Tom", "Brady", "tbrady@email.com", "password", "password"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); String userId = events.expectRegister("tbrady@email.com", "tbrady@email.com").assertEvent().getUserId(); UserRepresentation user = testRealm().users().get(userId).toRepresentation(); @@ -260,13 +260,13 @@ public void testRegistrationFormWithReadonlyUsernameAndEmail() throws IOExceptio loginPage.form().register(); registerPage.assertCurrent(); - Assert.assertTrue("Username is missing on the registration page.", registerPage.isUsernamePresent()); - Assert.assertFalse("Email should not be present on the registration page.", registerPage.isEmailPresent()); + Assertions.assertTrue(registerPage.isUsernamePresent(), "Username is missing on the registration page."); + Assertions.assertFalse(registerPage.isEmailPresent(), "Email should not be present on the registration page."); registerPage.register("Alice", "Wood", null, "awood", "password", "password"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); String userId = events.expectRegister("awood", null).removeDetail("email").assertEvent().getUserId(); UserRepresentation user = testRealm().users().get(userId).toRepresentation(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/UserProfileTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/UserProfileTest.java index e6d1f1892bac..281b09567271 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/UserProfileTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/UserProfileTest.java @@ -83,8 +83,8 @@ import org.keycloak.validate.validators.UriValidator; import org.hamcrest.Matchers; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static java.util.Optional.ofNullable; @@ -95,12 +95,12 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Pedro Igor @@ -145,7 +145,7 @@ public void testReadOnlyAllowed() throws Exception { Response response = realmRes.users().create(userRep); final String userId = ApiUtil.getCreatedId(response); userRep = realmRes.users().get(userId).toRepresentation(); - Assert.assertEquals(Collections.singletonList("123"), userRep.getAttributes().get("foo")); + Assertions.assertEquals(Collections.singletonList("123"), userRep.getAttributes().get("foo")); // it should work if foo is read-only in the context getTestingClient().server(TEST_REALM_NAME).run(session -> { @@ -188,7 +188,7 @@ public void testReadOnlyAllowed() throws Exception { UserProfile profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes, user); try { profile.validate(); - Assert.fail("Should fail validation on foo minimum length"); + Assertions.fail("Should fail validation on foo minimum length"); } catch (ValidationException ve) { assertTrue(ve.isAttributeOnError("foo")); assertTrue(ve.hasError(LengthValidator.MESSAGE_INVALID_LENGTH)); @@ -230,7 +230,7 @@ private static void testCustomAttributeInAnyContext(KeycloakSession session) { try { profile.validate(); - Assert.fail("Should fail validation"); + Assertions.fail("Should fail validation"); } catch (ValidationException ve) { // address is mandatory assertTrue(ve.isAttributeOnError("address")); @@ -315,7 +315,7 @@ private static void testResolveProfile(KeycloakSession session) { try { profile.validate(); - Assert.fail("Should fail validation"); + Assertions.fail("Should fail validation"); } catch (ValidationException ve) { // address is mandatory assertTrue(ve.isAttributeOnError("business.address")); @@ -350,7 +350,7 @@ private static void failValidationWhenEmptyAttributes(KeycloakSession session) { try { profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes); profile.validate(); - Assert.fail("Should fail validation"); + Assertions.fail("Should fail validation"); } catch (ValidationException ve) { // username is mandatory assertTrue(ve.isAttributeOnError(UserModel.USERNAME)); @@ -363,7 +363,7 @@ private static void failValidationWhenEmptyAttributes(KeycloakSession session) { attributes.put(UserModel.EMAIL, "profile-user@keycloak.org"); profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes); profile.validate(); - Assert.fail("Should fail validation"); + Assertions.fail("Should fail validation"); } catch (ValidationException ve) { // username is mandatory assertTrue(ve.isAttributeOnError(UserModel.USERNAME)); @@ -378,7 +378,7 @@ private static void failValidationWhenEmptyAttributes(KeycloakSession session) { profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes); profile.validate(); } catch (ValidationException ve) { - Assert.fail("Should be OK email as username"); + Assertions.fail("Should be OK email as username"); } finally { // we should probably avoid this kind of logic and make the test reset the realm to original state realm.setRegistrationEmailAsUsername(false); @@ -434,7 +434,7 @@ private static void testEmailAsUsernameValidation(KeycloakSession session) { profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes); profile.validate(); } catch (ValidationException ve) { - Assert.fail("Should be OK email as username"); + Assertions.fail("Should be OK email as username"); } finally { realm.setRegistrationEmailAsUsername(false); } @@ -483,7 +483,7 @@ private static void testValidateComplianceWithUserProfile(KeycloakSession sessio try { profile.validate(); - Assert.fail("Should fail validation"); + Assertions.fail("Should fail validation"); } catch (ValidationException ve) { // username is mandatory assertTrue(ve.isAttributeOnError("address")); @@ -524,7 +524,7 @@ private static void testGetProfileAttributes(KeycloakSession session) { try { profile.validate(); - Assert.fail("Should fail validation"); + Assertions.fail("Should fail validation"); } catch (ValidationException ve) { // username is mandatory assertTrue(ve.isAttributeOnError("address")); @@ -751,7 +751,7 @@ private static void testReadonlyEmailCannotBeUpdated(KeycloakSession session) { } catch (ValidationException ve) { assertTrue(ve.isAttributeOnError("email")); } - assertEquals("E-Mail address shouldn't be changed", "readonly@foo.bar", user.getEmail()); + assertEquals("readonly@foo.bar", user.getEmail(), "E-Mail address shouldn't be changed"); attributes.put(UserModel.EMAIL, "admin-can-change@foo.bar"); profile = provider.create(UserProfileContext.USER_API, attributes, user); @@ -1424,7 +1424,7 @@ private static void testNullAttributesInConfig(KeycloakSession session) { config.setAttributes(Collections.emptyList()); try { provider.setConfiguration(config); - Assert.fail("Expected to fail as we are trying to remove required attributes email and username"); + Assertions.fail("Expected to fail as we are trying to remove required attributes email and username"); } catch (ComponentValidationException cve) { //ignore } @@ -1585,12 +1585,12 @@ public void testEmailRequired(KeycloakSession session) { UPConfig config = UPConfigUtils.parseSystemDefaultConfig(); provider.setConfiguration(config); UPAttribute emailOrigConfig = config.getAttribute(UserModel.EMAIL); - Assert.assertEquals(emailOrigConfig.getRequired().getRoles(), Set.of(ROLE_USER)); // Should be required only for users by default + Assertions.assertEquals(emailOrigConfig.getRequired().getRoles(), Set.of(ROLE_USER)); // Should be required only for users by default try { profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes); profile.validate(); - Assert.fail("Should not be here as email is required for users"); + Assertions.fail("Should not be here as email is required for users"); } catch (ValidationException ve) { // expected } @@ -1598,7 +1598,7 @@ public void testEmailRequired(KeycloakSession session) { profile = provider.create(UserProfileContext.USER_API, attributes); profile.validate(); } catch (ValidationException ve) { - Assert.fail("Should not be here as email is NOT required for administrators"); + Assertions.fail("Should not be here as email is NOT required for administrators"); } // Test email required in config, registrationEmailAsUsername = false : Email should be required @@ -1608,14 +1608,14 @@ public void testEmailRequired(KeycloakSession session) { try { profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes); profile.validate(); - Assert.fail("Should not be here as email is required for users"); + Assertions.fail("Should not be here as email is required for users"); } catch (ValidationException ve) { // expected } try { profile = provider.create(UserProfileContext.USER_API, attributes); profile.validate(); - Assert.fail("Should not be here as email is required for administrators"); + Assertions.fail("Should not be here as email is required for administrators"); } catch (ValidationException ve) { // expected } @@ -1626,14 +1626,14 @@ public void testEmailRequired(KeycloakSession session) { try { profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes); profile.validate(); - Assert.fail("Should not be here as email is required for users"); + Assertions.fail("Should not be here as email is required for users"); } catch (ValidationException ve) { // expected } try { profile = provider.create(UserProfileContext.USER_API, attributes); profile.validate(); - Assert.fail("Should not be here as email is required for administrators"); + Assertions.fail("Should not be here as email is required for administrators"); } catch (ValidationException ve) { // expected } @@ -1649,14 +1649,14 @@ public void testEmailRequired(KeycloakSession session) { try { profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes); profile.validate(); - Assert.fail("Should not be here as email is required for users"); + Assertions.fail("Should not be here as email is required for users"); } catch (ValidationException ve) { // expected } try { profile = provider.create(UserProfileContext.USER_API, attributes); profile.validate(); - Assert.fail("Should not be here as email is required for administrators"); + Assertions.fail("Should not be here as email is required for administrators"); } catch (ValidationException ve) { // expected } @@ -1669,13 +1669,13 @@ public void testEmailRequired(KeycloakSession session) { profile = provider.create(UserProfileContext.UPDATE_PROFILE, attributes); profile.validate(); } catch (ValidationException ve) { - Assert.fail("Should not be here as email is required for users"); + Assertions.fail("Should not be here as email is required for users"); } try { profile = provider.create(UserProfileContext.USER_API, attributes); profile.validate(); } catch (ValidationException ve) { - Assert.fail("Should not be here as email is required for administrators"); + Assertions.fail("Should not be here as email is required for administrators"); } } @@ -1959,7 +1959,7 @@ private static void testConfigurationInvalidScope(KeycloakSession session) { try { provider.setConfiguration(config); - Assert.fail("Expected to fail due to invalid client scope"); + Assertions.fail("Expected to fail due to invalid client scope"); } catch (ComponentValidationException cve) { //ignore } @@ -2514,8 +2514,8 @@ private static void testEmailFieldHiddenWhenEmptyAndReadOnlyWithUpdateEmailEnabl Map> readableAttributes = profile.getAttributes().getReadable(); // Email should NOT be visible in UPDATE_PROFILE context when empty and read-only - assertFalse("Email field should be hidden when empty, read-only, and UPDATE_EMAIL is enabled", - readableAttributes.containsKey(UserModel.EMAIL)); + assertFalse(readableAttributes.containsKey(UserModel.EMAIL), + "Email field should be hidden when empty, read-only, and UPDATE_EMAIL is enabled"); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/config/UPConfigParserTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/config/UPConfigParserTest.java index 530ec179fe02..710635d60927 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/config/UPConfigParserTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/config/UPConfigParserTest.java @@ -38,8 +38,8 @@ import org.keycloak.userprofile.config.UPConfigUtils; import com.fasterxml.jackson.databind.JsonMappingException; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.userprofile.config.UPConfigUtils.readConfig; import static org.keycloak.userprofile.config.UPConfigUtils.validate; @@ -65,18 +65,18 @@ public void configureTestRealm(RealmRepresentation testRealm) { @Test public void attributeNameIsValid() { // few invalid cases - Assert.assertFalse(UPConfigUtils.isValidAttributeName("")); - Assert.assertFalse(UPConfigUtils.isValidAttributeName(" ")); - Assert.assertFalse(UPConfigUtils.isValidAttributeName("a b")); - Assert.assertFalse(UPConfigUtils.isValidAttributeName("a*b")); - Assert.assertFalse(UPConfigUtils.isValidAttributeName("a%b")); - Assert.assertFalse(UPConfigUtils.isValidAttributeName("a$b")); + Assertions.assertFalse(UPConfigUtils.isValidAttributeName("")); + Assertions.assertFalse(UPConfigUtils.isValidAttributeName(" ")); + Assertions.assertFalse(UPConfigUtils.isValidAttributeName("a b")); + Assertions.assertFalse(UPConfigUtils.isValidAttributeName("a*b")); + Assertions.assertFalse(UPConfigUtils.isValidAttributeName("a%b")); + Assertions.assertFalse(UPConfigUtils.isValidAttributeName("a$b")); // few valid cases - Assert.assertTrue(UPConfigUtils.isValidAttributeName("a-b")); - Assert.assertTrue(UPConfigUtils.isValidAttributeName("a.b")); - Assert.assertTrue(UPConfigUtils.isValidAttributeName("a_b")); - Assert.assertTrue(UPConfigUtils.isValidAttributeName("a3B")); + Assertions.assertTrue(UPConfigUtils.isValidAttributeName("a-b")); + Assertions.assertTrue(UPConfigUtils.isValidAttributeName("a.b")); + Assertions.assertTrue(UPConfigUtils.isValidAttributeName("a_b")); + Assertions.assertTrue(UPConfigUtils.isValidAttributeName("a3B")); } @Test @@ -84,70 +84,70 @@ public void loadConfigurationFromJsonFile() throws IOException { UPConfig config = readConfig(getValidConfigFileIS()); // only basic assertion to check config is loaded, more detailed tests follow - Assert.assertEquals(5, config.getAttributes().size()); + Assertions.assertEquals(5, config.getAttributes().size()); } @Test public void parseConfigurationFile_OK() throws IOException { UPConfig config = loadValidConfig(); - Assert.assertNotNull(config); + Assertions.assertNotNull(config); // assert *** attributes *** - Assert.assertEquals(5, config.getAttributes().size()); + Assertions.assertEquals(5, config.getAttributes().size()); UPAttribute att = config.getAttributes().get(1); - Assert.assertNotNull(att); - Assert.assertEquals("email", att.getName()); + Assertions.assertNotNull(att); + Assertions.assertEquals("email", att.getName()); // validation - Assert.assertEquals(3, att.getValidations().size()); - Assert.assertEquals(1, att.getValidations().get("length").size()); - Assert.assertEquals(255, att.getValidations().get("length").get("max")); + Assertions.assertEquals(3, att.getValidations().size()); + Assertions.assertEquals(1, att.getValidations().get("length").size()); + Assertions.assertEquals(255, att.getValidations().get("length").get("max")); // annotations - Assert.assertEquals("userEmailFormFieldHint", att.getAnnotations().get("formHintKey")); + Assertions.assertEquals("userEmailFormFieldHint", att.getAnnotations().get("formHintKey")); att = config.getAttributes().get(4); // required - Assert.assertNotNull(att.getRequired()); - Assert.assertFalse(att.getRequired().isAlways()); - Assert.assertNotNull(att.getRequired().getScopes()); - Assert.assertNotNull(att.getRequired().getRoles()); - Assert.assertEquals(2, att.getRequired().getRoles().size()); + Assertions.assertNotNull(att.getRequired()); + Assertions.assertFalse(att.getRequired().isAlways()); + Assertions.assertNotNull(att.getRequired().getScopes()); + Assertions.assertNotNull(att.getRequired().getRoles()); + Assertions.assertEquals(2, att.getRequired().getRoles().size()); att = config.getAttributes().get(3); - Assert.assertTrue(att.getRequired().isAlways()); + Assertions.assertTrue(att.getRequired().isAlways()); // permissions - Assert.assertNotNull(att.getPermissions()); - Assert.assertNotNull(att.getPermissions().getEdit()); - Assert.assertEquals(1, att.getPermissions().getEdit().size()); - Assert.assertTrue(att.getPermissions().getEdit().contains("admin")); - Assert.assertNotNull(att.getPermissions().getView()); - Assert.assertEquals(2, att.getPermissions().getView().size()); - Assert.assertTrue(att.getPermissions().getView().contains("admin")); - Assert.assertTrue(att.getPermissions().getView().contains("user")); + Assertions.assertNotNull(att.getPermissions()); + Assertions.assertNotNull(att.getPermissions().getEdit()); + Assertions.assertEquals(1, att.getPermissions().getEdit().size()); + Assertions.assertTrue(att.getPermissions().getEdit().contains("admin")); + Assertions.assertNotNull(att.getPermissions().getView()); + Assertions.assertEquals(2, att.getPermissions().getView().size()); + Assertions.assertTrue(att.getPermissions().getView().contains("admin")); + Assertions.assertTrue(att.getPermissions().getView().contains("user")); //selector att = config.getAttributes().get(4); - Assert.assertNotNull(att.getSelector().getScopes()); - Assert.assertEquals(3, att.getSelector().getScopes().size()); - Assert.assertTrue(att.getSelector().getScopes().contains("phone-3-sel")); + Assertions.assertNotNull(att.getSelector().getScopes()); + Assertions.assertEquals(3, att.getSelector().getScopes().size()); + Assertions.assertTrue(att.getSelector().getScopes().contains("phone-3-sel")); //displayName att = config.getAttributes().get(4); - Assert.assertEquals("${profile.phone}", att.getDisplayName()); + Assertions.assertEquals("${profile.phone}", att.getDisplayName()); // group - Assert.assertEquals("contact", att.getGroup()); + Assertions.assertEquals("contact", att.getGroup()); // assert *** groups *** - Assert.assertEquals(1, config.getGroups().size()); + Assertions.assertEquals(1, config.getGroups().size()); UPGroup group = config.getGroups().get(0); - Assert.assertEquals("contact", group.getName()); - Assert.assertEquals("Contact information", group.getDisplayHeader()); - Assert.assertEquals("Required to contact you in case of emergency", group.getDisplayDescription()); - Assert.assertEquals(1, group.getAnnotations().size()); - Assert.assertEquals("value1", group.getAnnotations().get("contactanno1")); + Assertions.assertEquals("contact", group.getName()); + Assertions.assertEquals("Contact information", group.getDisplayHeader()); + Assertions.assertEquals("Required to contact you in case of emergency", group.getDisplayDescription()); + Assertions.assertEquals(1, group.getAnnotations().size()); + Assertions.assertEquals("value1", group.getAnnotations().get("contactanno1")); } /** @@ -186,7 +186,7 @@ public void validateConfiguration_OK() { public static void validateConfiguration_OK(KeycloakSession session) throws IOException { List errors = validate(session, loadValidConfig()); - Assert.assertTrue(errors.isEmpty()); + Assertions.assertTrue(errors.isEmpty()); } @Test @@ -202,21 +202,21 @@ public static void validateConfiguration_attributeNameErrors(KeycloakSession ses attConfig.setName(null); List errors = validate(session, config); - Assert.assertEquals(1, errors.size()); + Assertions.assertEquals(1, errors.size()); attConfig.setName(" "); errors = validate(session, config); - Assert.assertEquals(1, errors.size()); + Assertions.assertEquals(1, errors.size()); // duplicate attribute name attConfig.setName("lastName"); errors = validate(session, config); - Assert.assertEquals(1, errors.size()); + Assertions.assertEquals(1, errors.size()); // attribute name format error - unallowed character attConfig.setName("ema il"); errors = validate(session, config); - Assert.assertEquals(1, errors.size()); + Assertions.assertEquals(1, errors.size()); } @Test @@ -233,32 +233,32 @@ public static void validateConfiguration_attributePermissionsErrors(KeycloakSess // no permissions configures at all attConfig.setPermissions(null); List errors = validate(session, config); - Assert.assertEquals(0, errors.size()); + Assertions.assertEquals(0, errors.size()); // no permissions structure fields configured UPAttributePermissions permsConfig = new UPAttributePermissions(); attConfig.setPermissions(permsConfig); errors = validate(session, config); - Assert.assertTrue(errors.isEmpty()); + Assertions.assertTrue(errors.isEmpty()); // valid if both are present, even empty permsConfig.setEdit(Collections.emptySet()); permsConfig.setView(Collections.emptySet()); attConfig.setPermissions(permsConfig); errors = validate(session, config); - Assert.assertEquals(0, errors.size()); + Assertions.assertEquals(0, errors.size()); Set withInvRole = Collections.singleton("invalid"); // invalid role used for view permsConfig.setView(withInvRole); errors = validate(session, config); - Assert.assertEquals(1, errors.size()); + Assertions.assertEquals(1, errors.size()); // invalid role used for edit also permsConfig.setEdit(withInvRole); errors = validate(session, config); - Assert.assertEquals(2, errors.size()); + Assertions.assertEquals(2, errors.size()); } @Test @@ -275,20 +275,20 @@ public static void validateConfiguration_attributeRequirementsErrors(KeycloakSes // it is OK without requirements configures at all attConfig.setRequired(null); List errors = validate(session, config); - Assert.assertEquals(0, errors.size()); + Assertions.assertEquals(0, errors.size()); // it is OK with empty config as it means ALWAYS required UPAttributeRequired reqConfig = new UPAttributeRequired(); attConfig.setRequired(reqConfig); errors = validate(session, config); - Assert.assertEquals(0, errors.size()); - Assert.assertTrue(reqConfig.isAlways()); + Assertions.assertEquals(0, errors.size()); + Assertions.assertTrue(reqConfig.isAlways()); // invalid role used reqConfig.setRoles(Collections.singleton("invalid")); errors = validate(session, config); - Assert.assertEquals(1, errors.size()); - Assert.assertFalse(reqConfig.isAlways()); + Assertions.assertEquals(1, errors.size()); + Assertions.assertFalse(reqConfig.isAlways()); } @@ -312,7 +312,7 @@ private static void validateConfiguration_attributeValidationsErrors(KeycloakSes // empty validator name validationConfig.put(" ",null); List errors = validate(session, config); - Assert.assertEquals(1, errors.size()); + Assertions.assertEquals(1, errors.size()); // wrong configuration for "length" validator @@ -321,7 +321,7 @@ private static void validateConfiguration_attributeValidationsErrors(KeycloakSes vc.put("min", "aaa"); validationConfig.put("length", vc ); errors = validate(session, config); - Assert.assertEquals(1, errors.size()); + Assertions.assertEquals(1, errors.size()); } @Test @@ -336,8 +336,8 @@ private static void validateConfiguration_attributeGroupConfigurationErrors(Keyc UPGroup groupWithoutName = new UPGroup(); config.addGroup(groupWithoutName); List errors = validate(session, config); - Assert.assertEquals(1, errors.size()); - Assert.assertEquals("Name is mandatory for groups, found 1 group(s) without name.", errors.get(0)); + Assertions.assertEquals(1, errors.size()); + Assertions.assertEquals("Name is mandatory for groups, found 1 group(s) without name.", errors.get(0)); } @Test @@ -352,8 +352,8 @@ private static void validateConfiguration_attributeGroupReferenceErrors(Keycloak UPAttribute firstAttribute = config.getAttributes().get(0); firstAttribute.setGroup("non-existing-group"); List errors = validate(session, config); - Assert.assertEquals(1, errors.size()); - Assert.assertEquals("Attribute 'username' references unknown group 'non-existing-group'", errors.get(0)); + Assertions.assertEquals(1, errors.size()); + Assertions.assertEquals("Attribute 'username' references unknown group 'non-existing-group'", errors.get(0)); } @Test @@ -370,7 +370,7 @@ private static void validateConfiguration_attributeAnnotationsErrors(KeycloakSes att.getAnnotations().put("inputOptionLabels", ""); List errors = validate(session, config); - Assert.assertEquals(2, errors.size()); + Assertions.assertEquals(2, errors.size()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/config/UPConfigUtilsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/config/UPConfigUtilsTest.java index c7b0f46fa354..8f289ac240bc 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/config/UPConfigUtilsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/user/profile/config/UPConfigUtilsTest.java @@ -22,8 +22,8 @@ import org.keycloak.userprofile.UserProfileContext; import org.keycloak.userprofile.config.UPConfigUtils; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.userprofile.config.UPConfigUtils.ROLE_ADMIN; import static org.keycloak.userprofile.config.UPConfigUtils.ROLE_USER; @@ -38,46 +38,46 @@ public class UPConfigUtilsTest { @Test public void canBeAuthFlowContext() { - Assert.assertFalse(UserProfileContext.USER_API.canBeAuthFlowContext()); + Assertions.assertFalse(UserProfileContext.USER_API.canBeAuthFlowContext()); - Assert.assertTrue(UserProfileContext.ACCOUNT.canBeAuthFlowContext()); - Assert.assertTrue(UserProfileContext.IDP_REVIEW.canBeAuthFlowContext()); - Assert.assertTrue(UserProfileContext.REGISTRATION.canBeAuthFlowContext()); - Assert.assertTrue(UserProfileContext.UPDATE_PROFILE.canBeAuthFlowContext()); + Assertions.assertTrue(UserProfileContext.ACCOUNT.canBeAuthFlowContext()); + Assertions.assertTrue(UserProfileContext.IDP_REVIEW.canBeAuthFlowContext()); + Assertions.assertTrue(UserProfileContext.REGISTRATION.canBeAuthFlowContext()); + Assertions.assertTrue(UserProfileContext.UPDATE_PROFILE.canBeAuthFlowContext()); } @Test public void isRoleForContext() { - Assert.assertFalse(UserProfileContext.ACCOUNT.isRoleForContext( null)); + Assertions.assertFalse(UserProfileContext.ACCOUNT.isRoleForContext( null)); Set roles = new HashSet<>(); roles.add(ROLE_ADMIN); - Assert.assertTrue(UserProfileContext.USER_API.isRoleForContext(roles)); - Assert.assertFalse(UserProfileContext.ACCOUNT.isRoleForContext(roles)); - Assert.assertFalse(UserProfileContext.UPDATE_PROFILE.isRoleForContext(roles)); + Assertions.assertTrue(UserProfileContext.USER_API.isRoleForContext(roles)); + Assertions.assertFalse(UserProfileContext.ACCOUNT.isRoleForContext(roles)); + Assertions.assertFalse(UserProfileContext.UPDATE_PROFILE.isRoleForContext(roles)); roles = new HashSet<>(); roles.add(ROLE_USER); - Assert.assertFalse(UserProfileContext.USER_API.isRoleForContext(roles)); - Assert.assertTrue(UserProfileContext.ACCOUNT.isRoleForContext(roles)); - Assert.assertTrue(UserProfileContext.IDP_REVIEW.isRoleForContext(roles)); - Assert.assertTrue(UserProfileContext.REGISTRATION.isRoleForContext(roles)); + Assertions.assertFalse(UserProfileContext.USER_API.isRoleForContext(roles)); + Assertions.assertTrue(UserProfileContext.ACCOUNT.isRoleForContext(roles)); + Assertions.assertTrue(UserProfileContext.IDP_REVIEW.isRoleForContext(roles)); + Assertions.assertTrue(UserProfileContext.REGISTRATION.isRoleForContext(roles)); // both in roles roles.add(ROLE_ADMIN); - Assert.assertTrue(UserProfileContext.USER_API.isRoleForContext(roles)); - Assert.assertTrue(UserProfileContext.ACCOUNT.isRoleForContext(roles)); - Assert.assertTrue(UserProfileContext.IDP_REVIEW.isRoleForContext(roles)); - Assert.assertTrue(UserProfileContext.REGISTRATION.isRoleForContext(roles)); + Assertions.assertTrue(UserProfileContext.USER_API.isRoleForContext(roles)); + Assertions.assertTrue(UserProfileContext.ACCOUNT.isRoleForContext(roles)); + Assertions.assertTrue(UserProfileContext.IDP_REVIEW.isRoleForContext(roles)); + Assertions.assertTrue(UserProfileContext.REGISTRATION.isRoleForContext(roles)); } @Test public void capitalizeFirstLetter() { - Assert.assertNull(UPConfigUtils.capitalizeFirstLetter(null)); - Assert.assertEquals("",UPConfigUtils.capitalizeFirstLetter("")); - Assert.assertEquals("A",UPConfigUtils.capitalizeFirstLetter("a")); - Assert.assertEquals("AbcDefGh",UPConfigUtils.capitalizeFirstLetter("abcDefGh")); + Assertions.assertNull(UPConfigUtils.capitalizeFirstLetter(null)); + Assertions.assertEquals("",UPConfigUtils.capitalizeFirstLetter("")); + Assertions.assertEquals("A",UPConfigUtils.capitalizeFirstLetter("a")); + Assertions.assertEquals("AbcDefGh",UPConfigUtils.capitalizeFirstLetter("abcDefGh")); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/AssertAdminEvents.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/AssertAdminEvents.java index b5b56615749a..ee3dce0bce95 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/AssertAdminEvents.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/AssertAdminEvents.java @@ -36,7 +36,6 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.RoleRepresentation; import org.keycloak.testsuite.AbstractKeycloakTest; -import org.keycloak.testsuite.Assert; import org.keycloak.util.JsonSerialization; import com.fasterxml.jackson.core.type.TypeReference; @@ -44,6 +43,7 @@ import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.hamcrest.TypeSafeMatcher; +import org.junit.jupiter.api.Assertions; import org.junit.rules.TestRule; import org.junit.runners.model.Statement; @@ -75,14 +75,14 @@ public void evaluate() throws Throwable { public AdminEventRepresentation poll() { AdminEventRepresentation event = fetchNextEvent(); - Assert.assertNotNull("Admin event expected", event); + Assertions.assertNotNull(event, "Admin event expected"); return event; } public void assertEmpty() { AdminEventRepresentation event = fetchNextEvent(); - Assert.assertNull("Empty admin event queue expected, but there is " + event, event); + Assertions.assertNull(event, "Empty admin event queue expected, but there is " + event); } // Clears both "classic" and admin events for now @@ -190,12 +190,12 @@ public AdminEventRepresentation assertEvent() { } public AdminEventRepresentation assertEvent(AdminEventRepresentation actual) { - Assert.assertEquals(expected.getRealmId(), actual.getRealmId()); + Assertions.assertEquals(expected.getRealmId(), actual.getRealmId()); assertThat(actual.getResourcePath(), resourcePath); - Assert.assertEquals(expected.getResourceType(), actual.getResourceType()); - Assert.assertEquals(expected.getOperationType(), actual.getOperationType()); + Assertions.assertEquals(expected.getResourceType(), actual.getResourceType()); + Assertions.assertEquals(expected.getOperationType(), actual.getOperationType()); - Assert.assertTrue(ObjectUtil.isEqualOrBothNull(expected.getError(), actual.getError())); + Assertions.assertTrue(ObjectUtil.isEqualOrBothNull(expected.getError(), actual.getError())); // AuthDetails AuthDetailsRepresentation expectedAuth = expected.getAuthDetails(); @@ -204,18 +204,18 @@ public AdminEventRepresentation assertEvent(AdminEventRepresentation actual) { } AuthDetailsRepresentation actualAuth = actual.getAuthDetails(); - Assert.assertEquals(expectedAuth.getRealmId(), actualAuth.getRealmId()); + Assertions.assertEquals(expectedAuth.getRealmId(), actualAuth.getRealmId()); if(expectedAuth.getUserId() != null) { - Assert.assertEquals(expectedAuth.getUserId(), actualAuth.getUserId()); + Assertions.assertEquals(expectedAuth.getUserId(), actualAuth.getUserId()); } if (expectedAuth.getClientId() != null) { - Assert.assertEquals(expectedAuth.getClientId(), actualAuth.getClientId()); + Assertions.assertEquals(expectedAuth.getClientId(), actualAuth.getClientId()); } // Representation comparison if (expectedRep != null) { if (actual.getRepresentation() == null) { - Assert.fail("Expected representation " + expectedRep + " but no representation was available on actual event"); + Assertions.fail("Expected representation " + expectedRep + " but no representation was available on actual event"); } else { try { @@ -234,7 +234,7 @@ public AdminEventRepresentation assertEvent(AdminEventRepresentation actual) { for (RoleRepresentation role : actualRoles) { actualRolesMap.put(role.getId(), role.getName()); } - Assert.assertEquals(expectedRolesMap, actualRolesMap); + Assertions.assertEquals(expectedRolesMap, actualRolesMap); } else if (expectedRep instanceof Map) { Object actualRep = JsonSerialization.readValue(actual.getRepresentation(), Map.class); @@ -247,7 +247,7 @@ public AdminEventRepresentation assertEvent(AdminEventRepresentation actual) { Object expectedValue = entry.getValue(); if (expectedValue != null) { Object actualValue = actualRepMap.get(entry.getKey()); - Assert.assertEquals("Map item with key '" + entry.getKey() + "' not equal.", expectedValue, actualValue); + Assertions.assertEquals(expectedValue, actualValue, "Map item with key '" + entry.getKey() + "' not equal."); } } } else { @@ -259,7 +259,7 @@ public AdminEventRepresentation assertEvent(AdminEventRepresentation actual) { Object expectedValue = Reflections.invokeMethod(method, expectedRep); if (expectedValue != null) { Object actualValue = Reflections.invokeMethod(method, actualRep); - Assert.assertEquals("Property method '" + method.getName() + "' of representation not equal.", expectedValue, actualValue); + Assertions.assertEquals(expectedValue, actualValue, "Property method '" + method.getName() + "' of representation not equal."); } } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/AttributesAssert.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/AttributesAssert.java index 6990fb0f7b80..fe607bb29bae 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/AttributesAssert.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/AttributesAssert.java @@ -19,7 +19,7 @@ import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/ClientPoliciesUtil.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/ClientPoliciesUtil.java index 6fd4bb7e1d97..4a656089222b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/ClientPoliciesUtil.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/ClientPoliciesUtil.java @@ -84,7 +84,7 @@ import static org.keycloak.jose.jwk.JWKUtil.toIntegerBytes; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; public final class ClientPoliciesUtil { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/JsonTestUtils.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/JsonTestUtils.java index e941057545a0..4c5a51a3f263 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/JsonTestUtils.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/JsonTestUtils.java @@ -23,7 +23,7 @@ import org.keycloak.util.JsonSerialization; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; /** * Utility for comparing JSON objects @@ -42,7 +42,7 @@ public static void assertJsonEquals(T o1, T o2) { try { String o1Stripped = JsonSerialization.writeValueAsString(o1); String o2Stripped = JsonSerialization.writeValueAsString(o2); - Assert.assertEquals(o1Stripped, o2Stripped); + Assertions.assertEquals(o1Stripped, o2Stripped); } catch (IOException ioe) { throw new RuntimeException(ioe); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/MailAssert.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/MailAssert.java index 9acb3b14cba5..77f89666a4a0 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/MailAssert.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/MailAssert.java @@ -26,9 +26,9 @@ import org.jboss.logging.Logger; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MailAssert { @@ -43,7 +43,7 @@ public static String assertEmailAndGetUrl(String from, String recipient, String } else { message = MailServer.getLastReceivedMessage(); } - assertNotNull("There is no received email.", message); + assertNotNull(message, "There is no received email."); assertEquals(recipient, message.getRecipients(RecipientType.TO)[0].toString()); assertEquals(from, message.getFrom()[0].toString()); @@ -60,7 +60,7 @@ public static String assertEmailAndGetUrl(String from, String recipient, String String errorMessage = "Email content should contains \"" + content + "\", but it doesn't.\nEmail content:\n" + messageContent + "\n"; - assertTrue(errorMessage, messageContent.contains(content)); + assertTrue(messageContent.contains(content), errorMessage); for (String string : messageContent.split("\n")) { if (string.startsWith("http")) { // Ampersand escaped in the text version. Needs to be replaced to have correct URL diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/NoCacheAnnotationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/NoCacheAnnotationTest.java index 254dcc1c4b0b..371d3fbb309a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/NoCacheAnnotationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/NoCacheAnnotationTest.java @@ -24,8 +24,8 @@ import org.keycloak.testsuite.AbstractKeycloakTest; import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; /** * @author Réda Housni Alaoui @@ -40,7 +40,7 @@ public void addTestRealms(List testRealms) { @Test public void noCacheAnnotationOverridesProgrammaticCacheControlBehaviour() { Response response = getTestingClient().testing().getNoCacheAnnotatedEndpointResponse(2000L); - Assert.assertEquals(204, response.getStatus()); - Assert.assertEquals("no-cache", response.getHeaderString("cache-control")); + Assertions.assertEquals(204, response.getStatus()); + Assertions.assertEquals("no-cache", response.getHeaderString("cache-control")); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/UIAssert.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/UIAssert.java index 04116633c979..c9d80ee89847 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/UIAssert.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/UIAssert.java @@ -24,7 +24,7 @@ import static org.keycloak.testsuite.util.UIUtils.isElementVisible; import static org.keycloak.testsuite.util.UIUtils.isInputElementValid; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Vaclav Muzikar @@ -33,18 +33,18 @@ public final class UIAssert { public static void assertInputElementValid(boolean expected, WebElement element) { String msg = String.format("Expected %s to be %b; actual %s", ARIA_INVALID_ATTR_NAME, expected, element.getAttribute(ARIA_INVALID_ATTR_NAME)); - assertEquals(msg, expected, isInputElementValid(element)); + assertEquals(expected, isInputElementValid(element), msg); } public static void assertElementDisabled(boolean expected, WebElement element) { boolean actual = isElementDisabled(element); String msg = "Element should" + (!expected ? " not" : "") + " be disabled"; - assertEquals(msg, expected, actual); + assertEquals(expected, actual, msg); } public static void assertElementVisible(boolean expected, WebElement element) { boolean actual = isElementVisible(element); String msg = "Element should" + (!expected ? " not" : "") + " be visible"; - assertEquals(msg, expected, actual); + assertEquals(expected, actual, msg); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/URLAssert.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/URLAssert.java index f14e711a1993..1538a0baff73 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/URLAssert.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/util/URLAssert.java @@ -32,7 +32,7 @@ import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.awaitility.core.ThrowingRunnable; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebDriver; import static org.keycloak.testsuite.util.ServerURLs.removeDefaultPorts; @@ -41,7 +41,7 @@ import static org.keycloak.testsuite.util.URLUtils.currentUrlStartsWith; import static org.awaitility.Awaitility.await; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @@ -69,8 +69,8 @@ public static void assertCurrentUrlEquals(final URI url) { public static void assertCurrentUrlEquals(final String url) { awaitUntilAsserted(() -> { - assertTrue("Expected URL: " + url + " ; actual: " + DroneUtils.getCurrentDriver().getCurrentUrl(), - currentUrlEquals(url)); + assertTrue(currentUrlEquals(url), + "Expected URL: " + url + " ; actual: " + DroneUtils.getCurrentDriver().getCurrentUrl()); }); } @@ -90,8 +90,8 @@ public static void assertCurrentUrlStartsWith(final AbstractPage page) { public static void assertCurrentUrlStartsWith(final String url){ awaitUntilAsserted(() -> { - assertTrue("URL expected to begin with: " + removeDefaultPorts(url) + " ; actual URL: " + DroneUtils.getCurrentDriver().getCurrentUrl(), - currentUrlStartsWith(removeDefaultPorts(url))); + assertTrue(currentUrlStartsWith(removeDefaultPorts(url)), + "URL expected to begin with: " + removeDefaultPorts(url) + " ; actual URL: " + DroneUtils.getCurrentDriver().getCurrentUrl()); }); } @@ -113,8 +113,8 @@ public static void assertCurrentUrlDoesntStartWith(AbstractPage page) { public static void assertCurrentUrlDoesntStartWith(final String url) { awaitUntilAsserted(() -> { - assertTrue("URL expected NOT to begin with: " + url + " ; actual URL: " + DroneUtils.getCurrentDriver().getCurrentUrl(), - currentUrlDoesntStartWith(url)); + assertTrue(currentUrlDoesntStartWith(url), + "URL expected NOT to begin with: " + url + " ; actual URL: " + DroneUtils.getCurrentDriver().getCurrentUrl()); }); } @@ -148,7 +148,7 @@ public static abstract class AssertJSONResponseHandler implements AssertResponse public void assertResponse(CloseableHttpResponse response) throws IOException { HttpEntity entity = response.getEntity(); Header contentType = entity.getContentType(); - Assert.assertTrue(contentType.getValue().startsWith("application/json")); + Assertions.assertTrue(contentType.getValue().startsWith("application/json")); char [] buf = new char[8192]; StringWriter out = new StringWriter(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/validation/BuiltinValidatorsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/validation/BuiltinValidatorsTest.java index f2687c2f7aec..15e533f501c5 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/validation/BuiltinValidatorsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/validation/BuiltinValidatorsTest.java @@ -48,8 +48,8 @@ import org.keycloak.validate.validators.UriValidator; import com.google.common.collect.ImmutableMap; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.validate.ValidatorConfig.configFromMap; @@ -67,56 +67,56 @@ public void testLengthValidator() { Validator validator = BuiltinValidators.lengthValidator(); // null and empty values handling - Assert.assertFalse(validator.validate(null, "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MIN, 1))).isValid()); - Assert.assertFalse(validator.validate("", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MIN, 1))).isValid()); - Assert.assertFalse(validator.validate(" ", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MIN, 1))).isValid()); - Assert.assertTrue(validator.validate(" ", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MAX, 10))).isValid()); + Assertions.assertFalse(validator.validate(null, "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MIN, 1))).isValid()); + Assertions.assertFalse(validator.validate("", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MIN, 1))).isValid()); + Assertions.assertFalse(validator.validate(" ", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MIN, 1))).isValid()); + Assertions.assertTrue(validator.validate(" ", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MAX, 10))).isValid()); //KEYCLOAK-19006 reproducer - Assert.assertFalse(validator.validate(" ", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MAX, 4).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).config(LengthValidator.KEY_TRIM_DISABLED, true).build()).isValid()); + Assertions.assertFalse(validator.validate(" ", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MAX, 4).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).config(LengthValidator.KEY_TRIM_DISABLED, true).build()).isValid()); // min validation only - Assert.assertTrue(validator.validate("t", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 1).build()).isValid()); - Assert.assertFalse(validator.validate("tester", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 7).build()).isValid()); + Assertions.assertTrue(validator.validate("t", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 1).build()).isValid()); + Assertions.assertFalse(validator.validate("tester", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 7).build()).isValid()); //min value validation with "empty value ignoration" configured - Assert.assertTrue(validator.validate(null, "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 1).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).build()).isValid()); - Assert.assertTrue(validator.validate("", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 1).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).build()).isValid()); - Assert.assertFalse(validator.validate(" ", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 1).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).build()).isValid()); - Assert.assertTrue(validator.validate("t", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 1).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).build()).isValid()); - Assert.assertFalse(validator.validate("tester", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 7).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).build()).isValid()); + Assertions.assertTrue(validator.validate(null, "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 1).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).build()).isValid()); + Assertions.assertTrue(validator.validate("", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 1).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).build()).isValid()); + Assertions.assertFalse(validator.validate(" ", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 1).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).build()).isValid()); + Assertions.assertTrue(validator.validate("t", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 1).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).build()).isValid()); + Assertions.assertFalse(validator.validate("tester", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 7).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).build()).isValid()); // max validation only - Assert.assertTrue(validator.validate("tester", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MAX, 8).build()).isValid()); - Assert.assertFalse(validator.validate("tester", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MAX, 4).build()).isValid()); + Assertions.assertTrue(validator.validate("tester", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MAX, 8).build()).isValid()); + Assertions.assertFalse(validator.validate("tester", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MAX, 4).build()).isValid()); //max value validation with "empty value ignoration" configured - Assert.assertTrue(validator.validate(null, "name", ValidatorConfig.builder().config(LengthValidator.KEY_MAX, 8).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).build()).isValid()); - Assert.assertTrue(validator.validate("tester", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MAX, 8).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).build()).isValid()); - Assert.assertFalse(validator.validate("tester", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MAX, 4).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).build()).isValid()); + Assertions.assertTrue(validator.validate(null, "name", ValidatorConfig.builder().config(LengthValidator.KEY_MAX, 8).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).build()).isValid()); + Assertions.assertTrue(validator.validate("tester", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MAX, 8).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).build()).isValid()); + Assertions.assertFalse(validator.validate("tester", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MAX, 4).config(AbstractSimpleValidator.IGNORE_EMPTY_VALUE, true).build()).isValid()); // both validations together ValidatorConfig config1 = configFromMap(ImmutableMap.of(LengthValidator.KEY_MIN, 3, LengthValidator.KEY_MAX, 4)); - Assert.assertFalse(validator.validate("te", "name", config1).isValid()); - Assert.assertTrue(validator.validate("tes", "name", config1).isValid()); - Assert.assertTrue(validator.validate("test", "name", config1).isValid()); - Assert.assertFalse(validator.validate("testr", "name", config1).isValid()); + Assertions.assertFalse(validator.validate("te", "name", config1).isValid()); + Assertions.assertTrue(validator.validate("tes", "name", config1).isValid()); + Assertions.assertTrue(validator.validate("test", "name", config1).isValid()); + Assertions.assertFalse(validator.validate("testr", "name", config1).isValid()); // test value trimming performed by default - Assert.assertFalse("trim not performed", validator.validate("t ", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MIN, 2))).isValid()); - Assert.assertFalse("trim not performed", validator.validate(" t", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MIN, 2))).isValid()); - Assert.assertTrue("trim not performed", validator.validate("tr ", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MAX, 2))).isValid()); - Assert.assertTrue("trim not performed", validator.validate(" tr", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MAX, 2))).isValid()); + Assertions.assertFalse(validator.validate("t ", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MIN, 2))).isValid(), "trim not performed"); + Assertions.assertFalse(validator.validate(" t", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MIN, 2))).isValid(), "trim not performed"); + Assertions.assertTrue(validator.validate("tr ", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MAX, 2))).isValid(), "trim not performed"); + Assertions.assertTrue(validator.validate(" tr", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MAX, 2))).isValid(), "trim not performed"); // test value trimming disabled in config - Assert.assertTrue("trim disabled but performed", validator.validate("tr ", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MIN, 3, LengthValidator.KEY_TRIM_DISABLED, true))).isValid()); - Assert.assertFalse("trim disabled but performed", validator.validate("trr ", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MAX, 3, LengthValidator.KEY_TRIM_DISABLED, true))).isValid()); + Assertions.assertTrue(validator.validate("tr ", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MIN, 3, LengthValidator.KEY_TRIM_DISABLED, true))).isValid(), "trim disabled but performed"); + Assertions.assertFalse(validator.validate("trr ", "name", configFromMap(ImmutableMap.of(LengthValidator.KEY_MAX, 3, LengthValidator.KEY_TRIM_DISABLED, true))).isValid(), "trim disabled but performed"); //test correct error message selection - Assert.assertEquals(LengthValidator.MESSAGE_INVALID_LENGTH_TOO_SHORT,validator.validate("", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 1).build()).getErrors().iterator().next().getMessage()); - Assert.assertEquals(LengthValidator.MESSAGE_INVALID_LENGTH,validator.validate("", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 1).config(LengthValidator.KEY_MAX, 10).build()).getErrors().iterator().next().getMessage()); - Assert.assertEquals(LengthValidator.MESSAGE_INVALID_LENGTH_TOO_LONG,validator.validate("aaa", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MAX, 1).build()).getErrors().iterator().next().getMessage()); - Assert.assertEquals(LengthValidator.MESSAGE_INVALID_LENGTH,validator.validate("aaa", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 1).config(LengthValidator.KEY_MAX, 2).build()).getErrors().iterator().next().getMessage()); + Assertions.assertEquals(LengthValidator.MESSAGE_INVALID_LENGTH_TOO_SHORT,validator.validate("", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 1).build()).getErrors().iterator().next().getMessage()); + Assertions.assertEquals(LengthValidator.MESSAGE_INVALID_LENGTH,validator.validate("", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 1).config(LengthValidator.KEY_MAX, 10).build()).getErrors().iterator().next().getMessage()); + Assertions.assertEquals(LengthValidator.MESSAGE_INVALID_LENGTH_TOO_LONG,validator.validate("aaa", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MAX, 1).build()).getErrors().iterator().next().getMessage()); + Assertions.assertEquals(LengthValidator.MESSAGE_INVALID_LENGTH,validator.validate("aaa", "name", ValidatorConfig.builder().config(LengthValidator.KEY_MIN, 1).config(LengthValidator.KEY_MAX, 2).build()).getErrors().iterator().next().getMessage()); } @Test @@ -128,32 +128,32 @@ public void testLengthValidator_ConfigValidation(KeycloakSession session) { ValidationResult result = BuiltinValidators.validatorConfigValidator().validate(config, LengthValidator.ID, new ValidationContext(session)).toResult(); - Assert.assertFalse(result.isValid()); + Assertions.assertFalse(result.isValid()); ValidationError[] errors = result.getErrors().toArray(new ValidationError[0]); ValidationError error0 = errors[0]; - Assert.assertNotNull(error0); - Assert.assertEquals(LengthValidator.ID, error0.getValidatorId()); - Assert.assertEquals(LengthValidator.KEY_MIN, error0.getInputHint()); + Assertions.assertNotNull(error0); + Assertions.assertEquals(LengthValidator.ID, error0.getValidatorId()); + Assertions.assertEquals(LengthValidator.KEY_MIN, error0.getInputHint()); ValidationError error1 = errors[1]; - Assert.assertNotNull(error1); - Assert.assertEquals(LengthValidator.ID, error1.getValidatorId()); - Assert.assertEquals(LengthValidator.KEY_MAX, error1.getInputHint()); + Assertions.assertNotNull(error1); + Assertions.assertEquals(LengthValidator.ID, error1.getValidatorId()); + Assertions.assertEquals(LengthValidator.KEY_MAX, error1.getInputHint()); // empty config result = BuiltinValidators.validatorConfigValidator().validate(null, LengthValidator.ID, new ValidationContext(session)).toResult(); - Assert.assertEquals(2, result.getErrors().size()); + Assertions.assertEquals(2, result.getErrors().size()); result = BuiltinValidators.validatorConfigValidator().validate(ValidatorConfig.EMPTY, LengthValidator.ID, new ValidationContext(session)).toResult(); - Assert.assertEquals(2, result.getErrors().size()); + Assertions.assertEquals(2, result.getErrors().size()); // correct config - Assert.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(LengthValidator.KEY_MIN, "10")), LengthValidator.ID, new ValidationContext(session)).toResult().isValid()); - Assert.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(LengthValidator.KEY_MAX, "10")), LengthValidator.ID, new ValidationContext(session)).toResult().isValid()); - Assert.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(LengthValidator.KEY_MIN, "10", LengthValidator.KEY_MAX, "10")), LengthValidator.ID, new ValidationContext(session)).toResult().isValid()); + Assertions.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(LengthValidator.KEY_MIN, "10")), LengthValidator.ID, new ValidationContext(session)).toResult().isValid()); + Assertions.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(LengthValidator.KEY_MAX, "10")), LengthValidator.ID, new ValidationContext(session)).toResult().isValid()); + Assertions.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(LengthValidator.KEY_MIN, "10", LengthValidator.KEY_MAX, "10")), LengthValidator.ID, new ValidationContext(session)).toResult().isValid()); // max is smaller than min - Assert.assertFalse(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(LengthValidator.KEY_MIN, "10", LengthValidator.KEY_MAX, "9")), LengthValidator.ID, new ValidationContext(session)).toResult().isValid()); + Assertions.assertFalse(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(LengthValidator.KEY_MIN, "10", LengthValidator.KEY_MAX, "9")), LengthValidator.ID, new ValidationContext(session)).toResult().isValid()); } @Test @@ -162,31 +162,31 @@ public void testEmailValidator() { Validator validator = BuiltinValidators.emailValidator(); - Assert.assertFalse(validator.validate(null, "email").isValid()); - Assert.assertFalse(validator.validate("", "email").isValid()); - Assert.assertFalse(validator.validate(" ", "email").isValid()); + Assertions.assertFalse(validator.validate(null, "email").isValid()); + Assertions.assertFalse(validator.validate("", "email").isValid()); + Assertions.assertFalse(validator.validate(" ", "email").isValid()); // empty value ignoration configured - Assert.assertTrue(validator.validate(null, "emptyString", valConfigIgnoreEmptyValues).isValid()); - Assert.assertTrue(validator.validate("", "emptyString", valConfigIgnoreEmptyValues).isValid()); - Assert.assertFalse(validator.validate(" ", "blankString", valConfigIgnoreEmptyValues).isValid()); + Assertions.assertTrue(validator.validate(null, "emptyString", valConfigIgnoreEmptyValues).isValid()); + Assertions.assertTrue(validator.validate("", "emptyString", valConfigIgnoreEmptyValues).isValid()); + Assertions.assertFalse(validator.validate(" ", "blankString", valConfigIgnoreEmptyValues).isValid()); - Assert.assertTrue(validator.validate("admin@example.org", "email").isValid()); - Assert.assertTrue(validator.validate("admin+sds@example.org", "email").isValid()); + Assertions.assertTrue(validator.validate("admin@example.org", "email").isValid()); + Assertions.assertTrue(validator.validate("admin+sds@example.org", "email").isValid()); - Assert.assertFalse(validator.validate(" ", "email").isValid()); - Assert.assertFalse(validator.validate("adminATexample.org", "email").isValid()); + Assertions.assertFalse(validator.validate(" ", "email").isValid()); + Assertions.assertFalse(validator.validate("adminATexample.org", "email").isValid()); - Assert.assertTrue(validator.validate("username@keycloak.org", "email", (ValidatorConfig) null).isValid()); - Assert.assertTrue(validator.validate("abcd012345678901234567890123456789012345678901234567890123456789@keycloak.org", "email").isValid()); - Assert.assertFalse(validator.validate("abcde012345678901234567890123456789012345678901234567890123456789@keycloak.org", "email").isValid()); - Assert.assertTrue(validator.validate("abcdef0123456789@keycloak.org", "email", + Assertions.assertTrue(validator.validate("username@keycloak.org", "email", (ValidatorConfig) null).isValid()); + Assertions.assertTrue(validator.validate("abcd012345678901234567890123456789012345678901234567890123456789@keycloak.org", "email").isValid()); + Assertions.assertFalse(validator.validate("abcde012345678901234567890123456789012345678901234567890123456789@keycloak.org", "email").isValid()); + Assertions.assertTrue(validator.validate("abcdef0123456789@keycloak.org", "email", new ValidatorConfig(ImmutableMap.of(EmailValidator.MAX_LOCAL_PART_LENGTH_PROPERTY, "16"))).isValid()); - Assert.assertFalse(validator.validate("abcdefg0123456789@keycloak.org", "email", + Assertions.assertFalse(validator.validate("abcdefg0123456789@keycloak.org", "email", new ValidatorConfig(ImmutableMap.of(EmailValidator.MAX_LOCAL_PART_LENGTH_PROPERTY, 16))).isValid()); - Assert.assertTrue(validator.validate("ab012345678901234567890123456789@keycloak.org", "email", + Assertions.assertTrue(validator.validate("ab012345678901234567890123456789@keycloak.org", "email", new ValidatorConfig(ImmutableMap.of(EmailValidator.MAX_LOCAL_PART_LENGTH_PROPERTY, "32"))).isValid()); - Assert.assertFalse(validator.validate("abc012345678901234567890123456789@keycloak.org", "email", + Assertions.assertFalse(validator.validate("abc012345678901234567890123456789@keycloak.org", "email", new ValidatorConfig(ImmutableMap.of(EmailValidator.MAX_LOCAL_PART_LENGTH_PROPERTY, 32))).isValid()); } @@ -197,20 +197,20 @@ public void testAbstractSimpleValidatorSupportForCollections() { List valuesCollection = new ArrayList<>(); - Assert.assertTrue(validator.validate(valuesCollection, "email").isValid()); + Assertions.assertTrue(validator.validate(valuesCollection, "email").isValid()); valuesCollection.add(""); - Assert.assertFalse(validator.validate(valuesCollection, "email").isValid()); + Assertions.assertFalse(validator.validate(valuesCollection, "email").isValid()); valuesCollection.add("admin@example.org"); - Assert.assertTrue(validator.validate("admin@example.org", "email").isValid()); + Assertions.assertTrue(validator.validate("admin@example.org", "email").isValid()); // wrong value fails validation even it is not at first position valuesCollection.add(" "); - Assert.assertFalse(validator.validate(valuesCollection, "email").isValid()); + Assertions.assertFalse(validator.validate(valuesCollection, "email").isValid()); valuesCollection.remove(valuesCollection.size() - 1); valuesCollection.add("adminATexample.org"); - Assert.assertFalse(validator.validate(valuesCollection, "email").isValid()); + Assertions.assertFalse(validator.validate(valuesCollection, "email").isValid()); } @@ -220,21 +220,21 @@ public void testNotBlankValidator() { Validator validator = BuiltinValidators.notBlankValidator(); // simple String value - Assert.assertTrue(validator.validate("tester", "username").isValid()); - Assert.assertFalse(validator.validate("", "username").isValid()); - Assert.assertFalse(validator.validate(" ", "username").isValid()); - Assert.assertFalse(validator.validate(null, "username").isValid()); + Assertions.assertTrue(validator.validate("tester", "username").isValid()); + Assertions.assertFalse(validator.validate("", "username").isValid()); + Assertions.assertFalse(validator.validate(" ", "username").isValid()); + Assertions.assertFalse(validator.validate(null, "username").isValid()); // collection as input - Assert.assertTrue(validator.validate(Arrays.asList("a", "b"), "username").isValid()); - Assert.assertFalse(validator.validate(new ArrayList<>(), "username").isValid()); - Assert.assertFalse(validator.validate(Arrays.asList(""), "username").isValid()); - Assert.assertFalse(validator.validate(Arrays.asList(" "), "username").isValid()); - Assert.assertFalse(validator.validate(Arrays.asList("a", " "), "username").isValid()); - Assert.assertFalse(validator.validate(Arrays.asList("a", new Object()), "username").isValid()); + Assertions.assertTrue(validator.validate(Arrays.asList("a", "b"), "username").isValid()); + Assertions.assertFalse(validator.validate(new ArrayList<>(), "username").isValid()); + Assertions.assertFalse(validator.validate(Arrays.asList(""), "username").isValid()); + Assertions.assertFalse(validator.validate(Arrays.asList(" "), "username").isValid()); + Assertions.assertFalse(validator.validate(Arrays.asList("a", " "), "username").isValid()); + Assertions.assertFalse(validator.validate(Arrays.asList("a", new Object()), "username").isValid()); // unsupported input type - Assert.assertFalse(validator.validate(new Object(), "username").isValid()); + Assertions.assertFalse(validator.validate(new Object(), "username").isValid()); } @Test @@ -242,17 +242,17 @@ public void testNotEmptyValidator() { Validator validator = BuiltinValidators.notEmptyValidator(); - Assert.assertTrue(validator.validate("tester", "username").isValid()); - Assert.assertTrue(validator.validate(" ", "username").isValid()); - Assert.assertTrue(validator.validate(Arrays.asList(1, 2, 3), "numberList").isValid()); - Assert.assertTrue(validator.validate(Collections.singleton("key"), "stringSet").isValid()); - Assert.assertTrue(validator.validate(Collections.singletonMap("key", "value"), "stringMap").isValid()); - - Assert.assertFalse(validator.validate(null, "username").isValid()); - Assert.assertFalse(validator.validate("", "username").isValid()); - Assert.assertFalse(validator.validate(Collections.emptyList(), "emptyList").isValid()); - Assert.assertFalse(validator.validate(Collections.emptySet(), "emptySet").isValid()); - Assert.assertFalse(validator.validate(Collections.emptyMap(), "emptyMap").isValid()); + Assertions.assertTrue(validator.validate("tester", "username").isValid()); + Assertions.assertTrue(validator.validate(" ", "username").isValid()); + Assertions.assertTrue(validator.validate(Arrays.asList(1, 2, 3), "numberList").isValid()); + Assertions.assertTrue(validator.validate(Collections.singleton("key"), "stringSet").isValid()); + Assertions.assertTrue(validator.validate(Collections.singletonMap("key", "value"), "stringMap").isValid()); + + Assertions.assertFalse(validator.validate(null, "username").isValid()); + Assertions.assertFalse(validator.validate("", "username").isValid()); + Assertions.assertFalse(validator.validate(Collections.emptyList(), "emptyList").isValid()); + Assertions.assertFalse(validator.validate(Collections.emptySet(), "emptySet").isValid()); + Assertions.assertFalse(validator.validate(Collections.emptyMap(), "emptyMap").isValid()); } @Test @@ -261,63 +261,63 @@ public void testDoubleValidator() { Validator validator = BuiltinValidators.doubleValidator(); // null value and empty String - Assert.assertFalse(validator.validate(null, "null").isValid()); - Assert.assertFalse(validator.validate("", "emptyString").isValid()); - Assert.assertFalse(validator.validate(" ", "blankString").isValid()); + Assertions.assertFalse(validator.validate(null, "null").isValid()); + Assertions.assertFalse(validator.validate("", "emptyString").isValid()); + Assertions.assertFalse(validator.validate(" ", "blankString").isValid()); // empty value ignoration configured - Assert.assertTrue(validator.validate(null, "emptyString", valConfigIgnoreEmptyValues).isValid()); - Assert.assertTrue(validator.validate("", "emptyString", valConfigIgnoreEmptyValues).isValid()); - Assert.assertTrue(validator.validate(" ", "blankString", valConfigIgnoreEmptyValues).isValid()); + Assertions.assertTrue(validator.validate(null, "emptyString", valConfigIgnoreEmptyValues).isValid()); + Assertions.assertTrue(validator.validate("", "emptyString", valConfigIgnoreEmptyValues).isValid()); + Assertions.assertTrue(validator.validate(" ", "blankString", valConfigIgnoreEmptyValues).isValid()); // simple values - Assert.assertTrue(validator.validate(10, "age").isValid()); - Assert.assertTrue(validator.validate("10", "age").isValid()); - Assert.assertTrue(validator.validate("3.14", "pi").isValid()); - Assert.assertTrue(validator.validate(" 3.14 ", "piWithBlank").isValid()); + Assertions.assertTrue(validator.validate(10, "age").isValid()); + Assertions.assertTrue(validator.validate("10", "age").isValid()); + Assertions.assertTrue(validator.validate("3.14", "pi").isValid()); + Assertions.assertTrue(validator.validate(" 3.14 ", "piWithBlank").isValid()); - Assert.assertFalse(validator.validate("a", "notAnumber").isValid()); - Assert.assertFalse(validator.validate(true, "true").isValid()); + Assertions.assertFalse(validator.validate("a", "notAnumber").isValid()); + Assertions.assertFalse(validator.validate(true, "true").isValid()); // collections - Assert.assertFalse(validator.validate(Arrays.asList(""), "age").isValid()); - Assert.assertTrue(validator.validate(Arrays.asList(""), "age",valConfigIgnoreEmptyValues).isValid()); - Assert.assertTrue(validator.validate(new ArrayList<>(), "age").isValid()); - Assert.assertTrue(validator.validate(Arrays.asList(10), "age").isValid()); - Assert.assertTrue(validator.validate(Arrays.asList(" 10 "), "age").isValid()); - Assert.assertTrue(validator.validate(Arrays.asList("3.14"), "pi").isValid()); - Assert.assertTrue(validator.validate(Arrays.asList("3.14", 10), "pi").isValid()); - - Assert.assertFalse(validator.validate(Arrays.asList("a"), "notAnumber").isValid()); - Assert.assertFalse(validator.validate(Arrays.asList("3.14", "a"), "notANumberPresent").isValid()); - Assert.assertFalse(validator.validate(Arrays.asList("3.14", new Object()), "notANumberPresent").isValid()); + Assertions.assertFalse(validator.validate(Arrays.asList(""), "age").isValid()); + Assertions.assertTrue(validator.validate(Arrays.asList(""), "age",valConfigIgnoreEmptyValues).isValid()); + Assertions.assertTrue(validator.validate(new ArrayList<>(), "age").isValid()); + Assertions.assertTrue(validator.validate(Arrays.asList(10), "age").isValid()); + Assertions.assertTrue(validator.validate(Arrays.asList(" 10 "), "age").isValid()); + Assertions.assertTrue(validator.validate(Arrays.asList("3.14"), "pi").isValid()); + Assertions.assertTrue(validator.validate(Arrays.asList("3.14", 10), "pi").isValid()); + + Assertions.assertFalse(validator.validate(Arrays.asList("a"), "notAnumber").isValid()); + Assertions.assertFalse(validator.validate(Arrays.asList("3.14", "a"), "notANumberPresent").isValid()); + Assertions.assertFalse(validator.validate(Arrays.asList("3.14", new Object()), "notANumberPresent").isValid()); // min only - Assert.assertTrue(validator.validate("10.1", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 1.4).build()).isValid()); - Assert.assertFalse(validator.validate("10.1", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 100.5).build()).isValid()); + Assertions.assertTrue(validator.validate("10.1", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 1.4).build()).isValid()); + Assertions.assertFalse(validator.validate("10.1", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 100.5).build()).isValid()); // min behavior around empty values - Assert.assertFalse(validator.validate(null, "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 1.1).build()).isValid()); - Assert.assertFalse(validator.validate("", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 1.1).build()).isValid()); - Assert.assertFalse(validator.validate(" ", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 1.1).build()).isValid()); - Assert.assertTrue(validator.validate(null, "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 1.1).config(valConfigIgnoreEmptyValues).build()).isValid()); - Assert.assertTrue(validator.validate("", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 1.1).config(valConfigIgnoreEmptyValues).build()).isValid()); - Assert.assertTrue(validator.validate(" ", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 1.1).config(valConfigIgnoreEmptyValues).build()).isValid()); + Assertions.assertFalse(validator.validate(null, "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 1.1).build()).isValid()); + Assertions.assertFalse(validator.validate("", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 1.1).build()).isValid()); + Assertions.assertFalse(validator.validate(" ", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 1.1).build()).isValid()); + Assertions.assertTrue(validator.validate(null, "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 1.1).config(valConfigIgnoreEmptyValues).build()).isValid()); + Assertions.assertTrue(validator.validate("", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 1.1).config(valConfigIgnoreEmptyValues).build()).isValid()); + Assertions.assertTrue(validator.validate(" ", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 1.1).config(valConfigIgnoreEmptyValues).build()).isValid()); // max only - Assert.assertFalse(validator.validate("10.5", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MAX, 1.1).build()).isValid()); - Assert.assertTrue(validator.validate("10.5", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MAX, 100.1).build()).isValid()); + Assertions.assertFalse(validator.validate("10.5", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MAX, 1.1).build()).isValid()); + Assertions.assertTrue(validator.validate("10.5", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MAX, 100.1).build()).isValid()); // min and max - Assert.assertFalse(validator.validate("10.09", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 10.1).config(DoubleValidator.KEY_MAX, 100).build()).isValid()); - Assert.assertTrue(validator.validate("10.1", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 10.1).config(DoubleValidator.KEY_MAX, 100).build()).isValid()); - Assert.assertTrue(validator.validate("100.1", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 10.1).config(DoubleValidator.KEY_MAX, 100.1).build()).isValid()); - Assert.assertFalse(validator.validate("100.2", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 10.1).config(DoubleValidator.KEY_MAX, 100.1).build()).isValid()); + Assertions.assertFalse(validator.validate("10.09", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 10.1).config(DoubleValidator.KEY_MAX, 100).build()).isValid()); + Assertions.assertTrue(validator.validate("10.1", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 10.1).config(DoubleValidator.KEY_MAX, 100).build()).isValid()); + Assertions.assertTrue(validator.validate("100.1", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 10.1).config(DoubleValidator.KEY_MAX, 100.1).build()).isValid()); + Assertions.assertFalse(validator.validate("100.2", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 10.1).config(DoubleValidator.KEY_MAX, 100.1).build()).isValid()); //test correct error message selection - Assert.assertEquals(DoubleValidator.MESSAGE_NUMBER_OUT_OF_RANGE_TOO_SMALL,validator.validate("10", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 100).build()).getErrors().iterator().next().getMessage()); - Assert.assertEquals(DoubleValidator.MESSAGE_NUMBER_OUT_OF_RANGE,validator.validate("10", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 100).config(DoubleValidator.KEY_MAX, 1000).build()).getErrors().iterator().next().getMessage()); - Assert.assertEquals(DoubleValidator.MESSAGE_NUMBER_OUT_OF_RANGE,validator.validate("10000", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 100).config(DoubleValidator.KEY_MAX, 1000).build()).getErrors().iterator().next().getMessage()); - Assert.assertEquals(DoubleValidator.MESSAGE_NUMBER_OUT_OF_RANGE_TOO_BIG,validator.validate("10000", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MAX, 1000).build()).getErrors().iterator().next().getMessage()); + Assertions.assertEquals(DoubleValidator.MESSAGE_NUMBER_OUT_OF_RANGE_TOO_SMALL,validator.validate("10", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 100).build()).getErrors().iterator().next().getMessage()); + Assertions.assertEquals(DoubleValidator.MESSAGE_NUMBER_OUT_OF_RANGE,validator.validate("10", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 100).config(DoubleValidator.KEY_MAX, 1000).build()).getErrors().iterator().next().getMessage()); + Assertions.assertEquals(DoubleValidator.MESSAGE_NUMBER_OUT_OF_RANGE,validator.validate("10000", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MIN, 100).config(DoubleValidator.KEY_MAX, 1000).build()).getErrors().iterator().next().getMessage()); + Assertions.assertEquals(DoubleValidator.MESSAGE_NUMBER_OUT_OF_RANGE_TOO_BIG,validator.validate("10000", "name", ValidatorConfig.builder().config(DoubleValidator.KEY_MAX, 1000).build()).getErrors().iterator().next().getMessage()); } @@ -330,32 +330,32 @@ public void testDoubleValidator_ConfigValidation(KeycloakSession session) { ValidationResult result = BuiltinValidators.validatorConfigValidator().validate(config, DoubleValidator.ID, new ValidationContext(session)).toResult(); - Assert.assertFalse(result.isValid()); + Assertions.assertFalse(result.isValid()); ValidationError[] errors = result.getErrors().toArray(new ValidationError[0]); ValidationError error0 = errors[0]; - Assert.assertNotNull(error0); - Assert.assertEquals(DoubleValidator.ID, error0.getValidatorId()); - Assert.assertEquals(DoubleValidator.KEY_MIN, error0.getInputHint()); + Assertions.assertNotNull(error0); + Assertions.assertEquals(DoubleValidator.ID, error0.getValidatorId()); + Assertions.assertEquals(DoubleValidator.KEY_MIN, error0.getInputHint()); ValidationError error1 = errors[1]; - Assert.assertNotNull(error1); - Assert.assertEquals(DoubleValidator.ID, error1.getValidatorId()); - Assert.assertEquals(DoubleValidator.KEY_MAX, error1.getInputHint()); + Assertions.assertNotNull(error1); + Assertions.assertEquals(DoubleValidator.ID, error1.getValidatorId()); + Assertions.assertEquals(DoubleValidator.KEY_MAX, error1.getInputHint()); // empty config result = BuiltinValidators.validatorConfigValidator().validate(null, DoubleValidator.ID, new ValidationContext(session)).toResult(); - Assert.assertEquals(0, result.getErrors().size()); + Assertions.assertEquals(0, result.getErrors().size()); result = BuiltinValidators.validatorConfigValidator().validate(ValidatorConfig.EMPTY, DoubleValidator.ID, new ValidationContext(session)).toResult(); - Assert.assertEquals(0, result.getErrors().size()); + Assertions.assertEquals(0, result.getErrors().size()); // correct config - Assert.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(DoubleValidator.KEY_MIN, "10.1")), DoubleValidator.ID, new ValidationContext(session)).toResult().isValid()); - Assert.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(DoubleValidator.KEY_MAX, "10.1")), DoubleValidator.ID, new ValidationContext(session)).toResult().isValid()); - Assert.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(DoubleValidator.KEY_MIN, "10.1", DoubleValidator.KEY_MAX, "11")), DoubleValidator.ID, new ValidationContext(session)).toResult().isValid()); + Assertions.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(DoubleValidator.KEY_MIN, "10.1")), DoubleValidator.ID, new ValidationContext(session)).toResult().isValid()); + Assertions.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(DoubleValidator.KEY_MAX, "10.1")), DoubleValidator.ID, new ValidationContext(session)).toResult().isValid()); + Assertions.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(DoubleValidator.KEY_MIN, "10.1", DoubleValidator.KEY_MAX, "11")), DoubleValidator.ID, new ValidationContext(session)).toResult().isValid()); // max is smaller than min - Assert.assertFalse(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(DoubleValidator.KEY_MIN, "10.1", DoubleValidator.KEY_MAX, "10.1")), DoubleValidator.ID, new ValidationContext(session)).toResult().isValid()); + Assertions.assertFalse(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(DoubleValidator.KEY_MIN, "10.1", DoubleValidator.KEY_MAX, "10.1")), DoubleValidator.ID, new ValidationContext(session)).toResult().isValid()); } @Test @@ -363,65 +363,65 @@ public void testIntegerValidator() { Validator validator = BuiltinValidators.integerValidator(); // null value and empty String - Assert.assertFalse(validator.validate(null, "null").isValid()); - Assert.assertFalse(validator.validate("", "emptyString").isValid()); + Assertions.assertFalse(validator.validate(null, "null").isValid()); + Assertions.assertFalse(validator.validate("", "emptyString").isValid()); // empty value ignoration configured - Assert.assertTrue(validator.validate(null, "emptyString", valConfigIgnoreEmptyValues).isValid()); - Assert.assertTrue(validator.validate("", "emptyString", valConfigIgnoreEmptyValues).isValid()); - Assert.assertTrue(validator.validate(" ", "blankString", valConfigIgnoreEmptyValues).isValid()); + Assertions.assertTrue(validator.validate(null, "emptyString", valConfigIgnoreEmptyValues).isValid()); + Assertions.assertTrue(validator.validate("", "emptyString", valConfigIgnoreEmptyValues).isValid()); + Assertions.assertTrue(validator.validate(" ", "blankString", valConfigIgnoreEmptyValues).isValid()); // simple values - Assert.assertTrue(validator.validate(10, "age").isValid()); - Assert.assertTrue(validator.validate("10", "age").isValid()); + Assertions.assertTrue(validator.validate(10, "age").isValid()); + Assertions.assertTrue(validator.validate("10", "age").isValid()); - Assert.assertFalse(validator.validate("3.14", "pi").isValid()); - Assert.assertFalse(validator.validate(" 3.14 ", "piWithBlank").isValid()); - Assert.assertFalse(validator.validate("a", "notAnumber").isValid()); - Assert.assertFalse(validator.validate(true, "true").isValid()); + Assertions.assertFalse(validator.validate("3.14", "pi").isValid()); + Assertions.assertFalse(validator.validate(" 3.14 ", "piWithBlank").isValid()); + Assertions.assertFalse(validator.validate("a", "notAnumber").isValid()); + Assertions.assertFalse(validator.validate(true, "true").isValid()); // collections - Assert.assertTrue(validator.validate(new ArrayList<>(), "age").isValid()); - Assert.assertFalse(validator.validate(Arrays.asList(""), "age").isValid()); - Assert.assertTrue(validator.validate(Arrays.asList(""), "age",valConfigIgnoreEmptyValues).isValid()); - Assert.assertTrue(validator.validate(Arrays.asList(10), "age").isValid()); - Assert.assertFalse(validator.validate(Arrays.asList(" 10 "), "age").isValid()); - - Assert.assertFalse(validator.validate(Arrays.asList("3.14"), "pi").isValid()); - Assert.assertFalse(validator.validate(Arrays.asList("3.14", 10), "pi").isValid()); - Assert.assertFalse(validator.validate(Arrays.asList("a"), "notAnumber").isValid()); - Assert.assertFalse(validator.validate(Arrays.asList("10", "a"), "notANumberPresent").isValid()); - Assert.assertFalse(validator.validate(Arrays.asList("10", new Object()), "notANumberPresent").isValid()); + Assertions.assertTrue(validator.validate(new ArrayList<>(), "age").isValid()); + Assertions.assertFalse(validator.validate(Arrays.asList(""), "age").isValid()); + Assertions.assertTrue(validator.validate(Arrays.asList(""), "age",valConfigIgnoreEmptyValues).isValid()); + Assertions.assertTrue(validator.validate(Arrays.asList(10), "age").isValid()); + Assertions.assertFalse(validator.validate(Arrays.asList(" 10 "), "age").isValid()); + + Assertions.assertFalse(validator.validate(Arrays.asList("3.14"), "pi").isValid()); + Assertions.assertFalse(validator.validate(Arrays.asList("3.14", 10), "pi").isValid()); + Assertions.assertFalse(validator.validate(Arrays.asList("a"), "notAnumber").isValid()); + Assertions.assertFalse(validator.validate(Arrays.asList("10", "a"), "notANumberPresent").isValid()); + Assertions.assertFalse(validator.validate(Arrays.asList("10", new Object()), "notANumberPresent").isValid()); // min only - Assert.assertTrue(validator.validate("10", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 1).build()).isValid()); - Assert.assertFalse(validator.validate("10", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 100).build()).isValid()); + Assertions.assertTrue(validator.validate("10", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 1).build()).isValid()); + Assertions.assertFalse(validator.validate("10", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 100).build()).isValid()); // min behavior around empty values - Assert.assertFalse(validator.validate(null, "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 1).build()).isValid()); - Assert.assertFalse(validator.validate("", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 1).build()).isValid()); - Assert.assertFalse(validator.validate(" ", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 1).build()).isValid()); - Assert.assertTrue(validator.validate(null, "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 1).config(valConfigIgnoreEmptyValues).build()).isValid()); - Assert.assertTrue(validator.validate("", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 1).config(valConfigIgnoreEmptyValues).build()).isValid()); - Assert.assertTrue(validator.validate(" ", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 1).config(valConfigIgnoreEmptyValues).build()).isValid()); + Assertions.assertFalse(validator.validate(null, "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 1).build()).isValid()); + Assertions.assertFalse(validator.validate("", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 1).build()).isValid()); + Assertions.assertFalse(validator.validate(" ", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 1).build()).isValid()); + Assertions.assertTrue(validator.validate(null, "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 1).config(valConfigIgnoreEmptyValues).build()).isValid()); + Assertions.assertTrue(validator.validate("", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 1).config(valConfigIgnoreEmptyValues).build()).isValid()); + Assertions.assertTrue(validator.validate(" ", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 1).config(valConfigIgnoreEmptyValues).build()).isValid()); // max only - Assert.assertFalse(validator.validate("10", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MAX, 1).build()).isValid()); - Assert.assertTrue(validator.validate("10", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MAX, 100).build()).isValid()); + Assertions.assertFalse(validator.validate("10", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MAX, 1).build()).isValid()); + Assertions.assertTrue(validator.validate("10", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MAX, 100).build()).isValid()); // min and max - Assert.assertFalse(validator.validate("9", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 10).config(IntegerValidator.KEY_MAX, 100).build()).isValid()); - Assert.assertTrue(validator.validate("10", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 10).config(IntegerValidator.KEY_MAX, 100).build()).isValid()); - Assert.assertTrue(validator.validate("100", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 10).config(IntegerValidator.KEY_MAX, 100).build()).isValid()); - Assert.assertFalse(validator.validate("101", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 10).config(IntegerValidator.KEY_MAX, 100).build()).isValid()); + Assertions.assertFalse(validator.validate("9", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 10).config(IntegerValidator.KEY_MAX, 100).build()).isValid()); + Assertions.assertTrue(validator.validate("10", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 10).config(IntegerValidator.KEY_MAX, 100).build()).isValid()); + Assertions.assertTrue(validator.validate("100", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 10).config(IntegerValidator.KEY_MAX, 100).build()).isValid()); + Assertions.assertFalse(validator.validate("101", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 10).config(IntegerValidator.KEY_MAX, 100).build()).isValid()); - Assert.assertTrue(validator.validate(Long.MIN_VALUE, "name").isValid()); - Assert.assertTrue(validator.validate(Long.MAX_VALUE, "name").isValid()); + Assertions.assertTrue(validator.validate(Long.MIN_VALUE, "name").isValid()); + Assertions.assertTrue(validator.validate(Long.MAX_VALUE, "name").isValid()); //test correct error message selection - Assert.assertEquals(IntegerValidator.MESSAGE_NUMBER_OUT_OF_RANGE_TOO_SMALL,validator.validate("10", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 100).build()).getErrors().iterator().next().getMessage()); - Assert.assertEquals(IntegerValidator.MESSAGE_NUMBER_OUT_OF_RANGE,validator.validate("10", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 100).config(IntegerValidator.KEY_MAX, 1000).build()).getErrors().iterator().next().getMessage()); - Assert.assertEquals(IntegerValidator.MESSAGE_NUMBER_OUT_OF_RANGE,validator.validate("10000", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 100).config(IntegerValidator.KEY_MAX, 1000).build()).getErrors().iterator().next().getMessage()); - Assert.assertEquals(IntegerValidator.MESSAGE_NUMBER_OUT_OF_RANGE_TOO_BIG,validator.validate("10000", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MAX, 1000).build()).getErrors().iterator().next().getMessage()); + Assertions.assertEquals(IntegerValidator.MESSAGE_NUMBER_OUT_OF_RANGE_TOO_SMALL,validator.validate("10", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 100).build()).getErrors().iterator().next().getMessage()); + Assertions.assertEquals(IntegerValidator.MESSAGE_NUMBER_OUT_OF_RANGE,validator.validate("10", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 100).config(IntegerValidator.KEY_MAX, 1000).build()).getErrors().iterator().next().getMessage()); + Assertions.assertEquals(IntegerValidator.MESSAGE_NUMBER_OUT_OF_RANGE,validator.validate("10000", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MIN, 100).config(IntegerValidator.KEY_MAX, 1000).build()).getErrors().iterator().next().getMessage()); + Assertions.assertEquals(IntegerValidator.MESSAGE_NUMBER_OUT_OF_RANGE_TOO_BIG,validator.validate("10000", "name", ValidatorConfig.builder().config(IntegerValidator.KEY_MAX, 1000).build()).getErrors().iterator().next().getMessage()); } @Test @@ -433,32 +433,32 @@ public void testIntegerValidator_ConfigValidation(KeycloakSession session) { ValidationResult result = BuiltinValidators.validatorConfigValidator().validate(config, IntegerValidator.ID, new ValidationContext(session)).toResult(); - Assert.assertFalse(result.isValid()); + Assertions.assertFalse(result.isValid()); ValidationError[] errors = result.getErrors().toArray(new ValidationError[0]); ValidationError error0 = errors[0]; - Assert.assertNotNull(error0); - Assert.assertEquals(IntegerValidator.ID, error0.getValidatorId()); - Assert.assertEquals(IntegerValidator.KEY_MIN, error0.getInputHint()); + Assertions.assertNotNull(error0); + Assertions.assertEquals(IntegerValidator.ID, error0.getValidatorId()); + Assertions.assertEquals(IntegerValidator.KEY_MIN, error0.getInputHint()); ValidationError error1 = errors[1]; - Assert.assertNotNull(error1); - Assert.assertEquals(IntegerValidator.ID, error1.getValidatorId()); - Assert.assertEquals(IntegerValidator.KEY_MAX, error1.getInputHint()); + Assertions.assertNotNull(error1); + Assertions.assertEquals(IntegerValidator.ID, error1.getValidatorId()); + Assertions.assertEquals(IntegerValidator.KEY_MAX, error1.getInputHint()); // empty config result = BuiltinValidators.validatorConfigValidator().validate(null, IntegerValidator.ID, new ValidationContext(session)).toResult(); - Assert.assertEquals(0, result.getErrors().size()); + Assertions.assertEquals(0, result.getErrors().size()); result = BuiltinValidators.validatorConfigValidator().validate(ValidatorConfig.EMPTY, IntegerValidator.ID, new ValidationContext(session)).toResult(); - Assert.assertEquals(0, result.getErrors().size()); + Assertions.assertEquals(0, result.getErrors().size()); // correct config - Assert.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(IntegerValidator.KEY_MIN, "10")), IntegerValidator.ID, new ValidationContext(session)).toResult().isValid()); - Assert.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(IntegerValidator.KEY_MAX, "10")), IntegerValidator.ID, new ValidationContext(session)).toResult().isValid()); - Assert.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(IntegerValidator.KEY_MIN, "10", IntegerValidator.KEY_MAX, "11")), IntegerValidator.ID, new ValidationContext(session)).toResult().isValid()); + Assertions.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(IntegerValidator.KEY_MIN, "10")), IntegerValidator.ID, new ValidationContext(session)).toResult().isValid()); + Assertions.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(IntegerValidator.KEY_MAX, "10")), IntegerValidator.ID, new ValidationContext(session)).toResult().isValid()); + Assertions.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(IntegerValidator.KEY_MIN, "10", IntegerValidator.KEY_MAX, "11")), IntegerValidator.ID, new ValidationContext(session)).toResult().isValid()); // max is smaller than min - Assert.assertFalse(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(IntegerValidator.KEY_MIN, "10", IntegerValidator.KEY_MAX, "10")), IntegerValidator.ID, new ValidationContext(session)).toResult().isValid()); + Assertions.assertFalse(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(IntegerValidator.KEY_MIN, "10", IntegerValidator.KEY_MAX, "10")), IntegerValidator.ID, new ValidationContext(session)).toResult().isValid()); } @Test @@ -468,27 +468,27 @@ public void testPatternValidator() { // Pattern object in the configuration ValidatorConfig config = configFromMap(Collections.singletonMap(PatternValidator.CFG_PATTERN, Pattern.compile("^start-.*-end$"))); - Assert.assertTrue(validator.validate("start-1234-end", "value", config).isValid()); - Assert.assertFalse(validator.validate("start___end", "value", config).isValid()); + Assertions.assertTrue(validator.validate("start-1234-end", "value", config).isValid()); + Assertions.assertFalse(validator.validate("start___end", "value", config).isValid()); // String in the configuration config = configFromMap(Collections.singletonMap(PatternValidator.CFG_PATTERN, "^start-.*-end$")); - Assert.assertTrue(validator.validate("start-1234-end", "value", config).isValid()); - Assert.assertFalse(validator.validate("start___end", "value", config).isValid()); + Assertions.assertTrue(validator.validate("start-1234-end", "value", config).isValid()); + Assertions.assertFalse(validator.validate("start___end", "value", config).isValid()); //custom error message config = ValidatorConfig.builder().config(PatternValidator.CFG_PATTERN, "^start-.*-end$").config(PatternValidator.CFG_ERROR_MESSAGE, "customError").build(); - Assert.assertEquals("customError", validator.validate("start___end", "value", config).getErrors().iterator().next().getMessage()); + Assertions.assertEquals("customError", validator.validate("start___end", "value", config).getErrors().iterator().next().getMessage()); // null and empty values handling - Assert.assertFalse(validator.validate(null, "value", config).isValid()); - Assert.assertFalse(validator.validate("", "value", config).isValid()); - Assert.assertFalse(validator.validate(" ", "value", config).isValid()); + Assertions.assertFalse(validator.validate(null, "value", config).isValid()); + Assertions.assertFalse(validator.validate("", "value", config).isValid()); + Assertions.assertFalse(validator.validate(" ", "value", config).isValid()); // empty value ignoration configured - Assert.assertTrue(validator.validate(null, "value", valConfigIgnoreEmptyValues).isValid()); - Assert.assertTrue(validator.validate("", "value", valConfigIgnoreEmptyValues).isValid()); - Assert.assertFalse(validator.validate(" ", "value", ValidatorConfig.builder().config(PatternValidator.CFG_PATTERN, "^[^\\s]$").config(valConfigIgnoreEmptyValues).build()).isValid()); + Assertions.assertTrue(validator.validate(null, "value", valConfigIgnoreEmptyValues).isValid()); + Assertions.assertTrue(validator.validate("", "value", valConfigIgnoreEmptyValues).isValid()); + Assertions.assertFalse(validator.validate(" ", "value", ValidatorConfig.builder().config(PatternValidator.CFG_PATTERN, "^[^\\s]$").config(valConfigIgnoreEmptyValues).build()).isValid()); } @@ -497,31 +497,31 @@ public void testUriValidator() throws Exception { Validator validator = BuiltinValidators.uriValidator(); - Assert.assertTrue(validator.validate(null, "baseUrl").isValid()); - Assert.assertTrue(validator.validate("", "baseUrl").isValid()); - Assert.assertTrue(validator.validate("http://localhost:3000/", "baseUrl").isValid()); - Assert.assertTrue(validator.validate("https://localhost:3000/", "baseUrl").isValid()); - Assert.assertTrue(validator.validate("https://localhost:3000/#someFragment", "baseUrl").isValid()); - Assert.assertTrue(validator.validate(new URL("https://localhost:3000/#someFragment"), "baseUrl").isValid()); + Assertions.assertTrue(validator.validate(null, "baseUrl").isValid()); + Assertions.assertTrue(validator.validate("", "baseUrl").isValid()); + Assertions.assertTrue(validator.validate("http://localhost:3000/", "baseUrl").isValid()); + Assertions.assertTrue(validator.validate("https://localhost:3000/", "baseUrl").isValid()); + Assertions.assertTrue(validator.validate("https://localhost:3000/#someFragment", "baseUrl").isValid()); + Assertions.assertTrue(validator.validate(new URL("https://localhost:3000/#someFragment"), "baseUrl").isValid()); // Collections - Assert.assertTrue(validator.validate(Arrays.asList("https://localhost:3000/#someFragment", "https://localhost:3000"), "baseUrl").isValid()); - Assert.assertTrue(validator.validate(Arrays.asList("https://localhost:3000/#someFragment"), "baseUrl").isValid()); - Assert.assertTrue(validator.validate(Arrays.asList(new URL("https://localhost:3000/#someFragment")), "baseUrl").isValid()); - Assert.assertTrue(validator.validate(Arrays.asList(""), "baseUrl").isValid()); + Assertions.assertTrue(validator.validate(Arrays.asList("https://localhost:3000/#someFragment", "https://localhost:3000"), "baseUrl").isValid()); + Assertions.assertTrue(validator.validate(Arrays.asList("https://localhost:3000/#someFragment"), "baseUrl").isValid()); + Assertions.assertTrue(validator.validate(Arrays.asList(new URL("https://localhost:3000/#someFragment")), "baseUrl").isValid()); + Assertions.assertTrue(validator.validate(Arrays.asList(""), "baseUrl").isValid()); - Assert.assertFalse(validator.validate(" ", "baseUrl").isValid()); - Assert.assertFalse(validator.validate("file:///somefile.txt", "baseUrl").isValid()); - Assert.assertFalse(validator.validate("invalidUrl++@23", "invalidUri").isValid()); - Assert.assertFalse(validator.validate(Arrays.asList("https://localhost:3000/#someFragment", "file:///somefile.txt"), "baseUrl").isValid()); + Assertions.assertFalse(validator.validate(" ", "baseUrl").isValid()); + Assertions.assertFalse(validator.validate("file:///somefile.txt", "baseUrl").isValid()); + Assertions.assertFalse(validator.validate("invalidUrl++@23", "invalidUri").isValid()); + Assertions.assertFalse(validator.validate(Arrays.asList("https://localhost:3000/#someFragment", "file:///somefile.txt"), "baseUrl").isValid()); ValidatorConfig config = configFromMap(ImmutableMap.of(UriValidator.KEY_ALLOW_FRAGMENT, false)); - Assert.assertFalse(validator.validate("https://localhost:3000/#someFragment", "baseUrl", config).isValid()); + Assertions.assertFalse(validator.validate("https://localhost:3000/#someFragment", "baseUrl", config).isValid()); // it is also possible to call dedicated validation methods on a built-in validator - Assert.assertTrue(BuiltinValidators.uriValidator().validateUri(new URI("https://customurl"), Collections.singleton("https"), true, true)); + Assertions.assertTrue(BuiltinValidators.uriValidator().validateUri(new URI("https://customurl"), Collections.singleton("https"), true, true)); - Assert.assertFalse(BuiltinValidators.uriValidator().validateUri(new URI("http://customurl"), Collections.singleton("https"), true, true)); + Assertions.assertFalse(BuiltinValidators.uriValidator().validateUri(new URI("http://customurl"), Collections.singleton("https"), true, true)); } @Test @@ -529,38 +529,38 @@ public void testOptionsValidator(){ Validator validator = BuiltinValidators.optionsValidator(); // options not configured - always invalid - Assert.assertFalse(validator.validate(null, "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, null).build()).isValid()); - Assert.assertFalse(validator.validate("", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, null).build()).isValid()); - Assert.assertFalse(validator.validate(" ", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, null).build()).isValid()); - Assert.assertFalse(validator.validate("s", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, null).build()).isValid()); + Assertions.assertFalse(validator.validate(null, "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, null).build()).isValid()); + Assertions.assertFalse(validator.validate("", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, null).build()).isValid()); + Assertions.assertFalse(validator.validate(" ", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, null).build()).isValid()); + Assertions.assertFalse(validator.validate("s", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, null).build()).isValid()); // options not configured but empty and blanks ignored, others invalid - Assert.assertTrue(validator.validate(null, "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, null).config(valConfigIgnoreEmptyValues).build()).isValid()); - Assert.assertTrue(validator.validate("", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, null).config(valConfigIgnoreEmptyValues).build()).isValid()); - Assert.assertFalse(validator.validate(" ", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, null).config(valConfigIgnoreEmptyValues).build()).isValid()); - Assert.assertFalse(validator.validate("s", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, null).config(valConfigIgnoreEmptyValues).build()).isValid()); + Assertions.assertTrue(validator.validate(null, "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, null).config(valConfigIgnoreEmptyValues).build()).isValid()); + Assertions.assertTrue(validator.validate("", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, null).config(valConfigIgnoreEmptyValues).build()).isValid()); + Assertions.assertFalse(validator.validate(" ", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, null).config(valConfigIgnoreEmptyValues).build()).isValid()); + Assertions.assertFalse(validator.validate("s", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, null).config(valConfigIgnoreEmptyValues).build()).isValid()); List options = Arrays.asList("opt1", "opt2"); // options configured - Assert.assertFalse(validator.validate(null, "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).build()).isValid()); - Assert.assertFalse(validator.validate("", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).build()).isValid()); - Assert.assertFalse(validator.validate(" ", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).build()).isValid()); - Assert.assertFalse("must be case sensitive", validator.validate("Opt1", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).build()).isValid()); - Assert.assertTrue(validator.validate("opt1", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).build()).isValid()); - Assert.assertTrue(validator.validate("opt2", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).build()).isValid()); - Assert.assertFalse("trim not expected", validator.validate("opt2 ", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).build()).isValid()); - Assert.assertFalse("trim not expected", validator.validate(" opt2", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).build()).isValid()); + Assertions.assertFalse(validator.validate(null, "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).build()).isValid()); + Assertions.assertFalse(validator.validate("", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).build()).isValid()); + Assertions.assertFalse(validator.validate(" ", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).build()).isValid()); + Assertions.assertFalse(validator.validate("Opt1", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).build()).isValid(), "must be case sensitive"); + Assertions.assertTrue(validator.validate("opt1", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).build()).isValid()); + Assertions.assertTrue(validator.validate("opt2", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).build()).isValid()); + Assertions.assertFalse(validator.validate("opt2 ", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).build()).isValid(), "trim not expected"); + Assertions.assertFalse(validator.validate(" opt2", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).build()).isValid(), "trim not expected"); // options configured - empty and blanks ignored - Assert.assertTrue(validator.validate(null, "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).config(valConfigIgnoreEmptyValues).build()).isValid()); - Assert.assertTrue(validator.validate("", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).config(valConfigIgnoreEmptyValues).build()).isValid()); - Assert.assertFalse(validator.validate(" ", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).config(valConfigIgnoreEmptyValues).build()).isValid()); - Assert.assertFalse("must be case sensitive", validator.validate("Opt1", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).config(valConfigIgnoreEmptyValues).build()).isValid()); - Assert.assertTrue(validator.validate("opt1", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).config(valConfigIgnoreEmptyValues).build()).isValid()); - Assert.assertTrue(validator.validate("opt2", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).config(valConfigIgnoreEmptyValues).build()).isValid()); - Assert.assertFalse("trim not expected", validator.validate(" opt2", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).config(valConfigIgnoreEmptyValues).build()).isValid()); - Assert.assertFalse("trim not expected", validator.validate("opt2 ", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).config(valConfigIgnoreEmptyValues).build()).isValid()); + Assertions.assertTrue(validator.validate(null, "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).config(valConfigIgnoreEmptyValues).build()).isValid()); + Assertions.assertTrue(validator.validate("", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).config(valConfigIgnoreEmptyValues).build()).isValid()); + Assertions.assertFalse(validator.validate(" ", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).config(valConfigIgnoreEmptyValues).build()).isValid()); + Assertions.assertFalse(validator.validate("Opt1", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).config(valConfigIgnoreEmptyValues).build()).isValid(), "must be case sensitive"); + Assertions.assertTrue(validator.validate("opt1", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).config(valConfigIgnoreEmptyValues).build()).isValid()); + Assertions.assertTrue(validator.validate("opt2", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).config(valConfigIgnoreEmptyValues).build()).isValid()); + Assertions.assertFalse(validator.validate(" opt2", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).config(valConfigIgnoreEmptyValues).build()).isValid(), "trim not expected"); + Assertions.assertFalse(validator.validate("opt2 ", "test", ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, options).config(valConfigIgnoreEmptyValues).build()).isValid(), "trim not expected"); } @Test @@ -568,14 +568,14 @@ public void testOptionsValidator(){ public void testOptionsValidator_Config_Validation(KeycloakSession session) { ValidationResult result = BuiltinValidators.validatorConfigValidator().validate(ValidatorConfig.builder().build(), OptionsValidator.ID, new ValidationContext(session)).toResult(); - Assert.assertFalse(result.isValid()); + Assertions.assertFalse(result.isValid()); // invalid type of the config value result = BuiltinValidators.validatorConfigValidator().validate(ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, "a").build(), OptionsValidator.ID, new ValidationContext(session)).toResult(); - Assert.assertFalse(result.isValid()); + Assertions.assertFalse(result.isValid()); result = BuiltinValidators.validatorConfigValidator().validate(ValidatorConfig.builder().config(OptionsValidator.KEY_OPTIONS, Arrays.asList("opt1")).build(), OptionsValidator.ID, new ValidationContext(session)).toResult(); - Assert.assertTrue(result.isValid()); + Assertions.assertTrue(result.isValid()); } @@ -586,34 +586,34 @@ public void testMultivaluedValidatorConfiguration(KeycloakSession session) { ValidatorConfig config = new ValidatorConfig(ImmutableMap.of(MultiValueValidator.KEY_MIN, new Object(), MultiValueValidator.KEY_MAX, "invalid")); ValidationResult result = BuiltinValidators.validatorConfigValidator().validate(config, MultiValueValidator.ID, new ValidationContext(session)).toResult(); - Assert.assertFalse(result.isValid()); + Assertions.assertFalse(result.isValid()); ValidationError[] errors = result.getErrors().toArray(new ValidationError[0]); ValidationError error0 = errors[0]; - Assert.assertNotNull(error0); - Assert.assertEquals(MultiValueValidator.ID, error0.getValidatorId()); - Assert.assertEquals(MultiValueValidator.KEY_MAX, error0.getInputHint()); + Assertions.assertNotNull(error0); + Assertions.assertEquals(MultiValueValidator.ID, error0.getValidatorId()); + Assertions.assertEquals(MultiValueValidator.KEY_MAX, error0.getInputHint()); ValidationError error1 = errors[1]; - Assert.assertNotNull(error1); - Assert.assertEquals(MultiValueValidator.ID, error1.getValidatorId()); - Assert.assertEquals(MultiValueValidator.KEY_MIN, error1.getInputHint()); + Assertions.assertNotNull(error1); + Assertions.assertEquals(MultiValueValidator.ID, error1.getValidatorId()); + Assertions.assertEquals(MultiValueValidator.KEY_MIN, error1.getInputHint()); // empty config result = BuiltinValidators.validatorConfigValidator().validate(null, MultiValueValidator.ID, new ValidationContext(session)).toResult(); - Assert.assertEquals(1, result.getErrors().size()); + Assertions.assertEquals(1, result.getErrors().size()); result = BuiltinValidators.validatorConfigValidator().validate(ValidatorConfig.EMPTY, MultiValueValidator.ID, new ValidationContext(session)).toResult(); - Assert.assertEquals(1, result.getErrors().size()); + Assertions.assertEquals(1, result.getErrors().size()); // correct config - Assert.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(MultiValueValidator.KEY_MAX, "10")), MultiValueValidator.ID, new ValidationContext(session)).toResult().isValid()); - Assert.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(MultiValueValidator.KEY_MIN, "10", MultiValueValidator.KEY_MAX, "10")), MultiValueValidator.ID, new ValidationContext(session)).toResult().isValid()); - Assert.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(MultiValueValidator.KEY_MIN, "10", MultiValueValidator.KEY_MAX, "11")), MultiValueValidator.ID, new ValidationContext(session)).toResult().isValid()); + Assertions.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(MultiValueValidator.KEY_MAX, "10")), MultiValueValidator.ID, new ValidationContext(session)).toResult().isValid()); + Assertions.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(MultiValueValidator.KEY_MIN, "10", MultiValueValidator.KEY_MAX, "10")), MultiValueValidator.ID, new ValidationContext(session)).toResult().isValid()); + Assertions.assertTrue(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(MultiValueValidator.KEY_MIN, "10", MultiValueValidator.KEY_MAX, "11")), MultiValueValidator.ID, new ValidationContext(session)).toResult().isValid()); // max is smaller than min - Assert.assertFalse(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(MultiValueValidator.KEY_MIN, "10", MultiValueValidator.KEY_MAX, "9")), MultiValueValidator.ID, new ValidationContext(session)).toResult().isValid()); + Assertions.assertFalse(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(MultiValueValidator.KEY_MIN, "10", MultiValueValidator.KEY_MAX, "9")), MultiValueValidator.ID, new ValidationContext(session)).toResult().isValid()); // max not set - Assert.assertFalse(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(MultiValueValidator.KEY_MIN, "10")), MultiValueValidator.ID, new ValidationContext(session)).toResult().isValid()); + Assertions.assertFalse(BuiltinValidators.validatorConfigValidator().validate(new ValidatorConfig(ImmutableMap.of(MultiValueValidator.KEY_MIN, "10")), MultiValueValidator.ID, new ValidationContext(session)).toResult().isValid()); } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/validation/ValidatorTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/validation/ValidatorTest.java index 57205d3fcbd7..4caedeec47d0 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/validation/ValidatorTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/validation/ValidatorTest.java @@ -33,8 +33,8 @@ import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Pedro Igor diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/validation/ValidatorsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/validation/ValidatorsTest.java index e145db4bc949..c74b9d5a444e 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/validation/ValidatorsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/validation/ValidatorsTest.java @@ -45,8 +45,8 @@ import org.keycloak.validate.validators.NotBlankValidator; import org.keycloak.validate.validators.ValidatorConfigValidator; -import org.junit.Assert; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import static org.keycloak.validate.ValidatorConfig.configFromMap; @@ -61,8 +61,8 @@ public void simpleValidation() { Validator validator = BuiltinValidators.notEmptyValidator(); - Assert.assertTrue(validator.validate("a").isValid()); - Assert.assertFalse(validator.validate("").isValid()); + Assertions.assertTrue(validator.validate("a").isValid()); + Assertions.assertFalse(validator.validate("").isValid()); } @Test @@ -75,7 +75,7 @@ public void simpleValidationWithContext(KeycloakSession session) { validator.validate("a", "username", context); ValidationResult result = context.toResult(); - Assert.assertTrue(result.isValid()); + Assertions.assertTrue(result.isValid()); } @Test @@ -86,7 +86,7 @@ public void simpleValidationFluent(KeycloakSession session) { ValidationResult result = BuiltinValidators.lengthValidator().validate("a", "username", context).toResult(); - Assert.assertTrue(result.isValid()); + Assertions.assertTrue(result.isValid()); } @Test @@ -100,7 +100,7 @@ public void simpleValidationLookup(KeycloakSession session) { validator.validate("a", "username", context); ValidationResult result = context.toResult(); - Assert.assertTrue(result.isValid()); + Assertions.assertTrue(result.isValid()); } @Test @@ -116,25 +116,25 @@ public void simpleValidationError(KeycloakSession session) { validator.validate(input, inputHint, context, configFromMap(Collections.singletonMap("min", "2"))); ValidationResult result = context.toResult(); - Assert.assertFalse(result.isValid()); - Assert.assertEquals(1, result.getErrors().size()); + Assertions.assertFalse(result.isValid()); + Assertions.assertEquals(1, result.getErrors().size()); ValidationError[] errors = result.getErrors().toArray(new ValidationError[0]); ValidationError error = errors[0]; - Assert.assertNotNull(error); - Assert.assertEquals(LengthValidator.ID, error.getValidatorId()); - Assert.assertEquals(inputHint, error.getInputHint()); - Assert.assertEquals(LengthValidator.MESSAGE_INVALID_LENGTH_TOO_SHORT, error.getMessage()); - Assert.assertEquals(Integer.valueOf(2), error.getMessageParameters()[0]); + Assertions.assertNotNull(error); + Assertions.assertEquals(LengthValidator.ID, error.getValidatorId()); + Assertions.assertEquals(inputHint, error.getInputHint()); + Assertions.assertEquals(LengthValidator.MESSAGE_INVALID_LENGTH_TOO_SHORT, error.getMessage()); + Assertions.assertEquals(Integer.valueOf(2), error.getMessageParameters()[0]); - Assert.assertTrue(result.hasErrorsForValidatorId(LengthValidator.ID)); - Assert.assertFalse(result.hasErrorsForValidatorId("unknown")); + Assertions.assertTrue(result.hasErrorsForValidatorId(LengthValidator.ID)); + Assertions.assertFalse(result.hasErrorsForValidatorId("unknown")); - Assert.assertEquals(result.getErrors(), result.getErrorsForValidatorId(LengthValidator.ID)); - Assert.assertEquals(result.getErrors(), result.getErrorsForInputHint(inputHint)); + Assertions.assertEquals(result.getErrors(), result.getErrorsForValidatorId(LengthValidator.ID)); + Assertions.assertEquals(result.getErrors(), result.getErrorsForInputHint(inputHint)); - Assert.assertTrue(result.hasErrorsForInputHint(inputHint)); - Assert.assertFalse(result.hasErrorsForInputHint("email")); + Assertions.assertTrue(result.hasErrorsForInputHint(inputHint)); + Assertions.assertFalse(result.hasErrorsForInputHint("email")); } @Test @@ -142,11 +142,11 @@ public void acceptOnError() { AtomicBoolean bool1 = new AtomicBoolean(); BuiltinValidators.notEmptyValidator().validate("a").toResult().ifNotValidAccept(r -> bool1.set(true)); - Assert.assertFalse(bool1.get()); + Assertions.assertFalse(bool1.get()); AtomicBoolean bool2 = new AtomicBoolean(); BuiltinValidators.notEmptyValidator().validate("").toResult().ifNotValidAccept(r -> bool2.set(true)); - Assert.assertTrue(bool2.get()); + Assertions.assertTrue(bool2.get()); } @Test @@ -159,7 +159,7 @@ public void forEachError(KeycloakSession session) { errors.add(e.getMessage()); }); - Assert.assertEquals(Arrays.asList(NotBlankValidator.MESSAGE_BLANK, NotBlankValidator.MESSAGE_BLANK), errors); + Assertions.assertEquals(Arrays.asList(NotBlankValidator.MESSAGE_BLANK, NotBlankValidator.MESSAGE_BLANK), errors); } @Test @@ -176,7 +176,7 @@ public void formatError(KeycloakSession session) { errors.add(e.formatMessage((message, args) -> MessageFormat.format(miniResourceBundle.getOrDefault(message, message), args))); }); - Assert.assertEquals(Arrays.asList("address.street is blank: <>", "address.zip is blank: "), errors); + Assertions.assertEquals(Arrays.asList("address.street is blank: <>", "address.zip is blank: "), errors); } @Test @@ -193,7 +193,7 @@ public void multipleValidations(KeycloakSession session) { ValidationResult result = context.toResult(); - Assert.assertTrue(result.isValid()); + Assertions.assertTrue(result.isValid()); } @Test @@ -210,18 +210,18 @@ public void multipleValidationsError(KeycloakSession session) { ValidationResult result = context.toResult(); - Assert.assertFalse(result.isValid()); - Assert.assertEquals(2, result.getErrors().size()); + Assertions.assertFalse(result.isValid()); + Assertions.assertEquals(2, result.getErrors().size()); ValidationError[] errors = result.getErrors().toArray(new ValidationError[0]); ValidationError error1 = errors[1]; - Assert.assertNotNull(error1); - Assert.assertEquals(NotBlankValidator.ID, error1.getValidatorId()); - Assert.assertEquals(inputHint, error1.getInputHint()); - Assert.assertEquals(NotBlankValidator.MESSAGE_BLANK, error1.getMessage()); - Assert.assertEquals(input, error1.getMessageParameters()[0]); + Assertions.assertNotNull(error1); + Assertions.assertEquals(NotBlankValidator.ID, error1.getValidatorId()); + Assertions.assertEquals(inputHint, error1.getInputHint()); + Assertions.assertEquals(NotBlankValidator.MESSAGE_BLANK, error1.getMessage()); + Assertions.assertEquals(input, error1.getMessageParameters()[0]); } @Test @@ -230,12 +230,12 @@ public void validateValidatorConfigSimple(KeycloakSession session) { SimpleValidator validator = LengthValidator.INSTANCE; - Assert.assertFalse(validator.validateConfig(session, null).isValid()); - Assert.assertTrue(validator.validateConfig(session, configFromMap(Collections.singletonMap("min", 1))).isValid()); - Assert.assertTrue(validator.validateConfig(session, configFromMap(Collections.singletonMap("max", 100))).isValid()); - Assert.assertFalse(validator.validateConfig(session, configFromMap(Collections.singletonMap("min", null))).isValid()); - Assert.assertFalse(validator.validateConfig(session, configFromMap(Collections.singletonMap("min", "a"))).isValid()); - Assert.assertTrue(validator.validateConfig(session, configFromMap(Collections.singletonMap("min", "123"))).isValid()); + Assertions.assertFalse(validator.validateConfig(session, null).isValid()); + Assertions.assertTrue(validator.validateConfig(session, configFromMap(Collections.singletonMap("min", 1))).isValid()); + Assertions.assertTrue(validator.validateConfig(session, configFromMap(Collections.singletonMap("max", 100))).isValid()); + Assertions.assertFalse(validator.validateConfig(session, configFromMap(Collections.singletonMap("min", null))).isValid()); + Assertions.assertFalse(validator.validateConfig(session, configFromMap(Collections.singletonMap("min", "a"))).isValid()); + Assertions.assertTrue(validator.validateConfig(session, configFromMap(Collections.singletonMap("min", "123"))).isValid()); } @Test @@ -243,17 +243,17 @@ public void validateValidatorConfigSimple(KeycloakSession session) { public void validateEmailValidator(KeycloakSession session) { SimpleValidator validator = BuiltinValidators.emailValidator(); - Assert.assertTrue(validator.validateConfig(session, null).isValid()); - Assert.assertTrue(validator.validateConfig(session, ValidatorConfig.EMPTY).isValid()); - Assert.assertTrue(validator.validateConfig(session, configFromMap(Collections.singletonMap( + Assertions.assertTrue(validator.validateConfig(session, null).isValid()); + Assertions.assertTrue(validator.validateConfig(session, ValidatorConfig.EMPTY).isValid()); + Assertions.assertTrue(validator.validateConfig(session, configFromMap(Collections.singletonMap( EmailValidator.MAX_LOCAL_PART_LENGTH_PROPERTY, 128))).isValid()); - Assert.assertTrue(validator.validateConfig(session, configFromMap(Collections.singletonMap( + Assertions.assertTrue(validator.validateConfig(session, configFromMap(Collections.singletonMap( EmailValidator.MAX_LOCAL_PART_LENGTH_PROPERTY, "128"))).isValid()); - Assert.assertFalse(validator.validateConfig(session, configFromMap(Collections.singletonMap( + Assertions.assertFalse(validator.validateConfig(session, configFromMap(Collections.singletonMap( EmailValidator.MAX_LOCAL_PART_LENGTH_PROPERTY, null))).isValid()); - Assert.assertFalse(validator.validateConfig(session, configFromMap(Collections.singletonMap( + Assertions.assertFalse(validator.validateConfig(session, configFromMap(Collections.singletonMap( EmailValidator.MAX_LOCAL_PART_LENGTH_PROPERTY, "a"))).isValid()); - Assert.assertFalse(validator.validateConfig(session, configFromMap(Collections.singletonMap( + Assertions.assertFalse(validator.validateConfig(session, configFromMap(Collections.singletonMap( EmailValidator.MAX_LOCAL_PART_LENGTH_PROPERTY, ""))).isValid()); } @@ -269,7 +269,7 @@ public void validateValidatorConfigMultipleOptions(KeycloakSession session) { ValidatorConfig validatorConfig = configFromMap(config); - Assert.assertTrue(validator.validateConfig(session, validatorConfig).isValid()); + Assertions.assertTrue(validator.validateConfig(session, validatorConfig).isValid()); } @Test @@ -284,17 +284,17 @@ public void validateValidatorConfigMultipleOptionsInvalidValues(KeycloakSession ValidationResult result = validator.validateConfig(session, configFromMap(config)); - Assert.assertFalse(result.isValid()); - Assert.assertEquals(2, result.getErrors().size()); + Assertions.assertFalse(result.isValid()); + Assertions.assertEquals(2, result.getErrors().size()); ValidationError[] errors = result.getErrors().toArray(new ValidationError[0]); ValidationError error1 = errors[1]; - Assert.assertNotNull(error1); - Assert.assertEquals(LengthValidator.ID, error1.getValidatorId()); - Assert.assertEquals("max", error1.getInputHint()); - Assert.assertEquals(ValidatorConfigValidator.MESSAGE_CONFIG_INVALID_NUMBER_VALUE, error1.getMessage()); - Assert.assertEquals(new ArrayList<>(), error1.getMessageParameters()[0]); + Assertions.assertNotNull(error1); + Assertions.assertEquals(LengthValidator.ID, error1.getValidatorId()); + Assertions.assertEquals("max", error1.getInputHint()); + Assertions.assertEquals(ValidatorConfigValidator.MESSAGE_CONFIG_INVALID_NUMBER_VALUE, error1.getMessage()); + Assertions.assertEquals(new ArrayList<>(), error1.getMessageParameters()[0]); } @Test @@ -308,48 +308,48 @@ public void validateValidatorConfigViaValidatorFactory(KeycloakSession session) ValidatorConfig validatorConfig = configFromMap(config); ValidationResult result = Validators.validateConfig(session, LengthValidator.ID, validatorConfig); - Assert.assertEquals(2, result.getErrors().size()); + Assertions.assertEquals(2, result.getErrors().size()); ValidationError[] errors = result.getErrors().toArray(new ValidationError[0]); ValidationError error1 = errors[1]; - Assert.assertNotNull(error1); - Assert.assertEquals(LengthValidator.ID, error1.getValidatorId()); - Assert.assertEquals("max", error1.getInputHint()); - Assert.assertEquals(ValidatorConfigValidator.MESSAGE_CONFIG_INVALID_NUMBER_VALUE, error1.getMessage()); - Assert.assertEquals(new ArrayList<>(), error1.getMessageParameters()[0]); + Assertions.assertNotNull(error1); + Assertions.assertEquals(LengthValidator.ID, error1.getValidatorId()); + Assertions.assertEquals("max", error1.getInputHint()); + Assertions.assertEquals(ValidatorConfigValidator.MESSAGE_CONFIG_INVALID_NUMBER_VALUE, error1.getMessage()); + Assertions.assertEquals(new ArrayList<>(), error1.getMessageParameters()[0]); } @Test @ModelTest public void nestedValidation(KeycloakSession session) { - Assert.assertTrue(MockAddressValidator.INSTANCE.validate( + Assertions.assertTrue(MockAddressValidator.INSTANCE.validate( new MockAddress("4848 Arcu St.", "Saint-Maur-des-Fossés", "02206", "Germany") , "address", new ValidationContext(session)).isValid()); ValidationResult result = MockAddressValidator.INSTANCE.validate( new MockAddress("", "Saint-Maur-des-Fossés", null, "Germany") , "address", new ValidationContext(session)).toResult(); - Assert.assertFalse(result.isValid()); - Assert.assertEquals(2, result.getErrors().size()); + Assertions.assertFalse(result.isValid()); + Assertions.assertEquals(2, result.getErrors().size()); ValidationError[] errors = result.getErrors().toArray(new ValidationError[0]); ValidationError error0 = errors[0]; - Assert.assertNotNull(error0); - Assert.assertEquals(NotBlankValidator.ID, error0.getValidatorId()); - Assert.assertEquals("address.street", error0.getInputHint()); - Assert.assertEquals(NotBlankValidator.MESSAGE_BLANK, error0.getMessage()); - Assert.assertEquals("", error0.getMessageParameters()[0]); + Assertions.assertNotNull(error0); + Assertions.assertEquals(NotBlankValidator.ID, error0.getValidatorId()); + Assertions.assertEquals("address.street", error0.getInputHint()); + Assertions.assertEquals(NotBlankValidator.MESSAGE_BLANK, error0.getMessage()); + Assertions.assertEquals("", error0.getMessageParameters()[0]); ValidationError error1 = errors[1]; - Assert.assertNotNull(error1); - Assert.assertEquals(NotBlankValidator.ID, error1.getValidatorId()); - Assert.assertEquals("address.zip", error1.getInputHint()); - Assert.assertEquals(NotBlankValidator.MESSAGE_BLANK, error1.getMessage()); + Assertions.assertNotNull(error1); + Assertions.assertEquals(NotBlankValidator.ID, error1.getValidatorId()); + Assertions.assertEquals("address.zip", error1.getInputHint()); + Assertions.assertEquals(NotBlankValidator.MESSAGE_BLANK, error1.getMessage()); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/vault/AbstractKeycloakVaultTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/vault/AbstractKeycloakVaultTest.java index e70dd9012d15..8498eb506cf6 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/vault/AbstractKeycloakVaultTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/vault/AbstractKeycloakVaultTest.java @@ -29,7 +29,7 @@ import org.keycloak.vault.VaultTranscriber; import org.jetbrains.annotations.NotNull; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; /** * Tests the usage of the {@link VaultTranscriber} on the server side. The tests attempt to obtain the transcriber from @@ -60,17 +60,17 @@ public void run(KeycloakSession session) { VaultTranscriber transcriber = getVaultTranscriber(session); // obtain an existing secret from the vault. Optional optional = getSecret(transcriber, testKey); - Assert.assertTrue(optional.isPresent()); - Assert.assertEquals(expectedSecret, optional.get()); + Assertions.assertTrue(optional.isPresent()); + Assertions.assertEquals(expectedSecret, optional.get()); // try obtaining a secret using a key that does not exist in the vault. optional = getSecret(transcriber, "${vault.invalid_entry}"); - Assert.assertFalse(optional.isPresent()); + Assertions.assertFalse(optional.isPresent()); // invoke the transcriber using a string that is not a vault expression. optional = getSecret(transcriber, "mysecret"); - Assert.assertTrue(optional.isPresent()); - Assert.assertEquals("mysecret", optional.get()); + Assertions.assertTrue(optional.isPresent()); + Assertions.assertEquals("mysecret", optional.get()); } private Optional getSecret(VaultTranscriber transcriber, String testKey) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/AbstractWebAuthnVirtualTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/AbstractWebAuthnVirtualTest.java index 22185b96619b..ede52e216ad1 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/AbstractWebAuthnVirtualTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/AbstractWebAuthnVirtualTest.java @@ -80,7 +80,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Abstract class for WebAuthn tests which use Virtual Authenticators diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/AppInitiatedActionWebAuthnTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/AppInitiatedActionWebAuthnTest.java index 9de0670549cf..7fead735b1f1 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/AppInitiatedActionWebAuthnTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/AppInitiatedActionWebAuthnTest.java @@ -66,8 +66,8 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Martin Bartos diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/passwordless/PasskeysKcOidcFirstBrokerLoginTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/passwordless/PasskeysKcOidcFirstBrokerLoginTest.java index 3286db646b33..750c672528f7 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/passwordless/PasskeysKcOidcFirstBrokerLoginTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/passwordless/PasskeysKcOidcFirstBrokerLoginTest.java @@ -49,9 +49,9 @@ import org.jboss.arquillian.graphene.page.Page; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.firefox.FirefoxDriver; @@ -143,18 +143,18 @@ public void testLinkAccountByReauthenticationWithPassword() { logInWithBroker(bc); BrokerTestTools.waitForPage(driver, "account already exists", false); - Assert.assertTrue(idpConfirmLinkPage.isCurrent()); - Assert.assertEquals("User with email user@localhost.com already exists. How do you want to continue?", idpConfirmLinkPage.getMessage()); + Assertions.assertTrue(idpConfirmLinkPage.isCurrent()); + Assertions.assertEquals("User with email user@localhost.com already exists. How do you want to continue?", idpConfirmLinkPage.getMessage()); idpConfirmLinkPage.clickLinkAccount(); - Assert.assertEquals("Authenticate to link your account with " + bc.getIDPAlias(), loginPage.getInfoMessage()); + Assertions.assertEquals("Authenticate to link your account with " + bc.getIDPAlias(), loginPage.getInfoMessage()); - Assert.assertThrows(NoSuchElementException.class, () -> loginPage.findSocialButton(bc.getIDPAlias())); - Assert.assertThrows(NoSuchElementException.class, () -> loginPage.clickRegister()); + Assertions.assertThrows(NoSuchElementException.class, () -> loginPage.findSocialButton(bc.getIDPAlias())); + Assertions.assertThrows(NoSuchElementException.class, () -> loginPage.clickRegister()); webAuthnLoginPage.isCurrent(); loginPage.login(bc.getUserPassword()); - Assert.assertTrue(appPage.isCurrent()); + Assertions.assertTrue(appPage.isCurrent()); assertNumFederatedIdentities(AdminApiUtil.findUserByUsername(adminClient.realm(bc.consumerRealmName()), "consumer").getId(), 1); } @@ -171,21 +171,21 @@ public void testLinkAccountByReauthenticationWithExternalPasskey() { logInWithBroker(bc); BrokerTestTools.waitForPage(driver, "account already exists", false); - Assert.assertTrue(idpConfirmLinkPage.isCurrent()); - Assert.assertEquals("User with email user@localhost.com already exists. How do you want to continue?", idpConfirmLinkPage.getMessage()); + Assertions.assertTrue(idpConfirmLinkPage.isCurrent()); + Assertions.assertEquals("User with email user@localhost.com already exists. How do you want to continue?", idpConfirmLinkPage.getMessage()); idpConfirmLinkPage.clickLinkAccount(); - Assert.assertEquals("Authenticate to link your account with " + bc.getIDPAlias(), loginPage.getInfoMessage()); + Assertions.assertEquals("Authenticate to link your account with " + bc.getIDPAlias(), loginPage.getInfoMessage()); - Assert.assertThrows(NoSuchElementException.class, () -> loginPage.findSocialButton(bc.getIDPAlias())); - Assert.assertThrows(NoSuchElementException.class, () -> loginPage.clickRegister()); + Assertions.assertThrows(NoSuchElementException.class, () -> loginPage.findSocialButton(bc.getIDPAlias())); + Assertions.assertThrows(NoSuchElementException.class, () -> loginPage.clickRegister()); webAuthnLoginPage.isCurrent(); loginPage.login(generatePassword()); // invalid password - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); webAuthnLoginPage.clickAuthenticate(); - Assert.assertTrue(appPage.isCurrent()); + Assertions.assertTrue(appPage.isCurrent()); assertNumFederatedIdentities(AdminApiUtil.findUserByUsername(adminClient.realm(bc.consumerRealmName()), "consumer").getId(), 1); } @@ -208,12 +208,12 @@ public void testLinkAccountByReauthenticationWithDiscoverablePasskey() throws IO } BrokerTestTools.waitForPage(driver, "account already exists", false); - Assert.assertTrue(idpConfirmLinkPage.isCurrent()); - Assert.assertEquals("User with email user@localhost.com already exists. How do you want to continue?", idpConfirmLinkPage.getMessage()); + Assertions.assertTrue(idpConfirmLinkPage.isCurrent()); + Assertions.assertEquals("User with email user@localhost.com already exists. How do you want to continue?", idpConfirmLinkPage.getMessage()); idpConfirmLinkPage.clickLinkAccount(); // login is automatically now via discoverable passkey - Assert.assertTrue(appPage.isCurrent()); + Assertions.assertTrue(appPage.isCurrent()); assertNumFederatedIdentities(AdminApiUtil.findUserByUsername(adminClient.realm(bc.consumerRealmName()), "consumer").getId(), 1); } @@ -269,7 +269,7 @@ protected void logout() { logoutConfirmPage.assertCurrent(); logoutConfirmPage.confirmLogout(); infoPage.assertCurrent(); - Assert.assertEquals("You are logged out", infoPage.getInfo()); + Assertions.assertEquals("You are logged out", infoPage.getInfo()); } catch (Exception e) { throw new RuntimeException("Cannot logout user", e); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/passwordless/PasskeysOrganizationAuthenticationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/passwordless/PasskeysOrganizationAuthenticationTest.java index 5aa1eb15cb3f..74661f2125e7 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/passwordless/PasskeysOrganizationAuthenticationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/passwordless/PasskeysOrganizationAuthenticationTest.java @@ -37,7 +37,6 @@ import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.testsuite.AbstractAdminTest; -import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.arquillian.annotation.IgnoreBrowserDriver; import org.keycloak.testsuite.util.WaitUtils; @@ -47,6 +46,7 @@ import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.By; import org.openqa.selenium.firefox.FirefoxDriver; @@ -146,7 +146,7 @@ public void webauthnLoginWithDiscoverableKeyRequiresMembership() throws IOExcept .filter(exec -> OrganizationAuthenticatorFactory.ID.equals(exec.getProviderId())) .findAny() .orElse(null); - Assert.assertNotNull("Organization execution not found", organizationExec); + Assertions.assertNotNull(organizationExec, "Organization execution not found"); AuthenticatorConfigRepresentation config = new AuthenticatorConfigRepresentation(); config.setAlias(KeycloakModelUtils.generateId()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/registration/AttestationConveyanceRegisterTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/registration/AttestationConveyanceRegisterTest.java index c9cf2012cde9..2fd33c7af2cd 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/registration/AttestationConveyanceRegisterTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/registration/AttestationConveyanceRegisterTest.java @@ -41,7 +41,7 @@ import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Martin Bartos diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/AbstractX509AuthenticationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/AbstractX509AuthenticationTest.java index 508bf21a614f..666a5732bd28 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/AbstractX509AuthenticationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/AbstractX509AuthenticationTest.java @@ -74,11 +74,11 @@ import org.jboss.arquillian.graphene.page.Page; import org.jboss.logging.Logger; import org.junit.AfterClass; -import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebDriver; import static org.keycloak.authentication.authenticators.x509.X509AuthenticatorConfigModel.IdentityMapperType.USERNAME_EMAIL; @@ -245,29 +245,29 @@ private void configureFlows() { this.realmId = adminClient.realm(REALM_NAME).toRepresentation().getId(); AuthenticationFlowRepresentation browserFlow = copyBrowserFlow(); - Assert.assertNotNull(browserFlow); + Assertions.assertNotNull(browserFlow); AuthenticationFlowRepresentation directGrantFlow = createDirectGrantFlow(); - Assert.assertNotNull(directGrantFlow); + Assertions.assertNotNull(directGrantFlow); setBrowserFlow(browserFlow); - Assert.assertEquals(testRealm().toRepresentation().getBrowserFlow(), browserFlow.getAlias()); + Assertions.assertEquals(testRealm().toRepresentation().getBrowserFlow(), browserFlow.getAlias()); setDirectGrantFlow(directGrantFlow); - Assert.assertEquals(testRealm().toRepresentation().getDirectGrantFlow(), directGrantFlow.getAlias()); - Assert.assertEquals(0, directGrantFlow.getAuthenticationExecutions().size()); + Assertions.assertEquals(testRealm().toRepresentation().getDirectGrantFlow(), directGrantFlow.getAlias()); + Assertions.assertEquals(0, directGrantFlow.getAuthenticationExecutions().size()); // Add X509 cert authenticator to the direct grant flow directGrantExecution = addAssertExecution(directGrantFlow, ValidateX509CertificateUsernameFactory.PROVIDER_ID, REQUIRED); - Assert.assertNotNull(directGrantExecution); + Assertions.assertNotNull(directGrantExecution); directGrantFlow = authMgmtResource.getFlow(directGrantFlow.getId()); - Assert.assertNotNull(directGrantFlow.getAuthenticationExecutions()); - Assert.assertEquals(1, directGrantFlow.getAuthenticationExecutions().size()); + Assertions.assertNotNull(directGrantFlow.getAuthenticationExecutions()); + Assertions.assertEquals(1, directGrantFlow.getAuthenticationExecutions().size()); // Add X509 authenticator to the browser flow browserExecution = addAssertExecution(browserFlow, X509ClientCertificateAuthenticatorFactory.PROVIDER_ID, ALTERNATIVE); - Assert.assertNotNull(browserExecution); + Assertions.assertNotNull(browserExecution); // Raise the priority of the authenticator to position it right before // the Username/password authentication @@ -297,7 +297,7 @@ private AuthenticationExecutionInfoRepresentation addAssertExecution(Authenticat // TODO the following statement asserts, the actual value is null? //assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AssertAdminEvents.isExpectedPrefixFollowedByUuid(AdminEventPaths.authMgmtBasePath() + "/executions"), rep); try { - Assert.assertEquals("added execution", 201, response.getStatus()); + Assertions.assertEquals(201, response.getStatus(), "added execution"); } finally { response.close(); } @@ -355,7 +355,7 @@ public void importTestRealms() { AuthenticationFlowRepresentation createFlow(AuthenticationFlowRepresentation flowRep) { Response response = authMgmtResource.createFlow(flowRep); try { - org.keycloak.testsuite.Assert.assertEquals(201, response.getStatus()); + Assertions.assertEquals(201, response.getStatus()); } finally { response.close(); @@ -377,7 +377,7 @@ AuthenticationFlowRepresentation copyFlow(String existingFlow, String newFlow) { Response response = authMgmtResource.copy(existingFlow, params); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, Encode.decode(AdminEventPaths.authCopyFlowPath(existingFlow)), params, ResourceType.AUTH_FLOW); try { - Assert.assertEquals("Copy flow", 201, response.getStatus()); + Assertions.assertEquals(201, response.getStatus(), "Copy flow"); } finally { response.close(); } @@ -433,7 +433,7 @@ static AuthenticatorConfigRepresentation newConfig(String alias, MapPeter Nalyvayko @@ -80,7 +80,7 @@ public void loginWithNonMatchingRegex() throws Exception { AuthenticatorConfigRepresentation cfg = newConfig("x509-browser-config", config.getConfig()); String cfgId = createConfig(browserExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.openLoginForm(); @@ -99,7 +99,7 @@ public void loginWithNonSupportedCertKeyUsage() throws Exception { AuthenticatorConfigRepresentation cfg = newConfig("x509-browser-config", createLoginSubjectEmailWithKeyUsage("dataEncipherment").getConfig()); String cfgId = createConfig(browserExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.openLoginForm(); @@ -125,13 +125,13 @@ public void loginWithRevalidateCertEnabledCertWithIncorrectTruststoreConfig() th AuthenticatorConfigRepresentation cfg = newConfig("x509-browser-config", createLoginSubjectEmailWithRevalidateCert(true).getConfig()); String cfgId = createConfig(browserExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.openLoginForm(); loginPage.assertCurrent(); // Verify there is an error message - Assert.assertNotNull(loginPage.getError()); + Assertions.assertNotNull(loginPage.getError()); assertThat(loginPage.getError(), containsString("Certificate validation's failed.")); } finally { @@ -144,18 +144,18 @@ public void loginIgnoreX509IdentityContinueToFormLogin() throws Exception { // Set the X509 authenticator configuration AuthenticatorConfigRepresentation cfg = newConfig("x509-browser-config", createLoginSubjectEmail2UsernameOrEmailConfig().getConfig()); String cfgId = createConfig(browserExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.openLoginForm(); - Assert.assertTrue(loginConfirmationPage.getSubjectDistinguishedNameText().startsWith("EMAILADDRESS=test-user@localhost")); - Assert.assertEquals("test-user@localhost", loginConfirmationPage.getUsernameText()); + Assertions.assertTrue(loginConfirmationPage.getSubjectDistinguishedNameText().startsWith("EMAILADDRESS=test-user@localhost")); + Assertions.assertEquals("test-user@localhost", loginConfirmationPage.getUsernameText()); loginConfirmationPage.ignore(); loginPage.login("test-user@localhost", "password"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); events.expectLogin() .user(userId) @@ -173,7 +173,7 @@ public void loginAsUserFromCertSubjectCN() { @Test public void loginAsUserFromCertSerialnumberAndIssuerDNMappedToUserAttribute() { UserRepresentation user = testRealm().users().get(userId2).toRepresentation(); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); user.singleAttribute("x509_certificate_serialnumber", "4105"); user.singleAttribute("x509_issuer_dn", "EMAILADDRESS=contact@keycloak.org, CN=Keycloak Intermediate CA, OU=Keycloak, O=Red Hat, ST=MA, C=US"); @@ -188,7 +188,7 @@ public void loginAsUserFromCertSerialnumberAndIssuerDNMappedToUserAttribute() { @Test public void loginAsUserFromHexCertSerialnumberAndIssuerDNMappedToUserAttribute() { UserRepresentation user = testRealm().users().get(userId2).toRepresentation(); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); user.singleAttribute("x509_certificate_serialnumber", "1009"); user.singleAttribute("x509_issuer_dn", "EMAILADDRESS=contact@keycloak.org, CN=Keycloak Intermediate CA, OU=Keycloak, O=Red Hat, ST=MA, C=US"); @@ -205,7 +205,7 @@ public void loginAsUserFromHexCertSerialnumberAndIssuerDNMappedToUserAttribute() public void loginAsUserFromCertIssuerDNMappedToUserAttribute() { UserRepresentation user = testRealm().users().get(userId2).toRepresentation(); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); user.singleAttribute("x509_certificate_identity", "Red Hat"); this.updateUser(user); @@ -220,7 +220,7 @@ public void loginAsUserFromCertIssuerDNMappedToUserAttribute() { public void loginAsUserFromCertSHA256MappedToUserAttribute() { UserRepresentation user = testRealm().users().get(userId2).toRepresentation(); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); user.singleAttribute("x509_cert_sha256thumbprint", "71237a14c118a90cc8406f14d039ed3431c9065f68e535293ee919d4c33b5e15"); this.updateUser(user); @@ -236,7 +236,7 @@ public void loginAsUserFromCertSHA256MappedToUserAttribute() { public void loginAsUserFromCertSerialNumberMappedToUserAttribute() { UserRepresentation user = testRealm().users().get(userId2).toRepresentation(); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); user.singleAttribute("x509_serial_number", "4105"); this.updateUser(user); @@ -251,7 +251,7 @@ public void loginAsUserFromCertSerialNumberMappedToUserAttribute() { public void loginAsUserFromHexCertSerialNumberMappedToUserAttribute() { UserRepresentation user = testRealm().users().get(userId2).toRepresentation(); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); user.singleAttribute("x509_serial_number", "1009"); this.updateUser(user); @@ -269,19 +269,19 @@ public void loginDuplicateUsersNotAllowed() { AuthenticatorConfigRepresentation cfg = newConfig("x509-browser-config", createLoginIssuerDN_OU2CustomAttributeConfig().getConfig()); String cfgId = createConfig(browserExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); // Set up the users so that the identity extracted from X509 client cert // matches more than a single user to trigger DuplicateModelException. UserRepresentation user = testRealm().users().get(userId2).toRepresentation(); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); user.singleAttribute("x509_certificate_identity", "Red Hat"); this.updateUser(user); user = testRealm().users().get(userId).toRepresentation(); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); user.singleAttribute("x509_certificate_identity", "Red Hat"); this.updateUser(user); @@ -294,8 +294,8 @@ public void loginDuplicateUsersNotAllowed() { loginPage.login("test-user@localhost", "password"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); events.expectLogin() .user(userId) @@ -314,8 +314,8 @@ public void loginAttemptedNoConfig() { // Continue with form based login loginPage.login("test-user@localhost", "password"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); events.expectLogin() .user(userId) .detail(Details.USERNAME, "test-user@localhost") @@ -334,13 +334,13 @@ public void loginWithX509CertCustomAttributeUserNotFound() { .setUserIdentityMapperType(USER_ATTRIBUTE); AuthenticatorConfigRepresentation cfg = newConfig("x509-browser-config", config.getConfig()); String cfgId = createConfig(browserExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.openLoginForm(); loginPage.assertCurrent(); // Verify there is an error message - Assert.assertNotNull(loginPage.getError()); + Assertions.assertNotNull(loginPage.getError()); assertThat(loginPage.getError(), containsString("X509 certificate authentication's failed.")); events.expectLogin() @@ -355,8 +355,8 @@ public void loginWithX509CertCustomAttributeUserNotFound() { // Continue with form based login loginPage.login("test-user@localhost", "password"); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); events.expectLogin() .user(userId) .detail(Details.USERNAME, "test-user@localhost") @@ -375,12 +375,12 @@ public void loginWithX509CertCustomAttributeSuccess() { .setUserIdentityMapperType(USER_ATTRIBUTE); AuthenticatorConfigRepresentation cfg = newConfig("x509-browser-config", config.getConfig()); String cfgId = createConfig(browserExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); // Update the attribute used to match the user identity to that // extracted from the client certificate UserRepresentation user = findUser("test-user@localhost"); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); user.singleAttribute("x509_certificate_identity", "Red Hat"); this.updateUser(user); @@ -388,24 +388,24 @@ public void loginWithX509CertCustomAttributeSuccess() { oauth.openLoginForm(); - Assert.assertTrue(loginConfirmationPage.getSubjectDistinguishedNameText().startsWith("EMAILADDRESS=test-user@localhost")); - Assert.assertEquals("test-user@localhost", loginConfirmationPage.getUsernameText()); + Assertions.assertTrue(loginConfirmationPage.getSubjectDistinguishedNameText().startsWith("EMAILADDRESS=test-user@localhost")); + Assertions.assertEquals("test-user@localhost", loginConfirmationPage.getUsernameText()); loginConfirmationPage.confirm(); - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); } @Test public void loginWithX509CertBadUserOrNotFound() { AuthenticatorConfigRepresentation cfg = newConfig("x509-browser-config", createLoginSubjectEmail2UsernameOrEmailConfig().getConfig()); String cfgId = createConfig(browserExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); // Delete user UserRepresentation user = findUser("test-user@localhost"); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); Response response = testRealm().users().delete(userId); assertEquals(204, response.getStatus()); @@ -417,7 +417,7 @@ public void loginWithX509CertBadUserOrNotFound() { loginPage.assertCurrent(); // Verify there is an error message - Assert.assertNotNull(loginPage.getError()); + Assertions.assertNotNull(loginPage.getError()); assertThat(loginPage.getError(), containsString("X509 certificate authentication's failed.")); @@ -436,10 +436,10 @@ public void loginWithX509CertBadUserOrNotFound() { loginPage.login("test-user@localhost", "password"); loginPage.assertCurrent(); - Assert.assertEquals("test-user@localhost", loginPage.getUsername()); - Assert.assertEquals("", loginPage.getPassword()); + Assertions.assertEquals("test-user@localhost", loginPage.getUsername()); + Assertions.assertEquals("", loginPage.getPassword()); - Assert.assertEquals("Invalid username or password.", loginPage.getInputError()); + Assertions.assertEquals("Invalid username or password.", loginPage.getInputError()); } @Test @@ -449,12 +449,12 @@ public void loginValidCertificateDisabledUser() { try { AuthenticatorConfigRepresentation cfg = newConfig("x509-browser-config", createLoginSubjectEmail2UsernameOrEmailConfig().getConfig()); String cfgId = createConfig(browserExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.openLoginForm(); loginPage.assertCurrent(); - Assert.assertNotNull(loginPage.getError()); + Assertions.assertNotNull(loginPage.getError()); assertThat(loginPage.getError(), containsString("X509 certificate authentication's failed. User is disabled")); @@ -471,11 +471,11 @@ public void loginValidCertificateDisabledUser() { loginPage.assertCurrent(); // KEYCLOAK-1741 - assert form field values kept - Assert.assertEquals("test-user@localhost", loginPage.getUsername()); - Assert.assertEquals("", loginPage.getPassword()); + Assertions.assertEquals("test-user@localhost", loginPage.getUsername()); + Assertions.assertEquals("", loginPage.getPassword()); // KEYCLOAK-2024 - Assert.assertEquals("Account is disabled, contact your administrator.", loginPage.getError()); + Assertions.assertEquals("Account is disabled, contact your administrator.", loginPage.getError()); events.expectLogin() .user(userId) @@ -500,14 +500,14 @@ public void loginNoIdentityConfirmationPage() { .setUserIdentityMapperType(USERNAME_EMAIL); AuthenticatorConfigRepresentation cfg = newConfig("x509-browser-config", config.getConfig()); String cfgId = createConfig(browserExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.openLoginForm(); // X509 authenticator extracts the user identity, maps it to an existing // user and automatically logs the user in without prompting to confirm // the identity. - Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); - Assert.assertNotNull(oauth.parseLoginResponse().getCode()); + Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType()); + Assertions.assertNotNull(oauth.parseLoginResponse().getCode()); AssertEvents.ExpectedEvent expectedEvent = events.expectLogin() .user(userId) @@ -538,7 +538,7 @@ public void loginWithCertificateAddedLater() throws Exception { public void changeLocaleOnX509InfoPage() { AuthenticatorConfigRepresentation cfg = newConfig("x509-browser-config", createLoginSubjectEmail2UsernameOrEmailConfig().getConfig()); String cfgId = createConfig(browserExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); log.debug("Open confirm page"); oauth.openLoginForm(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/X509DirectGrantTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/X509DirectGrantTest.java index 8b8d58b6b2f3..a2e017cfb12b 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/X509DirectGrantTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/X509DirectGrantTest.java @@ -34,10 +34,10 @@ import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.jboss.arquillian.drone.api.annotation.Drone; -import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebDriver; import static org.keycloak.authentication.authenticators.x509.X509AuthenticatorConfigModel.IdentityMapperType.USERNAME_EMAIL; @@ -47,7 +47,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Peter Nalyvayko @@ -71,19 +71,19 @@ public void loginFailedOnDuplicateUsers() throws Exception { AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", createLoginIssuerDN_OU2CustomAttributeConfig().getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); // Set up the users so that the identity extracted from X509 client cert // matches more than a single user to trigger DuplicateModelException. UserRepresentation user = testRealm().users().get(userId2).toRepresentation(); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); user.singleAttribute("x509_certificate_identity", "Red Hat"); this.updateUser(user); user = testRealm().users().get(userId).toRepresentation(); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); user.singleAttribute("x509_certificate_identity", "Red Hat"); this.updateUser(user); @@ -103,10 +103,10 @@ public void loginFailedOnInvalidUser() throws Exception { AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", createLoginIssuerDN_OU2CustomAttributeConfig().getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); UserRepresentation user = testRealm().users().get(userId2).toRepresentation(); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); user.singleAttribute("x509_certificate_identity", "-"); this.updateUser(user); @@ -138,7 +138,7 @@ public void loginWithNonSupportedCertKeyUsage() throws Exception { AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", createLoginSubjectEmailWithKeyUsage("dataEncipherment").getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.client("resource-owner", "secret"); AccessTokenResponse response = oauth.doPasswordGrantRequest("", ""); @@ -155,7 +155,7 @@ public void loginWithNonSupportedCertExtendedKeyUsage() throws Exception { AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", createLoginSubjectEmailWithExtendedKeyUsage("serverAuth").getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.client("resource-owner", "secret"); AccessTokenResponse response = oauth.doPasswordGrantRequest("", ""); @@ -170,7 +170,7 @@ public void loginWithNonMatchingRegex() throws Exception { AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.client("resource-owner", "secret"); AccessTokenResponse response = oauth.doPasswordGrantRequest("", ""); @@ -197,7 +197,7 @@ public void loginFailedDisabledUser() throws Exception { try { AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", createLoginSubjectEmail2UsernameOrEmailConfig().getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.client("resource-owner", "secret"); AccessTokenResponse response = oauth.doPasswordGrantRequest("", ""); @@ -236,7 +236,7 @@ public void loginCertificateRevoked() throws Exception { .setUserIdentityMapperType(USERNAME_EMAIL); AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.client("resource-owner", "secret"); AccessTokenResponse response = oauth.doPasswordGrantRequest("", ""); @@ -257,7 +257,7 @@ public void loginCertificateNotExpired() throws Exception { .setUserIdentityMapperType(USERNAME_EMAIL); AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.client("resource-owner", "secret"); AccessTokenResponse response = oauth.doPasswordGrantRequest("", ""); @@ -275,7 +275,7 @@ public void loginCertificateExpired() throws Exception { .setUserIdentityMapperType(USERNAME_EMAIL); AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); setTimeOffset(50 * 365 * 24 * 60 * 60); @@ -298,10 +298,10 @@ private void loginForceTemporaryAccountLock() throws Exception { AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); UserRepresentation user = testRealm().users().get(userId).toRepresentation(); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); user.singleAttribute("x509_certificate_identity", "-"); this.updateUser(user); @@ -325,7 +325,7 @@ public void loginFailedTemporarilyDisabledUser() throws Exception { AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", createLoginSubjectEmail2UsernameOrEmailConfig().getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.client("resource-owner", "secret"); AccessTokenResponse response = oauth.doPasswordGrantRequest("", ""); @@ -380,7 +380,7 @@ public void loginResourceOwnerCredentialsSuccess() throws Exception { .setUserIdentityMapperType(USERNAME_EMAIL); AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); doResourceOwnerCredentialsLogin("resource-owner", "secret", "test-user@localhost", ""); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/X509OCSPResponderFailOpenTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/X509OCSPResponderFailOpenTest.java index 45e17d3db6fa..8835ea60d60f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/X509OCSPResponderFailOpenTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/X509OCSPResponderFailOpenTest.java @@ -15,9 +15,9 @@ import org.apache.commons.io.IOUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.jboss.arquillian.drone.api.annotation.Drone; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebDriver; import static org.keycloak.authentication.authenticators.x509.X509AuthenticatorConfigModel.IdentityMapperType.USERNAME_EMAIL; @@ -25,7 +25,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class X509OCSPResponderFailOpenTest extends AbstractX509AuthenticationTest { @@ -57,7 +57,7 @@ public void ocspFailCloseLoginFailed() throws Exception { .setUserIdentityMapperType(USERNAME_EMAIL); AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.client("resource-owner", "secret"); AccessTokenResponse response = oauth.doPasswordGrantRequest("", ""); @@ -87,7 +87,7 @@ public void ocspFailOpenLoginSuccess() throws Exception { .setUserIdentityMapperType(USERNAME_EMAIL); AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); String keyStorePath = Paths.get(System.getProperty("client.certificate.keystore")) .getParent().resolve("client-ca.jks").toString(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/X509OCSPResponderSpecificCertTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/X509OCSPResponderSpecificCertTest.java index cad86330be72..ecd5cd87e27f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/X509OCSPResponderSpecificCertTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/X509OCSPResponderSpecificCertTest.java @@ -29,9 +29,9 @@ import io.undertow.server.handlers.BlockingHandler; import org.jboss.arquillian.drone.api.annotation.Drone; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebDriver; import static org.keycloak.authentication.authenticators.x509.X509AuthenticatorConfigModel.IdentityMapperType.USERNAME_EMAIL; @@ -39,7 +39,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Verifies Certificate revocation using OCSP responder but specifying specific @@ -75,7 +75,7 @@ public void loginFailedInvalidResponderOnOCSPResponderRevocationCheck() throws E .setUserIdentityMapperType(USERNAME_EMAIL); AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.client("resource-owner", "secret"); AccessTokenResponse response = oauth.doPasswordGrantRequest("", ""); @@ -114,7 +114,7 @@ public void loginFailedOnOCSPResponderRevocationCheck() throws Exception { .setUserIdentityMapperType(USERNAME_EMAIL); AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.client("resource-owner", "secret"); AccessTokenResponse response = oauth.doPasswordGrantRequest("", ""); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/X509OCSPResponderTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/X509OCSPResponderTest.java index 695f01fd16a3..c5540e68cabb 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/X509OCSPResponderTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/x509/X509OCSPResponderTest.java @@ -36,9 +36,9 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.jboss.arquillian.drone.api.annotation.Drone; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebDriver; import static org.keycloak.authentication.authenticators.x509.X509AuthenticatorConfigModel.IdentityMapperType.USERNAME_EMAIL; @@ -46,7 +46,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Verifies Certificate revocation using OCSP responder. @@ -83,7 +83,7 @@ public void loginFailedOnOCSPResponderRevocationCheck() throws Exception { .setUserIdentityMapperType(USERNAME_EMAIL); AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); oauth.client("resource-owner", "secret"); AccessTokenResponse response = oauth.doPasswordGrantRequest("", ""); @@ -104,7 +104,7 @@ public void loginFailedOnOCSPResponderRevocationCheckWithoutCA() throws Exceptio .setUserIdentityMapperType(USERNAME_EMAIL); AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); String keyStorePath = Paths.get(System.getProperty("client.certificate.keystore")) .getParent().resolve("client-ca.jks").toString(); @@ -136,7 +136,7 @@ public void loginClientCertSignedByIntermediateCA() throws Exception { .setUserIdentityMapperType(USERNAME_EMAIL); AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); String keyStorePath = Paths.get(System.getProperty("client.certificate.keystore")) .getParent().resolve("test-user-cert-intermediary-ca.jks").toString(); @@ -169,7 +169,7 @@ public void loginOKOnOCSPResponderRevocationCheckWithoutCA() throws Exception { .setUserIdentityMapperType(USERNAME_EMAIL); AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig()); String cfgId = createConfig(directGrantExecution.getId(), cfg); - Assert.assertNotNull(cfgId); + Assertions.assertNotNull(cfgId); String keyStorePath = Paths.get(System.getProperty("client.certificate.keystore")) .getParent().resolve("client-ca.jks").toString();