diff --git a/acl/src/test/java/org/springframework/security/acls/AclFormattingUtilsTests.java b/acl/src/test/java/org/springframework/security/acls/AclFormattingUtilsTests.java index 9986cfcbc6..57828a390e 100644 --- a/acl/src/test/java/org/springframework/security/acls/AclFormattingUtilsTests.java +++ b/acl/src/test/java/org/springframework/security/acls/AclFormattingUtilsTests.java @@ -1,22 +1,23 @@ + package org.springframework.security.acls; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import org.junit.Test; import org.springframework.security.acls.domain.AclFormattingUtils; import org.springframework.security.acls.model.Permission; -import junit.framework.TestCase; - /** * Tests for {@link AclFormattingUtils}. * * @author Andrei Stefan */ -public class AclFormattingUtilsTests extends TestCase { +public class AclFormattingUtilsTests { // ~ Methods // ======================================================================================================== - + @Test public final void testDemergePatternsParametersConstraints() throws Exception { try { AclFormattingUtils.demergePatterns(null, "SOME STRING"); @@ -47,15 +48,20 @@ public class AclFormattingUtilsTests extends TestCase { } } + @Test public final void testDemergePatterns() throws Exception { String original = "...........................A...R"; String removeBits = "...............................R"; - assertThat(AclFormattingUtils.demergePatterns(original, removeBits)).isEqualTo("...........................A...."); + assertThat(AclFormattingUtils.demergePatterns(original, removeBits)).isEqualTo( + "...........................A...."); - assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "......")).isEqualTo("ABCDEF"); - assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL")).isEqualTo("......"); + assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "......")).isEqualTo( + "ABCDEF"); + assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL")).isEqualTo( + "......"); } + @Test public final void testMergePatternsParametersConstraints() throws Exception { try { AclFormattingUtils.mergePatterns(null, "SOME STRING"); @@ -85,22 +91,23 @@ public class AclFormattingUtilsTests extends TestCase { } } + @Test public final void testMergePatterns() throws Exception { String original = "...............................R"; String extraBits = "...........................A...."; - assertThat( - AclFormattingUtils.mergePatterns(original, extraBits)).isEqualTo("...........................A...R"); + assertThat(AclFormattingUtils.mergePatterns(original, extraBits)).isEqualTo( + "...........................A...R"); - assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "......")) - .isEqualTo("ABCDEF"); - assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL")) - .isEqualTo("GHIJKL"); + assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "......")).isEqualTo( + "ABCDEF"); + assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL")).isEqualTo( + "GHIJKL"); } + @Test public final void testBinaryPrints() throws Exception { - assertThat( - AclFormattingUtils.printBinary(15)) - .isEqualTo("............................****"); + assertThat(AclFormattingUtils.printBinary(15)).isEqualTo( + "............................****"); try { AclFormattingUtils.printBinary(15, Permission.RESERVED_ON); @@ -116,20 +123,19 @@ public class AclFormattingUtilsTests extends TestCase { catch (IllegalArgumentException notExpected) { } - assertThat( - AclFormattingUtils.printBinary(15, 'x')) - .isEqualTo("............................xxxx"); + assertThat(AclFormattingUtils.printBinary(15, 'x')).isEqualTo( + "............................xxxx"); } + @Test public void testPrintBinaryNegative() { - assertThat( - AclFormattingUtils.printBinary(0x80000000)) - .isEqualTo("*..............................."); + assertThat(AclFormattingUtils.printBinary(0x80000000)).isEqualTo( + "*..............................."); } + @Test public void testPrintBinaryMinusOne() { - assertThat( - AclFormattingUtils.printBinary(0xffffffff)) - .isEqualTo("********************************"); + assertThat(AclFormattingUtils.printBinary(0xffffffff)).isEqualTo( + "********************************"); } } diff --git a/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityRetrievalStrategyImplTests.java b/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityRetrievalStrategyImplTests.java index 4cfe53bca6..35ef26150e 100644 --- a/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityRetrievalStrategyImplTests.java +++ b/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityRetrievalStrategyImplTests.java @@ -1,24 +1,22 @@ + package org.springframework.security.acls.domain; +import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.*; - -import org.springframework.security.acls.domain.ObjectIdentityImpl; -import org.springframework.security.acls.domain.ObjectIdentityRetrievalStrategyImpl; +import org.junit.Test; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.ObjectIdentityRetrievalStrategy; -import junit.framework.TestCase; - /** * Tests for {@link ObjectIdentityRetrievalStrategyImpl} * * @author Andrei Stefan */ -public class ObjectIdentityRetrievalStrategyImplTests extends TestCase { +public class ObjectIdentityRetrievalStrategyImplTests { + // ~ Methods // ======================================================================================================== - + @Test public void testObjectIdentityCreation() throws Exception { MockIdDomainObject domain = new MockIdDomainObject(); domain.setId(Integer.valueOf(1)); @@ -34,6 +32,7 @@ public class ObjectIdentityRetrievalStrategyImplTests extends TestCase { // ================================================================================================== @SuppressWarnings("unused") private class MockIdDomainObject { + private Object id; public Object getId() { diff --git a/acl/src/test/java/org/springframework/security/acls/sid/SidTests.java b/acl/src/test/java/org/springframework/security/acls/sid/SidTests.java index 22f3b2a031..14a1e7670c 100644 --- a/acl/src/test/java/org/springframework/security/acls/sid/SidTests.java +++ b/acl/src/test/java/org/springframework/security/acls/sid/SidTests.java @@ -1,8 +1,10 @@ + package org.springframework.security.acls.sid; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.security.acls.domain.GrantedAuthoritySid; import org.springframework.security.acls.domain.PrincipalSid; import org.springframework.security.acls.model.Sid; @@ -11,11 +13,11 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; -public class SidTests extends TestCase { +public class SidTests { // ~ Methods // ======================================================================================================== - + @Test public void testPrincipalSidConstructorsRequiredFields() throws Exception { // Check one String-argument constructor try { @@ -60,6 +62,7 @@ public class SidTests extends TestCase { // throws no exception } + @Test public void testGrantedAuthoritySidConstructorsRequiredFields() throws Exception { // Check one String-argument constructor try { @@ -116,6 +119,7 @@ public class SidTests extends TestCase { } } + @Test public void testPrincipalSidEquals() throws Exception { Authentication authentication = new TestingAuthenticationToken("johndoe", "password"); @@ -125,14 +129,15 @@ public class SidTests extends TestCase { assertThat(principalSid.equals("DIFFERENT_TYPE_OBJECT")).isFalse(); assertThat(principalSid.equals(principalSid)).isTrue(); assertThat(principalSid.equals(new PrincipalSid(authentication))).isTrue(); - assertTrue(principalSid.equals(new PrincipalSid( - new TestingAuthenticationToken("johndoe", null)))); - assertFalse(principalSid.equals(new PrincipalSid( - new TestingAuthenticationToken("scott", null)))); + assertThat(principalSid.equals(new PrincipalSid( + new TestingAuthenticationToken("johndoe", null)))).isTrue(); + assertThat(principalSid.equals(new PrincipalSid( + new TestingAuthenticationToken("scott", null)))).isFalse(); assertThat(principalSid.equals(new PrincipalSid("johndoe"))).isTrue(); assertThat(principalSid.equals(new PrincipalSid("scott"))).isFalse(); } + @Test public void testGrantedAuthoritySidEquals() throws Exception { GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST"); Sid gaSid = new GrantedAuthoritySid(ga); @@ -141,39 +146,44 @@ public class SidTests extends TestCase { assertThat(gaSid.equals("DIFFERENT_TYPE_OBJECT")).isFalse(); assertThat(gaSid.equals(gaSid)).isTrue(); assertThat(gaSid.equals(new GrantedAuthoritySid(ga))).isTrue(); - assertTrue(gaSid.equals(new GrantedAuthoritySid( - new SimpleGrantedAuthority("ROLE_TEST")))); - assertFalse(gaSid.equals(new GrantedAuthoritySid( - new SimpleGrantedAuthority("ROLE_NOT_EQUAL")))); + assertThat(gaSid.equals(new GrantedAuthoritySid( + new SimpleGrantedAuthority("ROLE_TEST")))).isTrue(); + assertThat(gaSid.equals(new GrantedAuthoritySid( + new SimpleGrantedAuthority("ROLE_NOT_EQUAL")))).isFalse(); assertThat(gaSid.equals(new GrantedAuthoritySid("ROLE_TEST"))).isTrue(); assertThat(gaSid.equals(new GrantedAuthoritySid("ROLE_NOT_EQUAL"))).isFalse(); } + @Test public void testPrincipalSidHashCode() throws Exception { Authentication authentication = new TestingAuthenticationToken("johndoe", "password"); Sid principalSid = new PrincipalSid(authentication); - assertThat(principalSid.hashCode()).isSameAs("johndoe".hashCode()); - assertThat(principalSid.hashCode()).isSameAs(new PrincipalSid("johndoe").hashCode()); - assertThat(principalSid.hashCode()).isNotEqualTo(new PrincipalSid("scott").hashCode()); + assertThat(principalSid.hashCode()).isEqualTo("johndoe".hashCode()); + assertThat(principalSid.hashCode()).isEqualTo( + new PrincipalSid("johndoe").hashCode()); + assertThat(principalSid.hashCode()).isNotEqualTo( + new PrincipalSid("scott").hashCode()); assertThat(principalSid.hashCode()).isNotEqualTo(new PrincipalSid( new TestingAuthenticationToken("scott", "password")).hashCode()); } + @Test public void testGrantedAuthoritySidHashCode() throws Exception { GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST"); Sid gaSid = new GrantedAuthoritySid(ga); assertThat(gaSid.hashCode()).isEqualTo("ROLE_TEST".hashCode()); - assertThat(gaSid.hashCode()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST") - .hashCode()); - assertThat(gaSid.hashCode()).isNotEqualTo(new GrantedAuthoritySid("ROLE_TEST_2") - .hashCode()); + assertThat(gaSid.hashCode()).isEqualTo( + new GrantedAuthoritySid("ROLE_TEST").hashCode()); + assertThat(gaSid.hashCode()).isNotEqualTo( + new GrantedAuthoritySid("ROLE_TEST_2").hashCode()); assertThat(gaSid.hashCode()).isNotEqualTo(new GrantedAuthoritySid( new SimpleGrantedAuthority("ROLE_TEST_2")).hashCode()); } + @Test public void testGetters() throws Exception { Authentication authentication = new TestingAuthenticationToken("johndoe", "password"); diff --git a/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationTokenTests.java b/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationTokenTests.java index 30953aa622..b34c4ea5ff 100644 --- a/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationTokenTests.java +++ b/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationTokenTests.java @@ -15,11 +15,14 @@ package org.springframework.security.cas.authentication; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +import java.util.List; -import junit.framework.TestCase; import org.jasig.cas.client.validation.Assertion; import org.jasig.cas.client.validation.AssertionImpl; +import org.junit.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; @@ -27,14 +30,13 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; -import java.util.*; - /** * Tests {@link CasAuthenticationToken}. * * @author Ben Alex */ -public class CasAuthenticationTokenTests extends TestCase { +public class CasAuthenticationTokenTests { + private final List ROLES = AuthorityUtils.createAuthorityList( "ROLE_ONE", "ROLE_TWO"); @@ -46,10 +48,7 @@ public class CasAuthenticationTokenTests extends TestCase { return new User(name, "password", true, true, true, true, ROLES); } - public final void setUp() throws Exception { - super.setUp(); - } - + @Test public void testConstructorRejectsNulls() { final Assertion assertion = new AssertionImpl("test"); try { @@ -94,14 +93,15 @@ public class CasAuthenticationTokenTests extends TestCase { try { new CasAuthenticationToken("key", makeUserDetails(), "Password", - AuthorityUtils.createAuthorityList("ROLE_1", null), - makeUserDetails(), assertion); + AuthorityUtils.createAuthorityList("ROLE_1", null), makeUserDetails(), + assertion); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } + @Test public void testEqualsWhenEqual() { final Assertion assertion = new AssertionImpl("test"); @@ -114,6 +114,7 @@ public class CasAuthenticationTokenTests extends TestCase { assertThat(token2).isEqualTo(token1); } + @Test public void testGetters() { // Build the proxy list returned in the ticket from CAS final Assertion assertion = new AssertionImpl("test"); @@ -122,14 +123,16 @@ public class CasAuthenticationTokenTests extends TestCase { assertThat(token.getKeyHash()).isEqualTo("key".hashCode()); assertThat(token.getPrincipal()).isEqualTo(makeUserDetails()); assertThat(token.getCredentials()).isEqualTo("Password"); - assertThat(token.getAuthorities()) - .contains(new SimpleGrantedAuthority("ROLE_ONE")); - assertThat(token.getAuthorities()) - .contains(new SimpleGrantedAuthority("ROLE_TWO")); + assertThat(token.getAuthorities()).contains( + new SimpleGrantedAuthority("ROLE_ONE")); + assertThat(token.getAuthorities()).contains( + new SimpleGrantedAuthority("ROLE_TWO")); assertThat(token.getAssertion()).isEqualTo(assertion); - assertThat(token.getUserDetails().getUsername()).isEqualTo(makeUserDetails().getUsername()); + assertThat(token.getUserDetails().getUsername()).isEqualTo( + makeUserDetails().getUsername()); } + @Test public void testNoArgConstructorDoesntExist() { try { CasAuthenticationToken.class.getDeclaredConstructor((Class[]) null); @@ -140,6 +143,7 @@ public class CasAuthenticationTokenTests extends TestCase { } } + @Test public void testNotEqualsDueToAbstractParentEqualsCheck() { final Assertion assertion = new AssertionImpl("test"); @@ -153,6 +157,7 @@ public class CasAuthenticationTokenTests extends TestCase { assertThat(!token1.equals(token2)).isTrue(); } + @Test public void testNotEqualsDueToDifferentAuthenticationClass() { final Assertion assertion = new AssertionImpl("test"); @@ -164,6 +169,7 @@ public class CasAuthenticationTokenTests extends TestCase { assertThat(!token1.equals(token2)).isTrue(); } + @Test public void testNotEqualsDueToKey() { final Assertion assertion = new AssertionImpl("test"); @@ -176,6 +182,7 @@ public class CasAuthenticationTokenTests extends TestCase { assertThat(!token1.equals(token2)).isTrue(); } + @Test public void testNotEqualsDueToAssertion() { final Assertion assertion = new AssertionImpl("test"); final Assertion assertion2 = new AssertionImpl("test"); @@ -189,6 +196,7 @@ public class CasAuthenticationTokenTests extends TestCase { assertThat(!token1.equals(token2)).isTrue(); } + @Test public void testSetAuthenticated() { final Assertion assertion = new AssertionImpl("test"); CasAuthenticationToken token = new CasAuthenticationToken("key", @@ -198,11 +206,13 @@ public class CasAuthenticationTokenTests extends TestCase { assertThat(!token.isAuthenticated()).isTrue(); } + @Test public void testToString() { final Assertion assertion = new AssertionImpl("test"); CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion); String result = token.toString(); - assertThat(result.lastIndexOf("Credentials (Service/Proxy Ticket):") != -1).isTrue(); + assertThat( + result.lastIndexOf("Credentials (Service/Proxy Ticket):") != -1).isTrue(); } } diff --git a/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationEntryPointTests.java b/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationEntryPointTests.java index f08bb0a732..539ad62492 100644 --- a/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationEntryPointTests.java +++ b/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationEntryPointTests.java @@ -15,26 +15,26 @@ package org.springframework.security.cas.web; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; -import junit.framework.TestCase; +import java.net.URLEncoder; +import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.cas.ServiceProperties; -import org.springframework.security.cas.web.CasAuthenticationEntryPoint; - -import java.net.URLEncoder; /** * Tests {@link CasAuthenticationEntryPoint}. * * @author Ben Alex */ -public class CasAuthenticationEntryPointTests extends TestCase { +public class CasAuthenticationEntryPointTests { + // ~ Methods // ======================================================================================================== - + @Test public void testDetectsMissingLoginFormUrl() throws Exception { CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); ep.setServiceProperties(new ServiceProperties()); @@ -48,6 +48,7 @@ public class CasAuthenticationEntryPointTests extends TestCase { } } + @Test public void testDetectsMissingServiceProperties() throws Exception { CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); ep.setLoginUrl("https://cas/login"); @@ -57,10 +58,12 @@ public class CasAuthenticationEntryPointTests extends TestCase { fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("serviceProperties must be specified"); + assertThat(expected.getMessage()).isEqualTo( + "serviceProperties must be specified"); } } + @Test public void testGettersSetters() { CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); ep.setLoginUrl("https://cas/login"); @@ -70,6 +73,7 @@ public class CasAuthenticationEntryPointTests extends TestCase { assertThat(ep.getServiceProperties() != null).isTrue(); } + @Test public void testNormalOperationWithRenewFalse() throws Exception { ServiceProperties sp = new ServiceProperties(); sp.setSendRenew(false); @@ -87,12 +91,12 @@ public class CasAuthenticationEntryPointTests extends TestCase { ep.afterPropertiesSet(); ep.commence(request, response, null); - assertEquals( - "https://cas/login?service=" - + URLEncoder.encode("https://mycompany.com/bigWebApp/login/cas", - "UTF-8"), response.getRedirectedUrl()); + assertThat("https://cas/login?service=" + URLEncoder.encode( + "https://mycompany.com/bigWebApp/login/cas", "UTF-8")).isEqualTo( + response.getRedirectedUrl()); } + @Test public void testNormalOperationWithRenewTrue() throws Exception { ServiceProperties sp = new ServiceProperties(); sp.setSendRenew(true); @@ -109,9 +113,8 @@ public class CasAuthenticationEntryPointTests extends TestCase { ep.afterPropertiesSet(); ep.commence(request, response, null); - assertEquals( - "https://cas/login?service=" - + URLEncoder.encode("https://mycompany.com/bigWebApp/login/cas", - "UTF-8") + "&renew=true", response.getRedirectedUrl()); + assertThat("https://cas/login?service=" + + URLEncoder.encode("https://mycompany.com/bigWebApp/login/cas", "UTF-8") + + "&renew=true").isEqualTo(response.getRedirectedUrl()); } } diff --git a/config/src/test/java/org/springframework/security/config/http/FilterSecurityMetadataSourceBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/http/FilterSecurityMetadataSourceBeanDefinitionParserTests.java index 65eeba6f6d..982a171586 100644 --- a/config/src/test/java/org/springframework/security/config/http/FilterSecurityMetadataSourceBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/http/FilterSecurityMetadataSourceBeanDefinitionParserTests.java @@ -1,8 +1,7 @@ + package org.springframework.security.config.http; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import java.util.Collection; @@ -23,9 +22,11 @@ import org.springframework.security.web.access.intercept.DefaultFilterInvocation /** * Tests for {@link FilterInvocationSecurityMetadataSourceParser}. + * * @author Luke Taylor */ public class FilterSecurityMetadataSourceBeanDefinitionParserTests { + private AbstractXmlApplicationContext appContext; @After @@ -45,10 +46,10 @@ public class FilterSecurityMetadataSourceBeanDefinitionParserTests { setContext("" + " " + ""); - DefaultFilterInvocationSecurityMetadataSource fids = (DefaultFilterInvocationSecurityMetadataSource) appContext - .getBean("fids"); - Collection cad = fids.getAttributes(createFilterInvocation( - "/anything", "GET")); + DefaultFilterInvocationSecurityMetadataSource fids = (DefaultFilterInvocationSecurityMetadataSource) appContext.getBean( + "fids"); + Collection cad = fids.getAttributes( + createFilterInvocation("/anything", "GET")); assertThat(cad).isNotNull(); assertThat(cad.contains(new SecurityConfig("ROLE_A"))).isTrue(); } @@ -59,11 +60,11 @@ public class FilterSecurityMetadataSourceBeanDefinitionParserTests { + " " + ""); - ExpressionBasedFilterInvocationSecurityMetadataSource fids = (ExpressionBasedFilterInvocationSecurityMetadataSource) appContext - .getBean("fids"); + ExpressionBasedFilterInvocationSecurityMetadataSource fids = (ExpressionBasedFilterInvocationSecurityMetadataSource) appContext.getBean( + "fids"); ConfigAttribute[] cad = fids.getAttributes( createFilterInvocation("/anything", "GET")).toArray( - new ConfigAttribute[0]); + new ConfigAttribute[0]); assertThat(cad.length).isEqualTo(1); assertThat(cad[0].toString()).isEqualTo("hasRole('ROLE_A')"); } @@ -73,14 +74,15 @@ public class FilterSecurityMetadataSourceBeanDefinitionParserTests { public void interceptUrlsSupportPropertyPlaceholders() { System.setProperty("secure.url", "/secure"); System.setProperty("secure.role", "ROLE_A"); - setContext("" - + "" - + " " - + ""); - DefaultFilterInvocationSecurityMetadataSource fids = (DefaultFilterInvocationSecurityMetadataSource) appContext - .getBean("fids"); - Collection cad = fids.getAttributes(createFilterInvocation( - "/secure", "GET")); + setContext( + "" + + "" + + " " + + ""); + DefaultFilterInvocationSecurityMetadataSource fids = (DefaultFilterInvocationSecurityMetadataSource) appContext.getBean( + "fids"); + Collection cad = fids.getAttributes( + createFilterInvocation("/secure", "GET")); assertThat(cad).isNotNull(); assertThat(cad).hasSize(1); assertThat(cad.contains(new SecurityConfig("ROLE_A"))).isTrue(); diff --git a/core/src/main/java/org/springframework/security/provisioning/JdbcUserDetailsManager.java b/core/src/main/java/org/springframework/security/provisioning/JdbcUserDetailsManager.java index 12bfa13a00..3bbff24c91 100644 --- a/core/src/main/java/org/springframework/security/provisioning/JdbcUserDetailsManager.java +++ b/core/src/main/java/org/springframework/security/provisioning/JdbcUserDetailsManager.java @@ -1,511 +1,511 @@ -package org.springframework.security.provisioning; - -import org.springframework.security.access.AccessDeniedException; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserCache; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.cache.NullUserCache; -import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl; -import org.springframework.context.ApplicationContextException; -import org.springframework.dao.IncorrectResultSizeDataAccessException; -import org.springframework.jdbc.core.PreparedStatementSetter; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.util.Assert; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Collection; -import java.util.List; - -/** - * Jdbc user management service, based on the same table structure as its parent class, - * JdbcDaoImpl. - *

- * Provides CRUD operations for both users and groups. Note that if the - * {@link #setEnableAuthorities(boolean) enableAuthorities} property is set to false, - * calls to createUser, updateUser and deleteUser will not store the authorities from the - * UserDetails or delete authorities for the user. Since this class cannot - * differentiate between authorities which were loaded for an individual or for a group of - * which the individual is a member, it's important that you take this into account when - * using this implementation for managing your users. - * - * @author Luke Taylor - * @since 2.0 - */ -public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsManager, - GroupManager { - // ~ Static fields/initializers - // ===================================================================================== - - // UserDetailsManager SQL - public static final String DEF_CREATE_USER_SQL = "insert into users (username, password, enabled) values (?,?,?)"; - public static final String DEF_DELETE_USER_SQL = "delete from users where username = ?"; - public static final String DEF_UPDATE_USER_SQL = "update users set password = ?, enabled = ? where username = ?"; - public static final String DEF_INSERT_AUTHORITY_SQL = "insert into authorities (username, authority) values (?,?)"; - public static final String DEF_DELETE_USER_AUTHORITIES_SQL = "delete from authorities where username = ?"; - public static final String DEF_USER_EXISTS_SQL = "select username from users where username = ?"; - public static final String DEF_CHANGE_PASSWORD_SQL = "update users set password = ? where username = ?"; - - // GroupManager SQL - public static final String DEF_FIND_GROUPS_SQL = "select group_name from groups"; - public static final String DEF_FIND_USERS_IN_GROUP_SQL = "select username from group_members gm, groups g " - + "where gm.group_id = g.id" + " and g.group_name = ?"; - public static final String DEF_INSERT_GROUP_SQL = "insert into groups (group_name) values (?)"; - public static final String DEF_FIND_GROUP_ID_SQL = "select id from groups where group_name = ?"; - public static final String DEF_INSERT_GROUP_AUTHORITY_SQL = "insert into group_authorities (group_id, authority) values (?,?)"; - public static final String DEF_DELETE_GROUP_SQL = "delete from groups where id = ?"; - public static final String DEF_DELETE_GROUP_AUTHORITIES_SQL = "delete from group_authorities where group_id = ?"; - public static final String DEF_DELETE_GROUP_MEMBERS_SQL = "delete from group_members where group_id = ?"; - public static final String DEF_RENAME_GROUP_SQL = "update groups set group_name = ? where group_name = ?"; - public static final String DEF_INSERT_GROUP_MEMBER_SQL = "insert into group_members (group_id, username) values (?,?)"; - public static final String DEF_DELETE_GROUP_MEMBER_SQL = "delete from group_members where group_id = ? and username = ?"; - public static final String DEF_GROUP_AUTHORITIES_QUERY_SQL = "select g.id, g.group_name, ga.authority " - + "from groups g, group_authorities ga " - + "where g.group_name = ? " - + "and g.id = ga.group_id "; - public static final String DEF_DELETE_GROUP_AUTHORITY_SQL = "delete from group_authorities where group_id = ? and authority = ?"; - - // ~ Instance fields - // ================================================================================================ - - protected final Log logger = LogFactory.getLog(getClass()); - - private String createUserSql = DEF_CREATE_USER_SQL; - private String deleteUserSql = DEF_DELETE_USER_SQL; - private String updateUserSql = DEF_UPDATE_USER_SQL; - private String createAuthoritySql = DEF_INSERT_AUTHORITY_SQL; - private String deleteUserAuthoritiesSql = DEF_DELETE_USER_AUTHORITIES_SQL; - private String userExistsSql = DEF_USER_EXISTS_SQL; - private String changePasswordSql = DEF_CHANGE_PASSWORD_SQL; - - private String findAllGroupsSql = DEF_FIND_GROUPS_SQL; - private String findUsersInGroupSql = DEF_FIND_USERS_IN_GROUP_SQL; - private String insertGroupSql = DEF_INSERT_GROUP_SQL; - private String findGroupIdSql = DEF_FIND_GROUP_ID_SQL; - private String insertGroupAuthoritySql = DEF_INSERT_GROUP_AUTHORITY_SQL; - private String deleteGroupSql = DEF_DELETE_GROUP_SQL; - private String deleteGroupAuthoritiesSql = DEF_DELETE_GROUP_AUTHORITIES_SQL; - private String deleteGroupMembersSql = DEF_DELETE_GROUP_MEMBERS_SQL; - private String renameGroupSql = DEF_RENAME_GROUP_SQL; - private String insertGroupMemberSql = DEF_INSERT_GROUP_MEMBER_SQL; - private String deleteGroupMemberSql = DEF_DELETE_GROUP_MEMBER_SQL; - private String groupAuthoritiesSql = DEF_GROUP_AUTHORITIES_QUERY_SQL; - private String deleteGroupAuthoritySql = DEF_DELETE_GROUP_AUTHORITY_SQL; - - private AuthenticationManager authenticationManager; - - private UserCache userCache = new NullUserCache(); - - // ~ Methods - // ======================================================================================================== - - protected void initDao() throws ApplicationContextException { - if (authenticationManager == null) { - logger.info("No authentication manager set. Reauthentication of users when changing passwords will " - + "not be performed."); - } - - super.initDao(); - } - - // ~ UserDetailsManager implementation - // ============================================================================== - - public void createUser(final UserDetails user) { - validateUserDetails(user); - getJdbcTemplate().update(createUserSql, new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - ps.setString(1, user.getUsername()); - ps.setString(2, user.getPassword()); - ps.setBoolean(3, user.isEnabled()); - } - - }); - - if (getEnableAuthorities()) { - insertUserAuthorities(user); - } - } - - public void updateUser(final UserDetails user) { - validateUserDetails(user); - getJdbcTemplate().update(updateUserSql, new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - ps.setString(1, user.getPassword()); - ps.setBoolean(2, user.isEnabled()); - ps.setString(3, user.getUsername()); - } - }); - - if (getEnableAuthorities()) { - deleteUserAuthorities(user.getUsername()); - insertUserAuthorities(user); - } - - userCache.removeUserFromCache(user.getUsername()); - } - - private void insertUserAuthorities(UserDetails user) { - for (GrantedAuthority auth : user.getAuthorities()) { - getJdbcTemplate().update(createAuthoritySql, user.getUsername(), - auth.getAuthority()); - } - } - - public void deleteUser(String username) { - if (getEnableAuthorities()) { - deleteUserAuthorities(username); - } - getJdbcTemplate().update(deleteUserSql, username); - userCache.removeUserFromCache(username); - } - - private void deleteUserAuthorities(String username) { - getJdbcTemplate().update(deleteUserAuthoritiesSql, username); - } - - public void changePassword(String oldPassword, String newPassword) - throws AuthenticationException { - Authentication currentUser = SecurityContextHolder.getContext() - .getAuthentication(); - - if (currentUser == null) { - // This would indicate bad coding somewhere - throw new AccessDeniedException( - "Can't change password as no Authentication object found in context " - + "for current user."); - } - - String username = currentUser.getName(); - - // If an authentication manager has been set, re-authenticate the user with the - // supplied password. - if (authenticationManager != null) { - logger.debug("Reauthenticating user '" + username - + "' for password change request."); - - authenticationManager.authenticate(new UsernamePasswordAuthenticationToken( - username, oldPassword)); - } - else { - logger.debug("No authentication manager set. Password won't be re-checked."); - } - - logger.debug("Changing password for user '" + username + "'"); - - getJdbcTemplate().update(changePasswordSql, newPassword, username); - - SecurityContextHolder.getContext().setAuthentication( - createNewAuthentication(currentUser, newPassword)); - - userCache.removeUserFromCache(username); - } - - protected Authentication createNewAuthentication(Authentication currentAuth, - String newPassword) { - UserDetails user = loadUserByUsername(currentAuth.getName()); - - UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken( - user, null, user.getAuthorities()); - newAuthentication.setDetails(currentAuth.getDetails()); - - return newAuthentication; - } - - public boolean userExists(String username) { - List users = getJdbcTemplate().queryForList(userExistsSql, - new String[] { username }, String.class); - - if (users.size() > 1) { - throw new IncorrectResultSizeDataAccessException( - "More than one user found with name '" + username + "'", 1); - } - - return users.size() == 1; - } - - // ~ GroupManager implementation - // ==================================================================================== - - public List findAllGroups() { - return getJdbcTemplate().queryForList(findAllGroupsSql, String.class); - } - - public List findUsersInGroup(String groupName) { - Assert.hasText(groupName); - return getJdbcTemplate().queryForList(findUsersInGroupSql, - new String[] { groupName }, String.class); - } - - public void createGroup(final String groupName, - final List authorities) { - Assert.hasText(groupName); - Assert.notNull(authorities); - - logger.debug("Creating new group '" + groupName + "' with authorities " - + AuthorityUtils.authorityListToSet(authorities)); - - getJdbcTemplate().update(insertGroupSql, groupName); - - final int groupId = findGroupId(groupName); - - for (GrantedAuthority a : authorities) { - final String authority = a.getAuthority(); - getJdbcTemplate().update(insertGroupAuthoritySql, - new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - ps.setInt(1, groupId); - ps.setString(2, authority); - } - }); - } - } - - public void deleteGroup(String groupName) { - logger.debug("Deleting group '" + groupName + "'"); - Assert.hasText(groupName); - - final int id = findGroupId(groupName); - PreparedStatementSetter groupIdPSS = new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - ps.setInt(1, id); - } - }; - getJdbcTemplate().update(deleteGroupMembersSql, groupIdPSS); - getJdbcTemplate().update(deleteGroupAuthoritiesSql, groupIdPSS); - getJdbcTemplate().update(deleteGroupSql, groupIdPSS); - } - - public void renameGroup(String oldName, String newName) { - logger.debug("Changing group name from '" + oldName + "' to '" + newName + "'"); - Assert.hasText(oldName); - Assert.hasText(newName); - - getJdbcTemplate().update(renameGroupSql, newName, oldName); - } - - public void addUserToGroup(final String username, final String groupName) { - logger.debug("Adding user '" + username + "' to group '" + groupName + "'"); - Assert.hasText(username); - Assert.hasText(groupName); - - final int id = findGroupId(groupName); - getJdbcTemplate().update(insertGroupMemberSql, new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - ps.setInt(1, id); - ps.setString(2, username); - } - }); - - userCache.removeUserFromCache(username); - } - - public void removeUserFromGroup(final String username, final String groupName) { - logger.debug("Removing user '" + username + "' to group '" + groupName + "'"); - Assert.hasText(username); - Assert.hasText(groupName); - - final int id = findGroupId(groupName); - - getJdbcTemplate().update(deleteGroupMemberSql, new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - ps.setInt(1, id); - ps.setString(2, username); - } - }); - - userCache.removeUserFromCache(username); - } - - public List findGroupAuthorities(String groupName) { - logger.debug("Loading authorities for group '" + groupName + "'"); - Assert.hasText(groupName); - - return getJdbcTemplate().query(groupAuthoritiesSql, new String[] { groupName }, - new RowMapper() { - public GrantedAuthority mapRow(ResultSet rs, int rowNum) - throws SQLException { - String roleName = getRolePrefix() + rs.getString(3); - - return new SimpleGrantedAuthority(roleName); - } - }); - } - - public void removeGroupAuthority(String groupName, final GrantedAuthority authority) { - logger.debug("Removing authority '" + authority + "' from group '" + groupName - + "'"); - Assert.hasText(groupName); - Assert.notNull(authority); - - final int id = findGroupId(groupName); - - getJdbcTemplate().update(deleteGroupAuthoritySql, new PreparedStatementSetter() { - - public void setValues(PreparedStatement ps) throws SQLException { - ps.setInt(1, id); - ps.setString(2, authority.getAuthority()); - } - }); - } - - public void addGroupAuthority(final String groupName, final GrantedAuthority authority) { - logger.debug("Adding authority '" + authority + "' to group '" + groupName + "'"); - Assert.hasText(groupName); - Assert.notNull(authority); - - final int id = findGroupId(groupName); - getJdbcTemplate().update(insertGroupAuthoritySql, new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - ps.setInt(1, id); - ps.setString(2, authority.getAuthority()); - } - }); - } - - private int findGroupId(String group) { - return getJdbcTemplate().queryForObject(findGroupIdSql, Integer.class, group); - } - - public void setAuthenticationManager(AuthenticationManager authenticationManager) { - this.authenticationManager = authenticationManager; - } - - public void setCreateUserSql(String createUserSql) { - Assert.hasText(createUserSql); - this.createUserSql = createUserSql; - } - - public void setDeleteUserSql(String deleteUserSql) { - Assert.hasText(deleteUserSql); - this.deleteUserSql = deleteUserSql; - } - - public void setUpdateUserSql(String updateUserSql) { - Assert.hasText(updateUserSql); - this.updateUserSql = updateUserSql; - } - - public void setCreateAuthoritySql(String createAuthoritySql) { - Assert.hasText(createAuthoritySql); - this.createAuthoritySql = createAuthoritySql; - } - - public void setDeleteUserAuthoritiesSql(String deleteUserAuthoritiesSql) { - Assert.hasText(deleteUserAuthoritiesSql); - this.deleteUserAuthoritiesSql = deleteUserAuthoritiesSql; - } - - public void setUserExistsSql(String userExistsSql) { - Assert.hasText(userExistsSql); - this.userExistsSql = userExistsSql; - } - - public void setChangePasswordSql(String changePasswordSql) { - Assert.hasText(changePasswordSql); - this.changePasswordSql = changePasswordSql; - } - - public void setFindAllGroupsSql(String findAllGroupsSql) { - Assert.hasText(findAllGroupsSql); - this.findAllGroupsSql = findAllGroupsSql; - } - - public void setFindUsersInGroupSql(String findUsersInGroupSql) { - Assert.hasText(findUsersInGroupSql); - this.findUsersInGroupSql = findUsersInGroupSql; - } - - public void setInsertGroupSql(String insertGroupSql) { - Assert.hasText(insertGroupSql); - this.insertGroupSql = insertGroupSql; - } - - public void setFindGroupIdSql(String findGroupIdSql) { - Assert.hasText(findGroupIdSql); - this.findGroupIdSql = findGroupIdSql; - } - - public void setInsertGroupAuthoritySql(String insertGroupAuthoritySql) { - Assert.hasText(insertGroupAuthoritySql); - this.insertGroupAuthoritySql = insertGroupAuthoritySql; - } - - public void setDeleteGroupSql(String deleteGroupSql) { - Assert.hasText(deleteGroupSql); - this.deleteGroupSql = deleteGroupSql; - } - - public void setDeleteGroupAuthoritiesSql(String deleteGroupAuthoritiesSql) { - Assert.hasText(deleteGroupAuthoritiesSql); - this.deleteGroupAuthoritiesSql = deleteGroupAuthoritiesSql; - } - - public void setDeleteGroupMembersSql(String deleteGroupMembersSql) { - Assert.hasText(deleteGroupMembersSql); - this.deleteGroupMembersSql = deleteGroupMembersSql; - } - - public void setRenameGroupSql(String renameGroupSql) { - Assert.hasText(renameGroupSql); - this.renameGroupSql = renameGroupSql; - } - - public void setInsertGroupMemberSql(String insertGroupMemberSql) { - Assert.hasText(insertGroupMemberSql); - this.insertGroupMemberSql = insertGroupMemberSql; - } - - public void setDeleteGroupMemberSql(String deleteGroupMemberSql) { - Assert.hasText(deleteGroupMemberSql); - this.deleteGroupMemberSql = deleteGroupMemberSql; - } - - public void setGroupAuthoritiesSql(String groupAuthoritiesSql) { - Assert.hasText(groupAuthoritiesSql); - this.groupAuthoritiesSql = groupAuthoritiesSql; - } - - public void setDeleteGroupAuthoritySql(String deleteGroupAuthoritySql) { - Assert.hasText(deleteGroupAuthoritySql); - this.deleteGroupAuthoritySql = deleteGroupAuthoritySql; - } - - /** - * Optionally sets the UserCache if one is in use in the application. This allows the - * user to be removed from the cache after updates have taken place to avoid stale - * data. - * - * @param userCache the cache used by the AuthenticationManager. - */ - public void setUserCache(UserCache userCache) { - Assert.notNull(userCache, "userCache cannot be null"); - this.userCache = userCache; - } - - private void validateUserDetails(UserDetails user) { - Assert.hasText(user.getUsername(), "Username may not be empty or null"); - validateAuthorities(user.getAuthorities()); - } - - private void validateAuthorities(Collection authorities) { - Assert.notNull(authorities, "Authorities list must not be null"); - - for (GrantedAuthority authority : authorities) { - Assert.notNull(authority, "Authorities list contains a null entry"); - Assert.hasText(authority.getAuthority(), - "getAuthority() method must return a non-empty string"); - } - } -} +package org.springframework.security.provisioning; + +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserCache; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.cache.NullUserCache; +import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl; +import org.springframework.context.ApplicationContextException; +import org.springframework.dao.IncorrectResultSizeDataAccessException; +import org.springframework.jdbc.core.PreparedStatementSetter; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.util.Assert; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Collection; +import java.util.List; + +/** + * Jdbc user management service, based on the same table structure as its parent class, + * JdbcDaoImpl. + *

+ * Provides CRUD operations for both users and groups. Note that if the + * {@link #setEnableAuthorities(boolean) enableAuthorities} property is set to false, + * calls to createUser, updateUser and deleteUser will not store the authorities from the + * UserDetails or delete authorities for the user. Since this class cannot + * differentiate between authorities which were loaded for an individual or for a group of + * which the individual is a member, it's important that you take this into account when + * using this implementation for managing your users. + * + * @author Luke Taylor + * @since 2.0 + */ +public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsManager, + GroupManager { + // ~ Static fields/initializers + // ===================================================================================== + + // UserDetailsManager SQL + public static final String DEF_CREATE_USER_SQL = "insert into users (username, password, enabled) values (?,?,?)"; + public static final String DEF_DELETE_USER_SQL = "delete from users where username = ?"; + public static final String DEF_UPDATE_USER_SQL = "update users set password = ?, enabled = ? where username = ?"; + public static final String DEF_INSERT_AUTHORITY_SQL = "insert into authorities (username, authority) values (?,?)"; + public static final String DEF_DELETE_USER_AUTHORITIES_SQL = "delete from authorities where username = ?"; + public static final String DEF_USER_EXISTS_SQL = "select username from users where username = ?"; + public static final String DEF_CHANGE_PASSWORD_SQL = "update users set password = ? where username = ?"; + + // GroupManager SQL + public static final String DEF_FIND_GROUPS_SQL = "select group_name from groups"; + public static final String DEF_FIND_USERS_IN_GROUP_SQL = "select username from group_members gm, groups g " + + "where gm.group_id = g.id" + " and g.group_name = ?"; + public static final String DEF_INSERT_GROUP_SQL = "insert into groups (group_name) values (?)"; + public static final String DEF_FIND_GROUP_ID_SQL = "select id from groups where group_name = ?"; + public static final String DEF_INSERT_GROUP_AUTHORITY_SQL = "insert into group_authorities (group_id, authority) values (?,?)"; + public static final String DEF_DELETE_GROUP_SQL = "delete from groups where id = ?"; + public static final String DEF_DELETE_GROUP_AUTHORITIES_SQL = "delete from group_authorities where group_id = ?"; + public static final String DEF_DELETE_GROUP_MEMBERS_SQL = "delete from group_members where group_id = ?"; + public static final String DEF_RENAME_GROUP_SQL = "update groups set group_name = ? where group_name = ?"; + public static final String DEF_INSERT_GROUP_MEMBER_SQL = "insert into group_members (group_id, username) values (?,?)"; + public static final String DEF_DELETE_GROUP_MEMBER_SQL = "delete from group_members where group_id = ? and username = ?"; + public static final String DEF_GROUP_AUTHORITIES_QUERY_SQL = "select g.id, g.group_name, ga.authority " + + "from groups g, group_authorities ga " + + "where g.group_name = ? " + + "and g.id = ga.group_id "; + public static final String DEF_DELETE_GROUP_AUTHORITY_SQL = "delete from group_authorities where group_id = ? and authority = ?"; + + // ~ Instance fields + // ================================================================================================ + + protected final Log logger = LogFactory.getLog(getClass()); + + private String createUserSql = DEF_CREATE_USER_SQL; + private String deleteUserSql = DEF_DELETE_USER_SQL; + private String updateUserSql = DEF_UPDATE_USER_SQL; + private String createAuthoritySql = DEF_INSERT_AUTHORITY_SQL; + private String deleteUserAuthoritiesSql = DEF_DELETE_USER_AUTHORITIES_SQL; + private String userExistsSql = DEF_USER_EXISTS_SQL; + private String changePasswordSql = DEF_CHANGE_PASSWORD_SQL; + + private String findAllGroupsSql = DEF_FIND_GROUPS_SQL; + private String findUsersInGroupSql = DEF_FIND_USERS_IN_GROUP_SQL; + private String insertGroupSql = DEF_INSERT_GROUP_SQL; + private String findGroupIdSql = DEF_FIND_GROUP_ID_SQL; + private String insertGroupAuthoritySql = DEF_INSERT_GROUP_AUTHORITY_SQL; + private String deleteGroupSql = DEF_DELETE_GROUP_SQL; + private String deleteGroupAuthoritiesSql = DEF_DELETE_GROUP_AUTHORITIES_SQL; + private String deleteGroupMembersSql = DEF_DELETE_GROUP_MEMBERS_SQL; + private String renameGroupSql = DEF_RENAME_GROUP_SQL; + private String insertGroupMemberSql = DEF_INSERT_GROUP_MEMBER_SQL; + private String deleteGroupMemberSql = DEF_DELETE_GROUP_MEMBER_SQL; + private String groupAuthoritiesSql = DEF_GROUP_AUTHORITIES_QUERY_SQL; + private String deleteGroupAuthoritySql = DEF_DELETE_GROUP_AUTHORITY_SQL; + + private AuthenticationManager authenticationManager; + + private UserCache userCache = new NullUserCache(); + + // ~ Methods + // ======================================================================================================== + + protected void initDao() throws ApplicationContextException { + if (authenticationManager == null) { + logger.info("No authentication manager set. Reauthentication of users when changing passwords will " + + "not be performed."); + } + + super.initDao(); + } + + // ~ UserDetailsManager implementation + // ============================================================================== + + public void createUser(final UserDetails user) { + validateUserDetails(user); + getJdbcTemplate().update(createUserSql, new PreparedStatementSetter() { + public void setValues(PreparedStatement ps) throws SQLException { + ps.setString(1, user.getUsername()); + ps.setString(2, user.getPassword()); + ps.setBoolean(3, user.isEnabled()); + } + + }); + + if (getEnableAuthorities()) { + insertUserAuthorities(user); + } + } + + public void updateUser(final UserDetails user) { + validateUserDetails(user); + getJdbcTemplate().update(updateUserSql, new PreparedStatementSetter() { + public void setValues(PreparedStatement ps) throws SQLException { + ps.setString(1, user.getPassword()); + ps.setBoolean(2, user.isEnabled()); + ps.setString(3, user.getUsername()); + } + }); + + if (getEnableAuthorities()) { + deleteUserAuthorities(user.getUsername()); + insertUserAuthorities(user); + } + + userCache.removeUserFromCache(user.getUsername()); + } + + private void insertUserAuthorities(UserDetails user) { + for (GrantedAuthority auth : user.getAuthorities()) { + getJdbcTemplate().update(createAuthoritySql, user.getUsername(), + auth.getAuthority()); + } + } + + public void deleteUser(String username) { + if (getEnableAuthorities()) { + deleteUserAuthorities(username); + } + getJdbcTemplate().update(deleteUserSql, username); + userCache.removeUserFromCache(username); + } + + private void deleteUserAuthorities(String username) { + getJdbcTemplate().update(deleteUserAuthoritiesSql, username); + } + + public void changePassword(String oldPassword, String newPassword) + throws AuthenticationException { + Authentication currentUser = SecurityContextHolder.getContext() + .getAuthentication(); + + if (currentUser == null) { + // This would indicate bad coding somewhere + throw new AccessDeniedException( + "Can't change password as no Authentication object found in context " + + "for current user."); + } + + String username = currentUser.getName(); + + // If an authentication manager has been set, re-authenticate the user with the + // supplied password. + if (authenticationManager != null) { + logger.debug("Reauthenticating user '" + username + + "' for password change request."); + + authenticationManager.authenticate(new UsernamePasswordAuthenticationToken( + username, oldPassword)); + } + else { + logger.debug("No authentication manager set. Password won't be re-checked."); + } + + logger.debug("Changing password for user '" + username + "'"); + + getJdbcTemplate().update(changePasswordSql, newPassword, username); + + SecurityContextHolder.getContext().setAuthentication( + createNewAuthentication(currentUser, newPassword)); + + userCache.removeUserFromCache(username); + } + + protected Authentication createNewAuthentication(Authentication currentAuth, + String newPassword) { + UserDetails user = loadUserByUsername(currentAuth.getName()); + + UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken( + user, null, user.getAuthorities()); + newAuthentication.setDetails(currentAuth.getDetails()); + + return newAuthentication; + } + + public boolean userExists(String username) { + List users = getJdbcTemplate().queryForList(userExistsSql, + new String[] { username }, String.class); + + if (users.size() > 1) { + throw new IncorrectResultSizeDataAccessException( + "More than one user found with name '" + username + "'", 1); + } + + return users.size() == 1; + } + + // ~ GroupManager implementation + // ==================================================================================== + + public List findAllGroups() { + return getJdbcTemplate().queryForList(findAllGroupsSql, String.class); + } + + public List findUsersInGroup(String groupName) { + Assert.hasText(groupName); + return getJdbcTemplate().queryForList(findUsersInGroupSql, + new String[] { groupName }, String.class); + } + + public void createGroup(final String groupName, + final List authorities) { + Assert.hasText(groupName); + Assert.notNull(authorities); + + logger.debug("Creating new group '" + groupName + "' with authorities " + + AuthorityUtils.authorityListToSet(authorities)); + + getJdbcTemplate().update(insertGroupSql, groupName); + + final int groupId = findGroupId(groupName); + + for (GrantedAuthority a : authorities) { + final String authority = a.getAuthority(); + getJdbcTemplate().update(insertGroupAuthoritySql, + new PreparedStatementSetter() { + public void setValues(PreparedStatement ps) throws SQLException { + ps.setInt(1, groupId); + ps.setString(2, authority); + } + }); + } + } + + public void deleteGroup(String groupName) { + logger.debug("Deleting group '" + groupName + "'"); + Assert.hasText(groupName); + + final int id = findGroupId(groupName); + PreparedStatementSetter groupIdPSS = new PreparedStatementSetter() { + public void setValues(PreparedStatement ps) throws SQLException { + ps.setInt(1, id); + } + }; + getJdbcTemplate().update(deleteGroupMembersSql, groupIdPSS); + getJdbcTemplate().update(deleteGroupAuthoritiesSql, groupIdPSS); + getJdbcTemplate().update(deleteGroupSql, groupIdPSS); + } + + public void renameGroup(String oldName, String newName) { + logger.debug("Changing group name from '" + oldName + "' to '" + newName + "'"); + Assert.hasText(oldName); + Assert.hasText(newName); + + getJdbcTemplate().update(renameGroupSql, newName, oldName); + } + + public void addUserToGroup(final String username, final String groupName) { + logger.debug("Adding user '" + username + "' to group '" + groupName + "'"); + Assert.hasText(username); + Assert.hasText(groupName); + + final int id = findGroupId(groupName); + getJdbcTemplate().update(insertGroupMemberSql, new PreparedStatementSetter() { + public void setValues(PreparedStatement ps) throws SQLException { + ps.setInt(1, id); + ps.setString(2, username); + } + }); + + userCache.removeUserFromCache(username); + } + + public void removeUserFromGroup(final String username, final String groupName) { + logger.debug("Removing user '" + username + "' to group '" + groupName + "'"); + Assert.hasText(username); + Assert.hasText(groupName); + + final int id = findGroupId(groupName); + + getJdbcTemplate().update(deleteGroupMemberSql, new PreparedStatementSetter() { + public void setValues(PreparedStatement ps) throws SQLException { + ps.setInt(1, id); + ps.setString(2, username); + } + }); + + userCache.removeUserFromCache(username); + } + + public List findGroupAuthorities(String groupName) { + logger.debug("Loading authorities for group '" + groupName + "'"); + Assert.hasText(groupName); + + return getJdbcTemplate().query(groupAuthoritiesSql, new String[] { groupName }, + new RowMapper() { + public GrantedAuthority mapRow(ResultSet rs, int rowNum) + throws SQLException { + String roleName = getRolePrefix() + rs.getString(3); + + return new SimpleGrantedAuthority(roleName); + } + }); + } + + public void removeGroupAuthority(String groupName, final GrantedAuthority authority) { + logger.debug("Removing authority '" + authority + "' from group '" + groupName + + "'"); + Assert.hasText(groupName); + Assert.notNull(authority); + + final int id = findGroupId(groupName); + + getJdbcTemplate().update(deleteGroupAuthoritySql, new PreparedStatementSetter() { + + public void setValues(PreparedStatement ps) throws SQLException { + ps.setInt(1, id); + ps.setString(2, authority.getAuthority()); + } + }); + } + + public void addGroupAuthority(final String groupName, final GrantedAuthority authority) { + logger.debug("Adding authority '" + authority + "' to group '" + groupName + "'"); + Assert.hasText(groupName); + Assert.notNull(authority); + + final int id = findGroupId(groupName); + getJdbcTemplate().update(insertGroupAuthoritySql, new PreparedStatementSetter() { + public void setValues(PreparedStatement ps) throws SQLException { + ps.setInt(1, id); + ps.setString(2, authority.getAuthority()); + } + }); + } + + private int findGroupId(String group) { + return getJdbcTemplate().queryForObject(findGroupIdSql, Integer.class, group); + } + + public void setAuthenticationManager(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + public void setCreateUserSql(String createUserSql) { + Assert.hasText(createUserSql); + this.createUserSql = createUserSql; + } + + public void setDeleteUserSql(String deleteUserSql) { + Assert.hasText(deleteUserSql); + this.deleteUserSql = deleteUserSql; + } + + public void setUpdateUserSql(String updateUserSql) { + Assert.hasText(updateUserSql); + this.updateUserSql = updateUserSql; + } + + public void setCreateAuthoritySql(String createAuthoritySql) { + Assert.hasText(createAuthoritySql); + this.createAuthoritySql = createAuthoritySql; + } + + public void setDeleteUserAuthoritiesSql(String deleteUserAuthoritiesSql) { + Assert.hasText(deleteUserAuthoritiesSql); + this.deleteUserAuthoritiesSql = deleteUserAuthoritiesSql; + } + + public void setUserExistsSql(String userExistsSql) { + Assert.hasText(userExistsSql); + this.userExistsSql = userExistsSql; + } + + public void setChangePasswordSql(String changePasswordSql) { + Assert.hasText(changePasswordSql); + this.changePasswordSql = changePasswordSql; + } + + public void setFindAllGroupsSql(String findAllGroupsSql) { + Assert.hasText(findAllGroupsSql); + this.findAllGroupsSql = findAllGroupsSql; + } + + public void setFindUsersInGroupSql(String findUsersInGroupSql) { + Assert.hasText(findUsersInGroupSql); + this.findUsersInGroupSql = findUsersInGroupSql; + } + + public void setInsertGroupSql(String insertGroupSql) { + Assert.hasText(insertGroupSql); + this.insertGroupSql = insertGroupSql; + } + + public void setFindGroupIdSql(String findGroupIdSql) { + Assert.hasText(findGroupIdSql); + this.findGroupIdSql = findGroupIdSql; + } + + public void setInsertGroupAuthoritySql(String insertGroupAuthoritySql) { + Assert.hasText(insertGroupAuthoritySql); + this.insertGroupAuthoritySql = insertGroupAuthoritySql; + } + + public void setDeleteGroupSql(String deleteGroupSql) { + Assert.hasText(deleteGroupSql); + this.deleteGroupSql = deleteGroupSql; + } + + public void setDeleteGroupAuthoritiesSql(String deleteGroupAuthoritiesSql) { + Assert.hasText(deleteGroupAuthoritiesSql); + this.deleteGroupAuthoritiesSql = deleteGroupAuthoritiesSql; + } + + public void setDeleteGroupMembersSql(String deleteGroupMembersSql) { + Assert.hasText(deleteGroupMembersSql); + this.deleteGroupMembersSql = deleteGroupMembersSql; + } + + public void setRenameGroupSql(String renameGroupSql) { + Assert.hasText(renameGroupSql); + this.renameGroupSql = renameGroupSql; + } + + public void setInsertGroupMemberSql(String insertGroupMemberSql) { + Assert.hasText(insertGroupMemberSql); + this.insertGroupMemberSql = insertGroupMemberSql; + } + + public void setDeleteGroupMemberSql(String deleteGroupMemberSql) { + Assert.hasText(deleteGroupMemberSql); + this.deleteGroupMemberSql = deleteGroupMemberSql; + } + + public void setGroupAuthoritiesSql(String groupAuthoritiesSql) { + Assert.hasText(groupAuthoritiesSql); + this.groupAuthoritiesSql = groupAuthoritiesSql; + } + + public void setDeleteGroupAuthoritySql(String deleteGroupAuthoritySql) { + Assert.hasText(deleteGroupAuthoritySql); + this.deleteGroupAuthoritySql = deleteGroupAuthoritySql; + } + + /** + * Optionally sets the UserCache if one is in use in the application. This allows the + * user to be removed from the cache after updates have taken place to avoid stale + * data. + * + * @param userCache the cache used by the AuthenticationManager. + */ + public void setUserCache(UserCache userCache) { + Assert.notNull(userCache, "userCache cannot be null"); + this.userCache = userCache; + } + + private void validateUserDetails(UserDetails user) { + Assert.hasText(user.getUsername(), "Username may not be empty or null"); + validateAuthorities(user.getAuthorities()); + } + + private void validateAuthorities(Collection authorities) { + Assert.notNull(authorities, "Authorities list must not be null"); + + for (GrantedAuthority authority : authorities) { + Assert.notNull(authority, "Authorities list contains a null entry"); + Assert.hasText(authority.getAuthority(), + "getAuthority() method must return a non-empty string"); + } + } +} diff --git a/core/src/test/java/org/springframework/security/access/SecurityConfigTests.java b/core/src/test/java/org/springframework/security/access/SecurityConfigTests.java index d471473621..56d8f7aae8 100644 --- a/core/src/test/java/org/springframework/security/access/SecurityConfigTests.java +++ b/core/src/test/java/org/springframework/security/access/SecurityConfigTests.java @@ -70,13 +70,13 @@ public class SecurityConfigTests { assertThat(!security1.equals(security3)).isTrue(); MockConfigAttribute mock1 = new MockConfigAttribute("TEST"); - assertThat(mock1).isEqualTo(security1); + assertThat(security1).isEqualTo(mock1); MockConfigAttribute mock2 = new MockConfigAttribute("NOT_EQUAL"); - assertThat(!security1.equals(mock2)).isTrue(); + assertThat(security1).isNotEqualTo(mock2); Integer int1 = Integer.valueOf(987); - assertThat(!security1.equals(int1)).isTrue(); + assertThat(security1).isNotEqualTo(int1); } @Test diff --git a/core/src/test/java/org/springframework/security/access/annotation/Jsr250MethodSecurityMetadataSourceTests.java b/core/src/test/java/org/springframework/security/access/annotation/Jsr250MethodSecurityMetadataSourceTests.java index 2ef2fa006c..984c26986e 100644 --- a/core/src/test/java/org/springframework/security/access/annotation/Jsr250MethodSecurityMetadataSourceTests.java +++ b/core/src/test/java/org/springframework/security/access/annotation/Jsr250MethodSecurityMetadataSourceTests.java @@ -13,6 +13,7 @@ * License for the specific language governing permissions and limitations under * the License. */ + package org.springframework.security.access.annotation; import static org.assertj.core.api.Assertions.assertThat; @@ -22,7 +23,6 @@ import java.util.Collection; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.security.access.ConfigAttribute; @@ -33,8 +33,11 @@ import org.springframework.security.access.intercept.method.MockMethodInvocation * @author Ben Alex */ public class Jsr250MethodSecurityMetadataSourceTests { + Jsr250MethodSecurityMetadataSource mds; + A a; + UserAllowedClass userAllowed; @Before @@ -60,27 +63,28 @@ public class Jsr250MethodSecurityMetadataSourceTests { public void permitAllMethodHasPermitAllAttribute() throws Exception { ConfigAttribute[] accessAttributes = findAttributes("permitAllMethod"); assertThat(accessAttributes).hasSize(1); - assertThat(accessAttributes[0].toString()).isEqualTo("javax.annotation.security.PermitAll"); + assertThat(accessAttributes[0].toString()).isEqualTo( + "javax.annotation.security.PermitAll"); } @Test public void noRoleMethodHasNoAttributes() throws Exception { - Collection accessAttributes = mds.findAttributes(a.getClass() - .getMethod("noRoleMethod"), null); + Collection accessAttributes = mds.findAttributes( + a.getClass().getMethod("noRoleMethod"), null); assertThat(accessAttributes).isNull(); } @Test public void classRoleIsAppliedToNoRoleMethod() throws Exception { - Collection accessAttributes = mds.findAttributes(userAllowed - .getClass().getMethod("noRoleMethod"), null); + Collection accessAttributes = mds.findAttributes( + userAllowed.getClass().getMethod("noRoleMethod"), null); assertThat(accessAttributes).isNull(); } @Test public void methodRoleOverridesClassRole() throws Exception { - Collection accessAttributes = mds.findAttributes(userAllowed - .getClass().getMethod("adminMethod"), null); + Collection accessAttributes = mds.findAttributes( + userAllowed.getClass().getMethod("adminMethod"), null); assertThat(accessAttributes).hasSize(1); assertThat(accessAttributes.toArray()[0].toString()).isEqualTo("ROLE_ADMIN"); } @@ -125,6 +129,7 @@ public class Jsr250MethodSecurityMetadataSourceTests { * Class-level annotations only affect the class they annotate and their members, that * is, its methods and fields. They never affect a member declared by a superclass, * even if it is not hidden or overridden by the class in question. + * * @throws Exception */ @Test @@ -162,7 +167,8 @@ public class Jsr250MethodSecurityMetadataSourceTests { } @Test - public void classLevelAnnotationsIgnoredByExplicitMemberAnnotation() throws Exception { + public void classLevelAnnotationsIgnoredByExplicitMemberAnnotation() + throws Exception { Child target = new Child(); MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(), "explicitMethod"); @@ -175,6 +181,7 @@ public class Jsr250MethodSecurityMetadataSourceTests { /** * The interfaces implemented by a class never contribute annotations to the class * itself or any of its members. + * * @throws Exception */ @Test @@ -231,6 +238,7 @@ public class Jsr250MethodSecurityMetadataSourceTests { @RolesAllowed("USER") public static class UserAllowedClass { + public void noRoleMethod() { } @@ -243,11 +251,13 @@ public class Jsr250MethodSecurityMetadataSourceTests { @RolesAllowed("IPARENT") interface IParent { + @RolesAllowed("INTERFACEMETHOD") void interfaceMethod(); } static class Parent implements IParent { + public void interfaceMethod() { } @@ -264,6 +274,7 @@ public class Jsr250MethodSecurityMetadataSourceTests { @RolesAllowed("DERIVED") class Child extends Parent { + public void overriden() { } diff --git a/core/src/test/java/org/springframework/security/access/annotation/SecuredAnnotationSecurityMetadataSourceTests.java b/core/src/test/java/org/springframework/security/access/annotation/SecuredAnnotationSecurityMetadataSourceTests.java index d101de8010..6a9dc5d504 100644 --- a/core/src/test/java/org/springframework/security/access/annotation/SecuredAnnotationSecurityMetadataSourceTests.java +++ b/core/src/test/java/org/springframework/security/access/annotation/SecuredAnnotationSecurityMetadataSourceTests.java @@ -12,12 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.security.access.annotation; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import static org.assertj.core.api.Assertions.fail; import java.lang.annotation.ElementType; @@ -78,7 +76,8 @@ public class SecuredAnnotationSecurityMetadataSourceTests { // should have 1 SecurityConfig for (ConfigAttribute sc : attrs) { - assertThat(sc.getAttribute()).as("Found an incorrect role").isEqualTo("ROLE_ADMIN"); + assertThat(sc.getAttribute()).as("Found an incorrect role").isEqualTo( + "ROLE_ADMIN"); } Method superMethod = null; @@ -101,14 +100,15 @@ public class SecuredAnnotationSecurityMetadataSourceTests { assertThat(superAttrs).as("Did not find 1 attribute").hasSize(1); // should have 1 SecurityConfig for (ConfigAttribute sc : superAttrs) { - assertThat(sc.getAttribute()).as("Found an incorrect role").isEqualTo("ROLE_ADMIN"); + assertThat(sc.getAttribute()).as("Found an incorrect role").isEqualTo( + "ROLE_ADMIN"); } } @Test public void classLevelAttributesAreFound() { - Collection attrs = this.mds - .findAttributes(BusinessService.class); + Collection attrs = this.mds.findAttributes( + BusinessService.class); assertThat(attrs).isNotNull(); @@ -165,8 +165,8 @@ public class SecuredAnnotationSecurityMetadataSourceTests { public void customAnnotationAttributesAreFound() throws Exception { SecuredAnnotationSecurityMetadataSource mds = new SecuredAnnotationSecurityMetadataSource( new CustomSecurityAnnotationMetadataExtractor()); - Collection attrs = mds - .findAttributes(CustomAnnotatedService.class); + Collection attrs = mds.findAttributes( + CustomAnnotatedService.class); assertThat(attrs).hasSize(1); assertThat(attrs.toArray()[0]).isEqualTo(SecurityEnum.ADMIN); } @@ -219,19 +219,22 @@ public class SecuredAnnotationSecurityMetadataSourceTests { // Inner classes class Department extends Entity { + public Department(String name) { super(name); } } interface DepartmentService extends BusinessService { + @Secured({ "ROLE_USER" }) Department someUserMethod3(Department dept); } @SuppressWarnings("serial") - class DepartmentServiceImpl extends BusinessServiceImpl implements - DepartmentService { + class DepartmentServiceImpl extends BusinessServiceImpl + implements DepartmentService { + @Secured({ "ROLE_ADMIN" }) public Department someUserMethod3(final Department dept) { return super.someUserMethod3(dept); @@ -247,7 +250,7 @@ public class SecuredAnnotationSecurityMetadataSourceTests { class CustomAnnotatedServiceImpl implements CustomAnnotatedService { } - enum SecurityEnum implements ConfigAttribute, GrantedAuthority { + enum SecurityEnum implements ConfigAttribute,GrantedAuthority { ADMIN, USER; public String getAttribute() { @@ -262,11 +265,13 @@ public class SecuredAnnotationSecurityMetadataSourceTests { @Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @interface CustomSecurityAnnotation { - SecurityEnum[] value(); + + SecurityEnum[]value(); } - class CustomSecurityAnnotationMetadataExtractor implements - AnnotationMetadataExtractor { + class CustomSecurityAnnotationMetadataExtractor + implements AnnotationMetadataExtractor { + public Collection extractAttributes( CustomSecurityAnnotation securityAnnotation) { SecurityEnum[] values = securityAnnotation.value(); @@ -283,26 +288,31 @@ public class SecuredAnnotationSecurityMetadataSourceTests { } public static interface ReturnVoid { + public void doSomething(List param); } @AnnotatedAnnotation public static interface ReturnVoid2 { + public void doSomething(List param); } @AnnotatedAnnotation public static class AnnotatedAnnotationAtClassLevel implements ReturnVoid { + public void doSomething(List param) { } } public static class AnnotatedAnnotationAtInterfaceLevel implements ReturnVoid2 { + public void doSomething(List param) { } } public static class AnnotatedAnnotationAtMethodLevel implements ReturnVoid { + @AnnotatedAnnotation public void doSomething(List param) { } diff --git a/core/src/test/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyImplTests.java b/core/src/test/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyImplTests.java index cf998601d7..8fdb440845 100644 --- a/core/src/test/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyImplTests.java +++ b/core/src/test/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyImplTests.java @@ -14,16 +14,13 @@ package org.springframework.security.access.hierarchicalroles; - import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.ArrayList; import java.util.List; -import junit.framework.TestCase; - -import org.springframework.security.access.hierarchicalroles.CycleInRoleHierarchyException; -import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl; +import org.junit.Test; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; @@ -32,8 +29,9 @@ import org.springframework.security.core.authority.AuthorityUtils; * * @author Michael Mayr */ -public class RoleHierarchyImplTests extends TestCase { +public class RoleHierarchyImplTests { + @Test public void testRoleHierarchyWithNullOrEmptyAuthorities() { List authorities0 = null; List authorities1 = new ArrayList(); @@ -41,93 +39,103 @@ public class RoleHierarchyImplTests extends TestCase { RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl(); roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B"); - assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities0)).isNotNull(); - assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities0)).isEmpty();; - assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities1)).isNotNull(); - assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities1)).isEmpty();; + assertThat(roleHierarchyImpl.getReachableGrantedAuthorities( + authorities0)).isNotNull(); + assertThat( + roleHierarchyImpl.getReachableGrantedAuthorities(authorities0)).isEmpty(); + ; + assertThat(roleHierarchyImpl.getReachableGrantedAuthorities( + authorities1)).isNotNull(); + assertThat( + roleHierarchyImpl.getReachableGrantedAuthorities(authorities1)).isEmpty(); + ; } + @Test public void testSimpleRoleHierarchy() { - List authorities0 = AuthorityUtils - .createAuthorityList("ROLE_0"); - List authorities1 = AuthorityUtils - .createAuthorityList("ROLE_A"); - List authorities2 = AuthorityUtils.createAuthorityList( - "ROLE_A", "ROLE_B"); + List authorities0 = AuthorityUtils.createAuthorityList( + "ROLE_0"); + List authorities1 = AuthorityUtils.createAuthorityList( + "ROLE_A"); + List authorities2 = AuthorityUtils.createAuthorityList("ROLE_A", + "ROLE_B"); RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl(); roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B"); - assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( + assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( roleHierarchyImpl.getReachableGrantedAuthorities(authorities0), - authorities0)); - assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( + authorities0)).isTrue(); + assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), - authorities2)); - assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( + authorities2)).isTrue(); + assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( roleHierarchyImpl.getReachableGrantedAuthorities(authorities2), - authorities2)); + authorities2)).isTrue(); } + @Test public void testTransitiveRoleHierarchies() { - List authorities1 = AuthorityUtils - .createAuthorityList("ROLE_A"); - List authorities2 = AuthorityUtils.createAuthorityList( - "ROLE_A", "ROLE_B", "ROLE_C"); - List authorities3 = AuthorityUtils.createAuthorityList( - "ROLE_A", "ROLE_B", "ROLE_C", "ROLE_D"); + List authorities1 = AuthorityUtils.createAuthorityList( + "ROLE_A"); + List authorities2 = AuthorityUtils.createAuthorityList("ROLE_A", + "ROLE_B", "ROLE_C"); + List authorities3 = AuthorityUtils.createAuthorityList("ROLE_A", + "ROLE_B", "ROLE_C", "ROLE_D"); RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl(); roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C"); - assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( + assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), - authorities2)); + authorities2)).isTrue(); - roleHierarchyImpl - .setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_D"); - assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( + roleHierarchyImpl.setHierarchy( + "ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_D"); + assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), - authorities3)); + authorities3)).isTrue(); } + @Test public void testComplexRoleHierarchy() { - List authoritiesInput1 = AuthorityUtils - .createAuthorityList("ROLE_A"); + List authoritiesInput1 = AuthorityUtils.createAuthorityList( + "ROLE_A"); List authoritiesOutput1 = AuthorityUtils.createAuthorityList( "ROLE_A", "ROLE_B", "ROLE_C", "ROLE_D"); - List authoritiesInput2 = AuthorityUtils - .createAuthorityList("ROLE_B"); + List authoritiesInput2 = AuthorityUtils.createAuthorityList( + "ROLE_B"); List authoritiesOutput2 = AuthorityUtils.createAuthorityList( "ROLE_B", "ROLE_D"); - List authoritiesInput3 = AuthorityUtils - .createAuthorityList("ROLE_C"); + List authoritiesInput3 = AuthorityUtils.createAuthorityList( + "ROLE_C"); List authoritiesOutput3 = AuthorityUtils.createAuthorityList( "ROLE_C", "ROLE_D"); - List authoritiesInput4 = AuthorityUtils - .createAuthorityList("ROLE_D"); - List authoritiesOutput4 = AuthorityUtils - .createAuthorityList("ROLE_D"); + List authoritiesInput4 = AuthorityUtils.createAuthorityList( + "ROLE_D"); + List authoritiesOutput4 = AuthorityUtils.createAuthorityList( + "ROLE_D"); RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl(); - roleHierarchyImpl - .setHierarchy("ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D"); + roleHierarchyImpl.setHierarchy( + "ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D"); - assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( + assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput1), - authoritiesOutput1)); - assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( + authoritiesOutput1)).isTrue(); + assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput2), - authoritiesOutput2)); - assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( + authoritiesOutput2)).isTrue(); + assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput3), - authoritiesOutput3)); - assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( + authoritiesOutput3)).isTrue(); + assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities( roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput4), - authoritiesOutput4)); + authoritiesOutput4)).isTrue(); } + @Test public void testCyclesInRoleHierarchy() { RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl(); @@ -146,28 +154,29 @@ public class RoleHierarchyImplTests extends TestCase { } try { - roleHierarchyImpl - .setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_A"); + roleHierarchyImpl.setHierarchy( + "ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_A"); fail("Cycle in role hierarchy was not detected!"); } catch (CycleInRoleHierarchyException e) { } try { - roleHierarchyImpl - .setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_E\nROLE_E > ROLE_D\nROLE_D > ROLE_B"); + roleHierarchyImpl.setHierarchy( + "ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_E\nROLE_E > ROLE_D\nROLE_D > ROLE_B"); fail("Cycle in role hierarchy was not detected!"); } catch (CycleInRoleHierarchyException e) { } } + @Test public void testNoCyclesInRoleHierarchy() { RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl(); try { - roleHierarchyImpl - .setHierarchy("ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D"); + roleHierarchyImpl.setHierarchy( + "ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D"); } catch (CycleInRoleHierarchyException e) { fail("A cycle in role hierarchy was incorrectly detected!"); @@ -175,29 +184,30 @@ public class RoleHierarchyImplTests extends TestCase { } // SEC-863 + @Test public void testSimpleRoleHierarchyWithCustomGrantedAuthorityImplementation() { - List authorities0 = HierarchicalRolesTestHelper - .createAuthorityList("ROLE_0"); - List authorities1 = HierarchicalRolesTestHelper - .createAuthorityList("ROLE_A"); - List authorities2 = HierarchicalRolesTestHelper - .createAuthorityList("ROLE_A", "ROLE_B"); + List authorities0 = HierarchicalRolesTestHelper.createAuthorityList( + "ROLE_0"); + List authorities1 = HierarchicalRolesTestHelper.createAuthorityList( + "ROLE_A"); + List authorities2 = HierarchicalRolesTestHelper.createAuthorityList( + "ROLE_A", "ROLE_B"); RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl(); roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B"); - assertTrue(HierarchicalRolesTestHelper - .containTheSameGrantedAuthoritiesCompareByAuthorityString( + assertThat( + HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString( roleHierarchyImpl.getReachableGrantedAuthorities(authorities0), - authorities0)); - assertTrue(HierarchicalRolesTestHelper - .containTheSameGrantedAuthoritiesCompareByAuthorityString( + authorities0)).isTrue(); + assertThat( + HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString( roleHierarchyImpl.getReachableGrantedAuthorities(authorities1), - authorities2)); - assertTrue(HierarchicalRolesTestHelper - .containTheSameGrantedAuthoritiesCompareByAuthorityString( + authorities2)).isTrue(); + assertThat( + HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString( roleHierarchyImpl.getReachableGrantedAuthorities(authorities2), - authorities2)); + authorities2)).isTrue(); } } diff --git a/core/src/test/java/org/springframework/security/access/intercept/AfterInvocationProviderManagerTests.java b/core/src/test/java/org/springframework/security/access/intercept/AfterInvocationProviderManagerTests.java index aa1a21de46..7717b7dddf 100644 --- a/core/src/test/java/org/springframework/security/access/intercept/AfterInvocationProviderManagerTests.java +++ b/core/src/test/java/org/springframework/security/access/intercept/AfterInvocationProviderManagerTests.java @@ -16,19 +16,18 @@ package org.springframework.security.access.intercept; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.Collection; import java.util.List; import java.util.Vector; -import junit.framework.TestCase; - import org.aopalliance.intercept.MethodInvocation; +import org.junit.Test; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.AfterInvocationProvider; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; -import org.springframework.security.access.intercept.AfterInvocationProviderManager; import org.springframework.security.core.Authentication; import org.springframework.security.util.SimpleMethodInvocation; @@ -38,11 +37,11 @@ import org.springframework.security.util.SimpleMethodInvocation; * @author Ben Alex */ @SuppressWarnings("unchecked") -public class AfterInvocationProviderManagerTests extends TestCase { +public class AfterInvocationProviderManagerTests { // ~ Methods // ======================================================================================================== - + @Test public void testCorrectOperation() throws Exception { AfterInvocationProviderManager manager = new AfterInvocationProviderManager(); List list = new Vector(); @@ -56,16 +55,16 @@ public class AfterInvocationProviderManagerTests extends TestCase { assertThat(manager.getProviders()).isEqualTo(list); manager.afterPropertiesSet(); - List attr1 = SecurityConfig - .createList(new String[] { "GIVE_ME_SWAP1" }); - List attr2 = SecurityConfig - .createList(new String[] { "GIVE_ME_SWAP2" }); - List attr3 = SecurityConfig - .createList(new String[] { "GIVE_ME_SWAP3" }); - List attr2and3 = SecurityConfig.createList(new String[] { - "GIVE_ME_SWAP2", "GIVE_ME_SWAP3" }); - List attr4 = SecurityConfig - .createList(new String[] { "NEVER_CAUSES_SWAP" }); + List attr1 = SecurityConfig.createList( + new String[] { "GIVE_ME_SWAP1" }); + List attr2 = SecurityConfig.createList( + new String[] { "GIVE_ME_SWAP2" }); + List attr3 = SecurityConfig.createList( + new String[] { "GIVE_ME_SWAP3" }); + List attr2and3 = SecurityConfig.createList( + new String[] { "GIVE_ME_SWAP2", "GIVE_ME_SWAP3" }); + List attr4 = SecurityConfig.createList( + new String[] { "NEVER_CAUSES_SWAP" }); assertThat(manager.decide(null, new SimpleMethodInvocation(), attr1, "content-before-swapping")).isEqualTo("swap1"); @@ -76,13 +75,14 @@ public class AfterInvocationProviderManagerTests extends TestCase { assertThat(manager.decide(null, new SimpleMethodInvocation(), attr3, "content-before-swapping")).isEqualTo("swap3"); - assertThat(manager.decide(null, - new SimpleMethodInvocation(), attr4, "content-before-swapping")).isEqualTo("content-before-swapping"); + assertThat(manager.decide(null, new SimpleMethodInvocation(), attr4, + "content-before-swapping")).isEqualTo("content-before-swapping"); - assertThat(manager.decide(null, new SimpleMethodInvocation(), - attr2and3, "content-before-swapping")).isEqualTo("swap3"); + assertThat(manager.decide(null, new SimpleMethodInvocation(), attr2and3, + "content-before-swapping")).isEqualTo("swap3"); } + @Test public void testRejectsEmptyProvidersList() { AfterInvocationProviderManager manager = new AfterInvocationProviderManager(); List list = new Vector(); @@ -92,10 +92,11 @@ public class AfterInvocationProviderManagerTests extends TestCase { fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { - assertTrue(true); + assertThat(true).isTrue(); } } + @Test public void testRejectsNonAfterInvocationProviders() { AfterInvocationProviderManager manager = new AfterInvocationProviderManager(); List list = new Vector(); @@ -110,10 +111,11 @@ public class AfterInvocationProviderManagerTests extends TestCase { fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { - assertTrue(true); + assertThat(true).isTrue(); } } + @Test public void testRejectsNullProvidersList() throws Exception { AfterInvocationProviderManager manager = new AfterInvocationProviderManager(); @@ -122,10 +124,11 @@ public class AfterInvocationProviderManagerTests extends TestCase { fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { - assertTrue(true); + assertThat(true).isTrue(); } } + @Test public void testSupportsConfigAttributeIteration() throws Exception { AfterInvocationProviderManager manager = new AfterInvocationProviderManager(); List list = new Vector(); @@ -138,10 +141,11 @@ public class AfterInvocationProviderManagerTests extends TestCase { manager.setProviders(list); manager.afterPropertiesSet(); - assertFalse(manager.supports(new SecurityConfig("UNKNOWN_ATTRIB"))); - assertTrue(manager.supports(new SecurityConfig("GIVE_ME_SWAP2"))); + assertThat(manager.supports(new SecurityConfig("UNKNOWN_ATTRIB"))).isFalse(); + assertThat(manager.supports(new SecurityConfig("GIVE_ME_SWAP2"))).isTrue(); } + @Test public void testSupportsSecureObjectIteration() throws Exception { AfterInvocationProviderManager manager = new AfterInvocationProviderManager(); List list = new Vector(); @@ -155,7 +159,7 @@ public class AfterInvocationProviderManagerTests extends TestCase { manager.afterPropertiesSet(); // assertFalse(manager.supports(FilterInvocation.class)); - assertTrue(manager.supports(MethodInvocation.class)); + assertThat(manager.supports(MethodInvocation.class)).isTrue(); } // ~ Inner Classes @@ -167,8 +171,11 @@ public class AfterInvocationProviderManagerTests extends TestCase { * supports. */ private class MockAfterInvocationProvider implements AfterInvocationProvider { + private Class secureObject; + private ConfigAttribute configAttribute; + private Object forceReturnObject; public MockAfterInvocationProvider(Object forceReturnObject, Class secureObject, @@ -180,7 +187,7 @@ public class AfterInvocationProviderManagerTests extends TestCase { public Object decide(Authentication authentication, Object object, Collection config, Object returnedObject) - throws AccessDeniedException { + throws AccessDeniedException { if (config.contains(configAttribute)) { return forceReturnObject; } diff --git a/core/src/test/java/org/springframework/security/access/intercept/NullRunAsManagerTests.java b/core/src/test/java/org/springframework/security/access/intercept/NullRunAsManagerTests.java index 9d50616ee0..0d4349b54c 100644 --- a/core/src/test/java/org/springframework/security/access/intercept/NullRunAsManagerTests.java +++ b/core/src/test/java/org/springframework/security/access/intercept/NullRunAsManagerTests.java @@ -17,34 +17,31 @@ package org.springframework.security.access.intercept; import static org.assertj.core.api.Assertions.assertThat; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.security.access.SecurityConfig; -import org.springframework.security.access.intercept.NullRunAsManager; /** * Tests {@link NullRunAsManager}. * * @author Ben Alex */ -public class NullRunAsManagerTests extends TestCase { +public class NullRunAsManagerTests { // ~ Methods // ======================================================================================================== - public final void setUp() throws Exception { - super.setUp(); - } - + @Test public void testAlwaysReturnsNull() { NullRunAsManager runAs = new NullRunAsManager(); assertThat(runAs.buildRunAs(null, null, null)).isNull(); } + @Test public void testAlwaysSupportsClass() { NullRunAsManager runAs = new NullRunAsManager(); assertThat(runAs.supports(String.class)).isTrue(); } + @Test public void testNeverSupportsAttribute() { NullRunAsManager runAs = new NullRunAsManager(); assertThat(runAs.supports(new SecurityConfig("X"))).isFalse(); diff --git a/core/src/test/java/org/springframework/security/access/intercept/RunAsManagerImplTests.java b/core/src/test/java/org/springframework/security/access/intercept/RunAsManagerImplTests.java index 9ace967c4b..dfcfde5682 100644 --- a/core/src/test/java/org/springframework/security/access/intercept/RunAsManagerImplTests.java +++ b/core/src/test/java/org/springframework/security/access/intercept/RunAsManagerImplTests.java @@ -16,11 +16,11 @@ package org.springframework.security.access.intercept; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.Set; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.security.access.SecurityConfig; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; @@ -31,17 +31,20 @@ import org.springframework.security.core.authority.AuthorityUtils; * * @author Ben Alex */ -public class RunAsManagerImplTests extends TestCase { +public class RunAsManagerImplTests { + + @Test public void testAlwaysSupportsClass() { RunAsManagerImpl runAs = new RunAsManagerImpl(); assertThat(runAs.supports(String.class)).isTrue(); } + @Test public void testDoesNotReturnAdditionalAuthoritiesIfCalledWithoutARunAsSetting() throws Exception { UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken( - "Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE", - "ROLE_TWO")); + "Test", "Password", + AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); RunAsManagerImpl runAs = new RunAsManagerImpl(); runAs.setKey("my_password"); @@ -51,6 +54,7 @@ public class RunAsManagerImplTests extends TestCase { assertThat(resultingToken).isEqualTo(null); } + @Test public void testRespectsRolePrefix() throws Exception { UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken( "Test", "Password", AuthorityUtils.createAuthorityList("ONE", "TWO")); @@ -62,12 +66,12 @@ public class RunAsManagerImplTests extends TestCase { Authentication result = runAs.buildRunAs(inputToken, new Object(), SecurityConfig.createList("RUN_AS_SOMETHING")); - assertTrue("Should have returned a RunAsUserToken", - result instanceof RunAsUserToken); + assertThat(result instanceof RunAsUserToken).withFailMessage( + "Should have returned a RunAsUserToken").isTrue(); assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal()); assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials()); - Set authorities = AuthorityUtils.authorityListToSet(result - .getAuthorities()); + Set authorities = AuthorityUtils.authorityListToSet( + result.getAuthorities()); assertThat(authorities.contains("FOOBAR_RUN_AS_SOMETHING")).isTrue(); assertThat(authorities.contains("ONE")).isTrue(); @@ -77,10 +81,11 @@ public class RunAsManagerImplTests extends TestCase { assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode()); } + @Test public void testReturnsAdditionalGrantedAuthorities() throws Exception { UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken( - "Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE", - "ROLE_TWO")); + "Test", "Password", + AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); RunAsManagerImpl runAs = new RunAsManagerImpl(); runAs.setKey("my_password"); @@ -95,8 +100,8 @@ public class RunAsManagerImplTests extends TestCase { assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal()); assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials()); - Set authorities = AuthorityUtils.authorityListToSet(result - .getAuthorities()); + Set authorities = AuthorityUtils.authorityListToSet( + result.getAuthorities()); assertThat(authorities.contains("ROLE_RUN_AS_SOMETHING")).isTrue(); assertThat(authorities.contains("ROLE_ONE")).isTrue(); assertThat(authorities.contains("ROLE_TWO")).isTrue(); @@ -105,6 +110,7 @@ public class RunAsManagerImplTests extends TestCase { assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode()); } + @Test public void testStartupDetectsMissingKey() throws Exception { RunAsManagerImpl runAs = new RunAsManagerImpl(); @@ -117,6 +123,7 @@ public class RunAsManagerImplTests extends TestCase { } } + @Test public void testStartupSuccessfulWithKey() throws Exception { RunAsManagerImpl runAs = new RunAsManagerImpl(); runAs.setKey("hello_world"); @@ -124,6 +131,7 @@ public class RunAsManagerImplTests extends TestCase { assertThat(runAs.getKey()).isEqualTo("hello_world"); } + @Test public void testSupports() throws Exception { RunAsManager runAs = new RunAsManagerImpl(); assertThat(runAs.supports(new SecurityConfig("RUN_AS_SOMETHING"))).isTrue(); diff --git a/core/src/test/java/org/springframework/security/access/intercept/RunAsUserTokenTests.java b/core/src/test/java/org/springframework/security/access/intercept/RunAsUserTokenTests.java index e3d8b794bc..56c98a0487 100644 --- a/core/src/test/java/org/springframework/security/access/intercept/RunAsUserTokenTests.java +++ b/core/src/test/java/org/springframework/security/access/intercept/RunAsUserTokenTests.java @@ -15,7 +15,10 @@ package org.springframework.security.access.intercept; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +import org.junit.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.authority.AuthorityUtils; @@ -24,28 +27,31 @@ import org.springframework.security.core.authority.AuthorityUtils; * * @author Ben Alex */ -public class RunAsUserTokenTests extends TestCase { +public class RunAsUserTokenTests { + @Test public void testAuthenticationSetting() { RunAsUserToken token = new RunAsUserToken("my_password", "Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), UsernamePasswordAuthenticationToken.class); - assertTrue(token.isAuthenticated()); + assertThat(token.isAuthenticated()).isTrue(); token.setAuthenticated(false); - assertTrue(!token.isAuthenticated()); + assertThat(!token.isAuthenticated()).isTrue(); } + @Test public void testGetters() { RunAsUserToken token = new RunAsUserToken("my_password", "Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), UsernamePasswordAuthenticationToken.class); - assertEquals("Test", token.getPrincipal()); - assertEquals("Password", token.getCredentials()); - assertEquals("my_password".hashCode(), token.getKeyHash()); - assertEquals(UsernamePasswordAuthenticationToken.class, + assertThat("Test").isEqualTo(token.getPrincipal()); + assertThat("Password").isEqualTo(token.getCredentials()); + assertThat("my_password".hashCode()).isEqualTo(token.getKeyHash()); + assertThat(UsernamePasswordAuthenticationToken.class).isEqualTo( token.getOriginalAuthentication()); } + @Test public void testNoArgConstructorDoesntExist() { Class clazz = RunAsUserToken.class; @@ -54,23 +60,24 @@ public class RunAsUserTokenTests extends TestCase { fail("Should have thrown NoSuchMethodException"); } catch (NoSuchMethodException expected) { - assertTrue(true); + assertThat(true).isTrue(); } } + @Test public void testToString() { RunAsUserToken token = new RunAsUserToken("my_password", "Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), UsernamePasswordAuthenticationToken.class); - assertTrue(token.toString().lastIndexOf( - "Original Class: " - + UsernamePasswordAuthenticationToken.class.getName().toString()) != -1); + assertThat(token.toString().lastIndexOf("Original Class: " + + UsernamePasswordAuthenticationToken.class.getName().toString()) != -1).isTrue(); } // SEC-1792 + @Test public void testToStringNullOriginalAuthentication() { RunAsUserToken token = new RunAsUserToken("my_password", "Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), null); - assertTrue(token.toString().lastIndexOf("Original Class: null") != -1); + assertThat(token.toString().lastIndexOf("Original Class: null") != -1).isTrue(); } } diff --git a/core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityMetadataSourceAdvisorTests.java b/core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityMetadataSourceAdvisorTests.java index 25d09fff68..5bca02d93a 100644 --- a/core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityMetadataSourceAdvisorTests.java +++ b/core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityMetadataSourceAdvisorTests.java @@ -15,15 +15,13 @@ package org.springframework.security.access.intercept.aopalliance; - import static org.assertj.core.api.Assertions.assertThat; - -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import java.lang.reflect.Method; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.security.TargetObject; import org.springframework.security.access.SecurityConfig; import org.springframework.security.access.method.MethodSecurityMetadataSource; @@ -33,10 +31,11 @@ import org.springframework.security.access.method.MethodSecurityMetadataSource; * * @author Ben Alex */ -public class MethodSecurityMetadataSourceAdvisorTests extends TestCase { +public class MethodSecurityMetadataSourceAdvisorTests { + // ~ Methods // ======================================================================================================== - + @Test public void testAdvisorReturnsFalseWhenMethodInvocationNotDefined() throws Exception { Class clazz = TargetObject.class; Method method = clazz.getMethod("makeLowerCase", new Class[] { String.class }); @@ -45,9 +44,11 @@ public class MethodSecurityMetadataSourceAdvisorTests extends TestCase { when(mds.getAttributes(method, clazz)).thenReturn(null); MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor( "", mds, ""); - assertThat(advisor.getPointcut().getMethodMatcher().matches(method, clazz)).isFalse(); + assertThat(advisor.getPointcut().getMethodMatcher().matches(method, + clazz)).isFalse(); } + @Test public void testAdvisorReturnsTrueWhenMethodInvocationIsDefined() throws Exception { Class clazz = TargetObject.class; Method method = clazz.getMethod("countLength", new Class[] { String.class }); @@ -57,6 +58,7 @@ public class MethodSecurityMetadataSourceAdvisorTests extends TestCase { SecurityConfig.createList("ROLE_A")); MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor( "", mds, ""); - assertThat(advisor.getPointcut().getMethodMatcher().matches(method, clazz)).isTrue(); + assertThat( + advisor.getPointcut().getMethodMatcher().matches(method, clazz)).isTrue(); } } diff --git a/core/src/test/java/org/springframework/security/access/vote/AbstractAccessDecisionManagerTests.java b/core/src/test/java/org/springframework/security/access/vote/AbstractAccessDecisionManagerTests.java index c4af2b970b..197f99bf7a 100644 --- a/core/src/test/java/org/springframework/security/access/vote/AbstractAccessDecisionManagerTests.java +++ b/core/src/test/java/org/springframework/security/access/vote/AbstractAccessDecisionManagerTests.java @@ -16,32 +16,29 @@ package org.springframework.security.access.vote; import static org.assertj.core.api.Assertions.assertThat; - -import junit.framework.TestCase; - -import org.springframework.security.access.AccessDecisionVoter; -import org.springframework.security.access.AccessDeniedException; -import org.springframework.security.access.ConfigAttribute; -import org.springframework.security.access.SecurityConfig; -import org.springframework.security.access.vote.AbstractAccessDecisionManager; -import org.springframework.security.access.vote.RoleVoter; -import org.springframework.security.core.Authentication; +import static org.assertj.core.api.Assertions.fail; import java.util.Collection; import java.util.List; import java.util.Vector; +import org.junit.Test; +import org.springframework.security.access.AccessDecisionVoter; +import org.springframework.security.access.ConfigAttribute; +import org.springframework.security.access.SecurityConfig; +import org.springframework.security.core.Authentication; + /** * Tests {@link AbstractAccessDecisionManager}. * * @author Ben Alex */ @SuppressWarnings("unchecked") -public class AbstractAccessDecisionManagerTests extends TestCase { +public class AbstractAccessDecisionManagerTests { // ~ Methods // ======================================================================================================== - + @Test public void testAllowIfAccessDecisionManagerDefaults() { List list = new Vector(); DenyAgainVoter denyVoter = new DenyAgainVoter(); @@ -52,6 +49,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase { assertThat(mock.isAllowIfAllAbstainDecisions()).isTrue(); // changed } + @Test public void testDelegatesSupportsClassRequests() throws Exception { List list = new Vector(); list.add(new DenyVoter()); @@ -63,6 +61,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase { assertThat(!mock.supports(Integer.class)).isTrue(); } + @Test public void testDelegatesSupportsRequests() throws Exception { List list = new Vector(); DenyVoter voter = new DenyVoter(); @@ -79,6 +78,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase { assertThat(!mock.supports(badAttr)).isTrue(); } + @Test public void testProperlyStoresListOfVoters() throws Exception { List list = new Vector(); DenyVoter voter = new DenyVoter(); @@ -89,6 +89,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase { assertThat(mock.getDecisionVoters().size()).isEqualTo(list.size()); } + @Test public void testRejectsEmptyList() throws Exception { List list = new Vector(); @@ -101,6 +102,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase { } } + @Test public void testRejectsNullVotersList() throws Exception { try { new MockDecisionManagerImpl(null); @@ -111,11 +113,13 @@ public class AbstractAccessDecisionManagerTests extends TestCase { } } + @Test public void testRoleVoterAlwaysReturnsTrueToSupports() { RoleVoter rv = new RoleVoter(); assertThat(rv.supports(String.class)).isTrue(); } + @Test public void testWillNotStartIfDecisionVotersNotSet() throws Exception { try { new MockDecisionManagerImpl(null); @@ -130,6 +134,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase { // ================================================================================================== private class MockDecisionManagerImpl extends AbstractAccessDecisionManager { + protected MockDecisionManagerImpl( List> decisionVoters) { super(decisionVoters); @@ -141,6 +146,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase { } private class MockStringOnlyVoter implements AccessDecisionVoter { + public boolean supports(Class clazz) { return String.class.isAssignableFrom(clazz); } diff --git a/core/src/test/java/org/springframework/security/access/vote/AuthenticatedVoterTests.java b/core/src/test/java/org/springframework/security/access/vote/AuthenticatedVoterTests.java index 057fc28de6..51411df572 100644 --- a/core/src/test/java/org/springframework/security/access/vote/AuthenticatedVoterTests.java +++ b/core/src/test/java/org/springframework/security/access/vote/AuthenticatedVoterTests.java @@ -16,15 +16,14 @@ package org.springframework.security.access.vote; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.List; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; -import org.springframework.security.access.vote.AuthenticatedVoter; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.RememberMeAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -36,7 +35,7 @@ import org.springframework.security.core.authority.AuthorityUtils; * * @author Ben Alex */ -public class AuthenticatedVoterTests extends TestCase { +public class AuthenticatedVoterTests { private Authentication createAnonymous() { return new AnonymousAuthenticationToken("ignored", "ignored", @@ -53,42 +52,46 @@ public class AuthenticatedVoterTests extends TestCase { AuthorityUtils.createAuthorityList("ignored")); } + @Test public void testAnonymousWorks() { AuthenticatedVoter voter = new AuthenticatedVoter(); - List def = SecurityConfig - .createList(AuthenticatedVoter.IS_AUTHENTICATED_ANONYMOUSLY); - assertEquals(AccessDecisionVoter.ACCESS_GRANTED, + List def = SecurityConfig.createList( + AuthenticatedVoter.IS_AUTHENTICATED_ANONYMOUSLY); + assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo( voter.vote(createAnonymous(), null, def)); - assertEquals(AccessDecisionVoter.ACCESS_GRANTED, + assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo( voter.vote(createRememberMe(), null, def)); - assertEquals(AccessDecisionVoter.ACCESS_GRANTED, + assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo( voter.vote(createFullyAuthenticated(), null, def)); } + @Test public void testFullyWorks() { AuthenticatedVoter voter = new AuthenticatedVoter(); - List def = SecurityConfig - .createList(AuthenticatedVoter.IS_AUTHENTICATED_FULLY); - assertEquals(AccessDecisionVoter.ACCESS_DENIED, + List def = SecurityConfig.createList( + AuthenticatedVoter.IS_AUTHENTICATED_FULLY); + assertThat(AccessDecisionVoter.ACCESS_DENIED).isEqualTo( voter.vote(createAnonymous(), null, def)); - assertEquals(AccessDecisionVoter.ACCESS_DENIED, + assertThat(AccessDecisionVoter.ACCESS_DENIED).isEqualTo( voter.vote(createRememberMe(), null, def)); - assertEquals(AccessDecisionVoter.ACCESS_GRANTED, + assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo( voter.vote(createFullyAuthenticated(), null, def)); } + @Test public void testRememberMeWorks() { AuthenticatedVoter voter = new AuthenticatedVoter(); - List def = SecurityConfig - .createList(AuthenticatedVoter.IS_AUTHENTICATED_REMEMBERED); - assertEquals(AccessDecisionVoter.ACCESS_DENIED, + List def = SecurityConfig.createList( + AuthenticatedVoter.IS_AUTHENTICATED_REMEMBERED); + assertThat(AccessDecisionVoter.ACCESS_DENIED).isEqualTo( voter.vote(createAnonymous(), null, def)); - assertEquals(AccessDecisionVoter.ACCESS_GRANTED, + assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo( voter.vote(createRememberMe(), null, def)); - assertEquals(AccessDecisionVoter.ACCESS_GRANTED, + assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo( voter.vote(createFullyAuthenticated(), null, def)); } + @Test public void testSetterRejectsNull() { AuthenticatedVoter voter = new AuthenticatedVoter(); @@ -101,15 +104,16 @@ public class AuthenticatedVoterTests extends TestCase { } } + @Test public void testSupports() { AuthenticatedVoter voter = new AuthenticatedVoter(); assertThat(voter.supports(String.class)).isTrue(); - assertTrue(voter.supports(new SecurityConfig( - AuthenticatedVoter.IS_AUTHENTICATED_ANONYMOUSLY))); - assertTrue(voter.supports(new SecurityConfig( - AuthenticatedVoter.IS_AUTHENTICATED_FULLY))); - assertTrue(voter.supports(new SecurityConfig( - AuthenticatedVoter.IS_AUTHENTICATED_REMEMBERED))); + assertThat(voter.supports(new SecurityConfig( + AuthenticatedVoter.IS_AUTHENTICATED_ANONYMOUSLY))).isTrue(); + assertThat(voter.supports( + new SecurityConfig(AuthenticatedVoter.IS_AUTHENTICATED_FULLY))).isTrue(); + assertThat(voter.supports(new SecurityConfig( + AuthenticatedVoter.IS_AUTHENTICATED_REMEMBERED))).isTrue(); assertThat(voter.supports(new SecurityConfig("FOO"))).isFalse(); } } diff --git a/core/src/test/java/org/springframework/security/access/vote/UnanimousBasedTests.java b/core/src/test/java/org/springframework/security/access/vote/UnanimousBasedTests.java index 02e0aa18aa..b721f23d6f 100644 --- a/core/src/test/java/org/springframework/security/access/vote/UnanimousBasedTests.java +++ b/core/src/test/java/org/springframework/security/access/vote/UnanimousBasedTests.java @@ -16,18 +16,16 @@ package org.springframework.security.access.vote; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.List; import java.util.Vector; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; -import org.springframework.security.access.vote.RoleVoter; -import org.springframework.security.access.vote.UnanimousBased; import org.springframework.security.authentication.TestingAuthenticationToken; /** @@ -35,7 +33,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken; * * @author Ben Alex */ -public class UnanimousBasedTests extends TestCase { +public class UnanimousBasedTests { // ~ Methods // ======================================================================================================== @@ -73,13 +71,14 @@ public class UnanimousBasedTests extends TestCase { "FOOBAR_2"); } + @Test public void testOneAffirmativeVoteOneDenyVoteOneAbstainVoteDeniesAccess() throws Exception { TestingAuthenticationToken auth = makeTestToken(); UnanimousBased mgr = makeDecisionManager(); - List config = SecurityConfig.createList(new String[] { "ROLE_1", - "DENY_FOR_SURE" }); + List config = SecurityConfig.createList( + new String[] { "ROLE_1", "DENY_FOR_SURE" }); try { mgr.decide(auth, new Object(), config); @@ -89,6 +88,7 @@ public class UnanimousBasedTests extends TestCase { } } + @Test public void testOneAffirmativeVoteTwoAbstainVotesGrantsAccess() throws Exception { TestingAuthenticationToken auth = makeTestToken(); UnanimousBased mgr = makeDecisionManager(); @@ -98,6 +98,7 @@ public class UnanimousBasedTests extends TestCase { mgr.decide(auth, new Object(), config); } + @Test public void testOneDenyVoteTwoAbstainVotesDeniesAccess() throws Exception { TestingAuthenticationToken auth = makeTestToken(); UnanimousBased mgr = makeDecisionManager(); @@ -112,16 +113,18 @@ public class UnanimousBasedTests extends TestCase { } } + @Test public void testRoleVoterPrefixObserved() throws Exception { TestingAuthenticationToken auth = makeTestTokenWithFooBarPrefix(); UnanimousBased mgr = makeDecisionManagerWithFooBarPrefix(); - List config = SecurityConfig.createList(new String[] { - "FOOBAR_1", "FOOBAR_2" }); + List config = SecurityConfig.createList( + new String[] { "FOOBAR_1", "FOOBAR_2" }); mgr.decide(auth, new Object(), config); } + @Test public void testThreeAbstainVotesDeniesAccessWithDefault() throws Exception { TestingAuthenticationToken auth = makeTestToken(); UnanimousBased mgr = makeDecisionManager(); @@ -138,6 +141,7 @@ public class UnanimousBasedTests extends TestCase { } } + @Test public void testThreeAbstainVotesGrantsAccessWithoutDefault() throws Exception { TestingAuthenticationToken auth = makeTestToken(); UnanimousBased mgr = makeDecisionManager(); @@ -149,12 +153,13 @@ public class UnanimousBasedTests extends TestCase { mgr.decide(auth, new Object(), config); } + @Test public void testTwoAffirmativeVotesTwoAbstainVotesGrantsAccess() throws Exception { TestingAuthenticationToken auth = makeTestToken(); UnanimousBased mgr = makeDecisionManager(); - List config = SecurityConfig.createList(new String[] { "ROLE_1", - "ROLE_2" }); + List config = SecurityConfig.createList( + new String[] { "ROLE_1", "ROLE_2" }); mgr.decide(auth, new Object(), config); } diff --git a/core/src/test/java/org/springframework/security/authentication/AuthenticationTrustResolverImplTests.java b/core/src/test/java/org/springframework/security/authentication/AuthenticationTrustResolverImplTests.java index 210f1825ef..f0608bce59 100644 --- a/core/src/test/java/org/springframework/security/authentication/AuthenticationTrustResolverImplTests.java +++ b/core/src/test/java/org/springframework/security/authentication/AuthenticationTrustResolverImplTests.java @@ -17,12 +17,7 @@ package org.springframework.security.authentication; import static org.assertj.core.api.Assertions.assertThat; -import junit.framework.TestCase; - -import org.springframework.security.authentication.AnonymousAuthenticationToken; -import org.springframework.security.authentication.AuthenticationTrustResolverImpl; -import org.springframework.security.authentication.RememberMeAuthenticationToken; -import org.springframework.security.authentication.TestingAuthenticationToken; +import org.junit.Test; import org.springframework.security.core.authority.AuthorityUtils; /** @@ -31,38 +26,42 @@ import org.springframework.security.core.authority.AuthorityUtils; * * @author Ben Alex */ -public class AuthenticationTrustResolverImplTests extends TestCase { +public class AuthenticationTrustResolverImplTests { // ~ Methods // ======================================================================================================== - + @Test public void testCorrectOperationIsAnonymous() { AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl(); - assertTrue(trustResolver.isAnonymous(new AnonymousAuthenticationToken("ignored", - "ignored", AuthorityUtils.createAuthorityList("ignored")))); - assertFalse(trustResolver.isAnonymous(new TestingAuthenticationToken("ignored", - "ignored", AuthorityUtils.createAuthorityList("ignored")))); + assertThat(trustResolver.isAnonymous(new AnonymousAuthenticationToken("ignored", + "ignored", AuthorityUtils.createAuthorityList("ignored")))).isTrue(); + assertThat(trustResolver.isAnonymous(new TestingAuthenticationToken("ignored", + "ignored", AuthorityUtils.createAuthorityList("ignored")))).isFalse(); } + @Test public void testCorrectOperationIsRememberMe() { AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl(); - assertTrue(trustResolver.isRememberMe(new RememberMeAuthenticationToken( - "ignored", "ignored", AuthorityUtils.createAuthorityList("ignored")))); - assertFalse(trustResolver.isAnonymous(new TestingAuthenticationToken("ignored", - "ignored", AuthorityUtils.createAuthorityList("ignored")))); + assertThat(trustResolver.isRememberMe(new RememberMeAuthenticationToken("ignored", + "ignored", AuthorityUtils.createAuthorityList("ignored")))).isTrue(); + assertThat(trustResolver.isAnonymous(new TestingAuthenticationToken("ignored", + "ignored", AuthorityUtils.createAuthorityList("ignored")))).isFalse(); } + @Test public void testGettersSetters() { AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl(); - assertEquals(AnonymousAuthenticationToken.class, + assertThat(AnonymousAuthenticationToken.class).isEqualTo( trustResolver.getAnonymousClass()); trustResolver.setAnonymousClass(TestingAuthenticationToken.class); - assertThat(trustResolver.getAnonymousClass()).isEqualTo(TestingAuthenticationToken.class); + assertThat(trustResolver.getAnonymousClass()).isEqualTo( + TestingAuthenticationToken.class); - assertEquals(RememberMeAuthenticationToken.class, + assertThat(RememberMeAuthenticationToken.class).isEqualTo( trustResolver.getRememberMeClass()); trustResolver.setRememberMeClass(TestingAuthenticationToken.class); - assertThat(trustResolver.getRememberMeClass()).isEqualTo(TestingAuthenticationToken.class); + assertThat(trustResolver.getRememberMeClass()).isEqualTo( + TestingAuthenticationToken.class); } } diff --git a/core/src/test/java/org/springframework/security/authentication/TestingAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/TestingAuthenticationProviderTests.java index 6e3ee79eb6..f197110738 100644 --- a/core/src/test/java/org/springframework/security/authentication/TestingAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/TestingAuthenticationProviderTests.java @@ -17,10 +17,7 @@ package org.springframework.security.authentication; import static org.assertj.core.api.Assertions.assertThat; -import junit.framework.TestCase; - -import org.springframework.security.authentication.TestingAuthenticationProvider; -import org.springframework.security.authentication.TestingAuthenticationToken; +import org.junit.Test; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; @@ -29,8 +26,9 @@ import org.springframework.security.core.authority.AuthorityUtils; * * @author Ben Alex */ -public class TestingAuthenticationProviderTests extends TestCase { +public class TestingAuthenticationProviderTests { + @Test public void testAuthenticates() { TestingAuthenticationProvider provider = new TestingAuthenticationProvider(); TestingAuthenticationToken token = new TestingAuthenticationToken("Test", @@ -42,9 +40,12 @@ public class TestingAuthenticationProviderTests extends TestCase { TestingAuthenticationToken castResult = (TestingAuthenticationToken) result; assertThat(castResult.getPrincipal()).isEqualTo("Test"); assertThat(castResult.getCredentials()).isEqualTo("Password"); - assertThat(AuthorityUtils.authorityListToSet(castResult.getAuthorities())).contains("ROLE_ONE","ROLE_TWO"); + assertThat( + AuthorityUtils.authorityListToSet(castResult.getAuthorities())).contains( + "ROLE_ONE", "ROLE_TWO"); } + @Test public void testSupports() { TestingAuthenticationProvider provider = new TestingAuthenticationProvider(); assertThat(provider.supports(TestingAuthenticationToken.class)).isTrue(); diff --git a/core/src/test/java/org/springframework/security/authentication/UsernamePasswordAuthenticationTokenTests.java b/core/src/test/java/org/springframework/security/authentication/UsernamePasswordAuthenticationTokenTests.java index 3c756611a9..485ebc9a17 100644 --- a/core/src/test/java/org/springframework/security/authentication/UsernamePasswordAuthenticationTokenTests.java +++ b/core/src/test/java/org/springframework/security/authentication/UsernamePasswordAuthenticationTokenTests.java @@ -16,11 +16,9 @@ package org.springframework.security.authentication; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; import static org.assertj.core.api.Assertions.fail; import org.junit.Test; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.authority.AuthorityUtils; /** @@ -69,8 +67,8 @@ public class UsernamePasswordAuthenticationTokenTests { @Test public void gettersReturnCorrectData() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( - "Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE", - "ROLE_TWO")); + "Test", "Password", + AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); assertThat(token.getPrincipal()).isEqualTo("Test"); assertThat(token.getCredentials()).isEqualTo("Password"); assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities()).contains( diff --git a/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationTokenTests.java b/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationTokenTests.java index 4be3379248..fe3ee281c5 100644 --- a/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationTokenTests.java +++ b/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationTokenTests.java @@ -16,11 +16,11 @@ package org.springframework.security.authentication.anonymous; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.List; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.GrantedAuthority; @@ -31,14 +31,14 @@ import org.springframework.security.core.authority.AuthorityUtils; * * @author Ben Alex */ -public class AnonymousAuthenticationTokenTests extends TestCase { +public class AnonymousAuthenticationTokenTests { - private final static List ROLES_12 = AuthorityUtils - .createAuthorityList("ROLE_ONE", "ROLE_TWO"); + private final static List ROLES_12 = AuthorityUtils.createAuthorityList( + "ROLE_ONE", "ROLE_TWO"); // ~ Methods // ======================================================================================================== - + @Test public void testConstructorRejectsNulls() { try { new AnonymousAuthenticationToken(null, "Test", ROLES_12); @@ -55,20 +55,23 @@ public class AnonymousAuthenticationTokenTests extends TestCase { } try { - new AnonymousAuthenticationToken("key", "Test", (List) null); + new AnonymousAuthenticationToken("key", "Test", + (List) null); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { - new AnonymousAuthenticationToken("key", "Test", AuthorityUtils.NO_AUTHORITIES); + new AnonymousAuthenticationToken("key", "Test", + AuthorityUtils.NO_AUTHORITIES); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } + @Test public void testEqualsWhenEqual() { AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test", ROLES_12); @@ -78,6 +81,7 @@ public class AnonymousAuthenticationTokenTests extends TestCase { assertThat(token2).isEqualTo(token1); } + @Test public void testGetters() { AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key", "Test", ROLES_12); @@ -86,10 +90,11 @@ public class AnonymousAuthenticationTokenTests extends TestCase { assertThat(token.getPrincipal()).isEqualTo("Test"); assertThat(token.getCredentials()).isEqualTo(""); assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains( - "ROLE_ONE","ROLE_TWO"); + "ROLE_ONE", "ROLE_TWO"); assertThat(token.isAuthenticated()).isTrue(); } + @Test public void testNoArgConstructorDoesntExist() { Class clazz = AnonymousAuthenticationToken.class; @@ -101,6 +106,7 @@ public class AnonymousAuthenticationTokenTests extends TestCase { } } + @Test public void testNotEqualsDueToAbstractParentEqualsCheck() { AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test", ROLES_12); @@ -110,6 +116,7 @@ public class AnonymousAuthenticationTokenTests extends TestCase { assertThat(token1.equals(token2)).isFalse(); } + @Test public void testNotEqualsDueToDifferentAuthenticationClass() { AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test", ROLES_12); @@ -119,6 +126,7 @@ public class AnonymousAuthenticationTokenTests extends TestCase { assertThat(token1.equals(token2)).isFalse(); } + @Test public void testNotEqualsDueToKey() { AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key", "Test", ROLES_12); @@ -129,6 +137,7 @@ public class AnonymousAuthenticationTokenTests extends TestCase { assertThat(token1.equals(token2)).isFalse(); } + @Test public void testSetAuthenticatedIgnored() { AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key", "Test", ROLES_12); diff --git a/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java index a87cb1954f..ca92683fd5 100644 --- a/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java @@ -16,7 +16,7 @@ package org.springframework.security.authentication.dao; import static org.assertj.core.api.Assertions.assertThat; - +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.mock; @@ -28,8 +28,7 @@ import java.security.SecureRandom; import java.util.ArrayList; import java.util.List; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.dao.DataRetrievalFailureException; import org.springframework.security.authentication.AccountExpiredException; import org.springframework.security.authentication.AuthenticationServiceException; @@ -59,13 +58,14 @@ import org.springframework.security.crypto.password.PasswordEncoder; * @author Ben Alex * @author Rob Winch */ -public class DaoAuthenticationProviderTests extends TestCase { - private static final List ROLES_12 = AuthorityUtils - .createAuthorityList("ROLE_ONE", "ROLE_TWO"); +public class DaoAuthenticationProviderTests { + + private static final List ROLES_12 = AuthorityUtils.createAuthorityList( + "ROLE_ONE", "ROLE_TWO"); // ~ Methods // ======================================================================================================== - + @Test public void testAuthenticateFailsForIncorrectPasswordCase() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "rod", "KOala"); @@ -83,6 +83,7 @@ public class DaoAuthenticationProviderTests extends TestCase { } } + @Test public void testReceivedBadCredentialsWhenCredentialsNotProvided() { // Test related to SEC-434 DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); @@ -100,12 +101,14 @@ public class DaoAuthenticationProviderTests extends TestCase { } } + @Test public void testAuthenticateFailsIfAccountExpired() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "peter", "opal"); DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); - provider.setUserDetailsService(new MockAuthenticationDaoUserPeterAccountExpired()); + provider.setUserDetailsService( + new MockAuthenticationDaoUserPeterAccountExpired()); provider.setUserCache(new MockUserCache()); try { @@ -117,6 +120,7 @@ public class DaoAuthenticationProviderTests extends TestCase { } } + @Test public void testAuthenticateFailsIfAccountLocked() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "peter", "opal"); @@ -134,12 +138,14 @@ public class DaoAuthenticationProviderTests extends TestCase { } } + @Test public void testAuthenticateFailsIfCredentialsExpired() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "peter", "opal"); DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); - provider.setUserDetailsService(new MockAuthenticationDaoUserPeterCredentialsExpired()); + provider.setUserDetailsService( + new MockAuthenticationDaoUserPeterCredentialsExpired()); provider.setUserCache(new MockUserCache()); try { @@ -163,6 +169,7 @@ public class DaoAuthenticationProviderTests extends TestCase { } } + @Test public void testAuthenticateFailsIfUserDisabled() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "peter", "opal"); @@ -180,6 +187,7 @@ public class DaoAuthenticationProviderTests extends TestCase { } } + @Test public void testAuthenticateFailsWhenAuthenticationDaoHasBackendFailure() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "rod", "koala"); @@ -196,6 +204,7 @@ public class DaoAuthenticationProviderTests extends TestCase { } } + @Test public void testAuthenticateFailsWithEmptyUsername() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( null, "koala"); @@ -213,6 +222,7 @@ public class DaoAuthenticationProviderTests extends TestCase { } } + @Test public void testAuthenticateFailsWithInvalidPassword() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "rod", "INVALID_PASSWORD"); @@ -230,6 +240,7 @@ public class DaoAuthenticationProviderTests extends TestCase { } } + @Test public void testAuthenticateFailsWithInvalidUsernameAndHideUserNotFoundExceptionFalse() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "INVALID_USER", "koala"); @@ -249,6 +260,7 @@ public class DaoAuthenticationProviderTests extends TestCase { } } + @Test public void testAuthenticateFailsWithInvalidUsernameAndHideUserNotFoundExceptionsWithDefaultOfTrue() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "INVALID_USER", "koala"); @@ -267,6 +279,7 @@ public class DaoAuthenticationProviderTests extends TestCase { } } + @Test public void testAuthenticateFailsWithMixedCaseUsernameIfDefaultChanged() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "RoD", "koala"); @@ -284,6 +297,7 @@ public class DaoAuthenticationProviderTests extends TestCase { } } + @Test public void testAuthenticates() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "rod", "koala"); @@ -302,11 +316,13 @@ public class DaoAuthenticationProviderTests extends TestCase { UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result; assertThat(castResult.getPrincipal().getClass()).isEqualTo(User.class); assertThat(castResult.getCredentials()).isEqualTo("koala"); - assertThat(AuthorityUtils.authorityListToSet(castResult.getAuthorities())) - .contains("ROLE_ONE","ROLE_TWO"); + assertThat( + AuthorityUtils.authorityListToSet(castResult.getAuthorities())).contains( + "ROLE_ONE", "ROLE_TWO"); assertThat(castResult.getDetails()).isEqualTo("192.168.0.1"); } + @Test public void testAuthenticatesASecondTime() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "rod", "koala"); @@ -331,6 +347,7 @@ public class DaoAuthenticationProviderTests extends TestCase { assertThat(result2.getCredentials()).isEqualTo(result.getCredentials()); } + @Test public void testAuthenticatesWhenASaltIsUsed() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "rod", "koala"); @@ -353,10 +370,11 @@ public class DaoAuthenticationProviderTests extends TestCase { // We expect original credentials user submitted to be returned assertThat(result.getCredentials()).isEqualTo("koala"); - assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities())) - .contains("ROLE_ONE","ROLE_TWO"); + assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities())).contains( + "ROLE_ONE", "ROLE_TWO"); } + @Test public void testAuthenticatesWithForcePrincipalAsString() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "rod", "koala"); @@ -377,6 +395,7 @@ public class DaoAuthenticationProviderTests extends TestCase { assertThat(castResult.getPrincipal()).isEqualTo("rod"); } + @Test public void testDetectsNullBeingReturnedFromAuthenticationDao() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "rod", "koala"); @@ -389,28 +408,33 @@ public class DaoAuthenticationProviderTests extends TestCase { fail("Should have thrown AuthenticationServiceException"); } catch (AuthenticationServiceException expected) { - assertEquals( - "UserDetailsService returned null, which is an interface contract violation", - expected.getMessage()); + assertThat( + "UserDetailsService returned null, which is an interface contract violation").isEqualTo( + expected.getMessage()); } } + @Test public void testGettersSetters() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setPasswordEncoder(new ShaPasswordEncoder()); - assertThat(provider.getPasswordEncoder().getClass()).isEqualTo(ShaPasswordEncoder.class); + assertThat(provider.getPasswordEncoder().getClass()).isEqualTo( + ShaPasswordEncoder.class); provider.setSaltSource(new SystemWideSaltSource()); - assertThat(provider.getSaltSource().getClass()).isEqualTo(SystemWideSaltSource.class); + assertThat(provider.getSaltSource().getClass()).isEqualTo( + SystemWideSaltSource.class); provider.setUserCache(new EhCacheBasedUserCache()); - assertThat(provider.getUserCache().getClass()).isEqualTo(EhCacheBasedUserCache.class); + assertThat(provider.getUserCache().getClass()).isEqualTo( + EhCacheBasedUserCache.class); assertThat(provider.isForcePrincipalAsString()).isFalse(); provider.setForcePrincipalAsString(true); assertThat(provider.isForcePrincipalAsString()).isTrue(); } + @Test public void testGoesBackToAuthenticationDaoToObtainLatestPasswordIfCachedPasswordSeemsIncorrect() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "rod", "koala"); @@ -436,9 +460,11 @@ public class DaoAuthenticationProviderTests extends TestCase { // To get this far, the new password was accepted // Check the cache was updated - assertThat(cache.getUserFromCache("rod").getPassword()).isEqualTo("easternLongNeckTurtle"); + assertThat(cache.getUserFromCache("rod").getPassword()).isEqualTo( + "easternLongNeckTurtle"); } + @Test public void testStartupFailsIfNoAuthenticationDao() throws Exception { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); @@ -451,6 +477,7 @@ public class DaoAuthenticationProviderTests extends TestCase { } } + @Test public void testStartupFailsIfNoUserCacheSet() throws Exception { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setUserDetailsService(new MockAuthenticationDaoUserrod()); @@ -466,6 +493,7 @@ public class DaoAuthenticationProviderTests extends TestCase { } } + @Test public void testStartupSuccess() throws Exception { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); UserDetailsService userDetailsService = new MockAuthenticationDaoUserrod(); @@ -476,6 +504,7 @@ public class DaoAuthenticationProviderTests extends TestCase { } + @Test public void testSupports() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); assertThat(provider.supports(UsernamePasswordAuthenticationToken.class)).isTrue(); @@ -483,6 +512,7 @@ public class DaoAuthenticationProviderTests extends TestCase { } // SEC-2056 + @Test public void testUserNotFoundEncodesPassword() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "missing", "koala"); @@ -504,6 +534,7 @@ public class DaoAuthenticationProviderTests extends TestCase { verify(encoder).matches(isA(String.class), isA(String.class)); } + @Test public void testUserNotFoundBCryptPasswordEncoder() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "missing", "koala"); @@ -512,8 +543,8 @@ public class DaoAuthenticationProviderTests extends TestCase { provider.setHideUserNotFoundExceptions(false); provider.setPasswordEncoder(encoder); MockAuthenticationDaoUserrod userDetailsService = new MockAuthenticationDaoUserrod(); - userDetailsService.password = encoder.encode((CharSequence) token - .getCredentials()); + userDetailsService.password = encoder.encode( + (CharSequence) token.getCredentials()); provider.setUserDetailsService(userDetailsService); try { provider.authenticate(token); @@ -523,6 +554,7 @@ public class DaoAuthenticationProviderTests extends TestCase { } } + @Test public void testUserNotFoundDefaultEncoder() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "missing", null); @@ -552,8 +584,8 @@ public class DaoAuthenticationProviderTests extends TestCase { provider.setHideUserNotFoundExceptions(false); provider.setPasswordEncoder(encoder); MockAuthenticationDaoUserrod userDetailsService = new MockAuthenticationDaoUserrod(); - userDetailsService.password = encoder.encode((CharSequence) foundUser - .getCredentials()); + userDetailsService.password = encoder.encode( + (CharSequence) foundUser.getCredentials()); provider.setUserDetailsService(userDetailsService); int sampleSize = 100; @@ -579,9 +611,10 @@ public class DaoAuthenticationProviderTests extends TestCase { double userFoundAvg = avg(userFoundTimes); double userNotFoundAvg = avg(userNotFoundTimes); - assertTrue("User not found average " + userNotFoundAvg - + " should be within 3ms of user found average " + userFoundAvg, - Math.abs(userNotFoundAvg - userFoundAvg) <= 3); + assertThat(Math.abs(userNotFoundAvg - userFoundAvg) <= 3).withFailMessage( + "User not found average " + userNotFoundAvg + + " should be within 3ms of user found average " + + userFoundAvg).isTrue(); } private double avg(List counts) { @@ -592,6 +625,7 @@ public class DaoAuthenticationProviderTests extends TestCase { return sum / counts.size(); } + @Test public void testUserNotFoundNullCredentials() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "missing", null); @@ -614,12 +648,15 @@ public class DaoAuthenticationProviderTests extends TestCase { // ================================================================================================== private class MockAuthenticationDaoReturnsNull implements UserDetailsService { + public UserDetails loadUserByUsername(String username) { return null; } } - private class MockAuthenticationDaoSimulateBackendError implements UserDetailsService { + private class MockAuthenticationDaoSimulateBackendError + implements UserDetailsService { + public UserDetails loadUserByUsername(String username) { throw new DataRetrievalFailureException( "This mock simulator is designed to fail"); @@ -627,6 +664,7 @@ public class DaoAuthenticationProviderTests extends TestCase { } private class MockAuthenticationDaoUserrod implements UserDetailsService { + private String password = "koala"; public UserDetails loadUserByUsername(String username) { @@ -644,10 +682,11 @@ public class DaoAuthenticationProviderTests extends TestCase { } private class MockAuthenticationDaoUserrodWithSalt implements UserDetailsService { + public UserDetails loadUserByUsername(String username) { if ("rod".equals(username)) { - return new User("rod", "koala{SYSTEM_SALT_VALUE}", true, true, true, - true, ROLES_12); + return new User("rod", "koala{SYSTEM_SALT_VALUE}", true, true, true, true, + ROLES_12); } else { throw new UsernameNotFoundException("Could not find: " + username); @@ -656,6 +695,7 @@ public class DaoAuthenticationProviderTests extends TestCase { } private class MockAuthenticationDaoUserPeter implements UserDetailsService { + public UserDetails loadUserByUsername(String username) { if ("peter".equals(username)) { return new User("peter", "opal", false, true, true, true, ROLES_12); @@ -666,8 +706,9 @@ public class DaoAuthenticationProviderTests extends TestCase { } } - private class MockAuthenticationDaoUserPeterAccountExpired implements - UserDetailsService { + private class MockAuthenticationDaoUserPeterAccountExpired + implements UserDetailsService { + public UserDetails loadUserByUsername(String username) { if ("peter".equals(username)) { return new User("peter", "opal", true, false, true, true, ROLES_12); @@ -678,8 +719,9 @@ public class DaoAuthenticationProviderTests extends TestCase { } } - private class MockAuthenticationDaoUserPeterAccountLocked implements - UserDetailsService { + private class MockAuthenticationDaoUserPeterAccountLocked + implements UserDetailsService { + public UserDetails loadUserByUsername(String username) { if ("peter".equals(username)) { return new User("peter", "opal", true, true, true, false, ROLES_12); @@ -690,8 +732,9 @@ public class DaoAuthenticationProviderTests extends TestCase { } } - private class MockAuthenticationDaoUserPeterCredentialsExpired implements - UserDetailsService { + private class MockAuthenticationDaoUserPeterCredentialsExpired + implements UserDetailsService { + public UserDetails loadUserByUsername(String username) { if ("peter".equals(username)) { return new User("peter", "opal", true, true, false, true, ROLES_12); diff --git a/core/src/test/java/org/springframework/security/authentication/dao/salt/ReflectionSaltSourceTests.java b/core/src/test/java/org/springframework/security/authentication/dao/salt/ReflectionSaltSourceTests.java index 1c2dc6ae72..c8c42bfa52 100644 --- a/core/src/test/java/org/springframework/security/authentication/dao/salt/ReflectionSaltSourceTests.java +++ b/core/src/test/java/org/springframework/security/authentication/dao/salt/ReflectionSaltSourceTests.java @@ -15,7 +15,7 @@ package org.springframework.security.authentication.dao.salt; -import static junit.framework.Assert.assertEquals; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.springframework.security.authentication.AuthenticationServiceException; diff --git a/core/src/test/java/org/springframework/security/authentication/dao/salt/SystemWideSaltSourceTests.java b/core/src/test/java/org/springframework/security/authentication/dao/salt/SystemWideSaltSourceTests.java index 2c85ac4859..d733ff8326 100644 --- a/core/src/test/java/org/springframework/security/authentication/dao/salt/SystemWideSaltSourceTests.java +++ b/core/src/test/java/org/springframework/security/authentication/dao/salt/SystemWideSaltSourceTests.java @@ -16,17 +16,17 @@ package org.springframework.security.authentication.dao.salt; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import org.junit.Test; import org.springframework.security.authentication.dao.SystemWideSaltSource; -import junit.framework.TestCase; - /** * Tests {@link SystemWideSaltSource}. * * @author Ben Alex */ -public class SystemWideSaltSourceTests extends TestCase { +public class SystemWideSaltSourceTests { // ~ Constructors // =================================================================================================== @@ -34,21 +34,9 @@ public class SystemWideSaltSourceTests extends TestCase { super(); } - public SystemWideSaltSourceTests(String arg0) { - super(arg0); - } - // ~ Methods // ======================================================================================================== - - public static void main(String[] args) { - junit.textui.TestRunner.run(SystemWideSaltSourceTests.class); - } - - public final void setUp() throws Exception { - super.setUp(); - } - + @Test public void testDetectsMissingSystemWideSalt() throws Exception { SystemWideSaltSource saltSource = new SystemWideSaltSource(); @@ -61,12 +49,14 @@ public class SystemWideSaltSourceTests extends TestCase { } } + @Test public void testGettersSetters() { SystemWideSaltSource saltSource = new SystemWideSaltSource(); saltSource.setSystemWideSalt("helloWorld"); assertThat(saltSource.getSystemWideSalt()).isEqualTo("helloWorld"); } + @Test public void testNormalOperation() throws Exception { SystemWideSaltSource saltSource = new SystemWideSaltSource(); saltSource.setSystemWideSalt("helloWorld"); @@ -75,6 +65,7 @@ public class SystemWideSaltSourceTests extends TestCase { } // SEC-2173 + @Test public void testToString() { String systemWideSalt = "helloWorld"; SystemWideSaltSource saltSource = new SystemWideSaltSource(); diff --git a/core/src/test/java/org/springframework/security/authentication/encoding/BasePasswordEncoderTests.java b/core/src/test/java/org/springframework/security/authentication/encoding/BasePasswordEncoderTests.java index cda4b44a06..89f8d6aa11 100644 --- a/core/src/test/java/org/springframework/security/authentication/encoding/BasePasswordEncoderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/encoding/BasePasswordEncoderTests.java @@ -15,7 +15,10 @@ package org.springframework.security.authentication.encoding; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.*; + +import org.junit.Test; + /** *

@@ -24,10 +27,11 @@ import junit.framework.TestCase; * * @author Ben Alex */ -public class BasePasswordEncoderTests extends TestCase { +public class BasePasswordEncoderTests { // ~ Methods // ======================================================================================================== + @Test public void testDemergeHandlesEmptyAndNullSalts() { MockPasswordEncoder pwd = new MockPasswordEncoder(); @@ -43,7 +47,7 @@ public class BasePasswordEncoderTests extends TestCase { assertThat(demerged[0]).isEqualTo("password"); assertThat(demerged[1]).isEqualTo(""); } - + @Test public void testDemergeWithEmptyStringIsRejected() { MockPasswordEncoder pwd = new MockPasswordEncoder(); @@ -55,7 +59,7 @@ public class BasePasswordEncoderTests extends TestCase { assertThat(expected.getMessage()).isEqualTo("Cannot pass a null or empty String"); } } - + @Test public void testDemergeWithNullIsRejected() { MockPasswordEncoder pwd = new MockPasswordEncoder(); @@ -67,7 +71,7 @@ public class BasePasswordEncoderTests extends TestCase { assertThat(expected.getMessage()).isEqualTo("Cannot pass a null or empty String"); } } - + @Test public void testMergeDemerge() { MockPasswordEncoder pwd = new MockPasswordEncoder(); @@ -78,7 +82,7 @@ public class BasePasswordEncoderTests extends TestCase { assertThat(demerged[0]).isEqualTo("password"); assertThat(demerged[1]).isEqualTo("foo"); } - + @Test public void testMergeDemergeWithDelimitersInPassword() { MockPasswordEncoder pwd = new MockPasswordEncoder(); @@ -90,7 +94,7 @@ public class BasePasswordEncoderTests extends TestCase { assertThat(demerged[0]).isEqualTo("p{ass{w{o}rd"); assertThat(demerged[1]).isEqualTo("foo"); } - + @Test public void testMergeDemergeWithNullAsPassword() { MockPasswordEncoder pwd = new MockPasswordEncoder(); @@ -101,7 +105,7 @@ public class BasePasswordEncoderTests extends TestCase { assertThat(demerged[0]).isEqualTo(""); assertThat(demerged[1]).isEqualTo("foo"); } - + @Test public void testStrictMergeRejectsDelimitersInSalt1() { MockPasswordEncoder pwd = new MockPasswordEncoder(); @@ -113,7 +117,7 @@ public class BasePasswordEncoderTests extends TestCase { assertThat(expected.getMessage()).isEqualTo("Cannot use { or } in salt.toString()"); } } - + @Test public void testStrictMergeRejectsDelimitersInSalt2() { MockPasswordEncoder pwd = new MockPasswordEncoder(); @@ -147,3 +151,4 @@ public class BasePasswordEncoderTests extends TestCase { } } } + diff --git a/core/src/test/java/org/springframework/security/authentication/encoding/Md4PasswordEncoderTests.java b/core/src/test/java/org/springframework/security/authentication/encoding/Md4PasswordEncoderTests.java index de4bdc3172..cb4f8564d8 100644 --- a/core/src/test/java/org/springframework/security/authentication/encoding/Md4PasswordEncoderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/encoding/Md4PasswordEncoderTests.java @@ -12,14 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.security.authentication.encoding; -import org.springframework.security.authentication.encoding.Md4PasswordEncoder; +import static org.assertj.core.api.Assertions.assertThat; -import junit.framework.TestCase; +import org.junit.Test; -public class Md4PasswordEncoderTests extends TestCase { +public class Md4PasswordEncoderTests { + @Test public void testEncodeUnsaltedPassword() { Md4PasswordEncoder md4 = new Md4PasswordEncoder(); md4.setEncodeHashAsBase64(true); @@ -27,6 +29,7 @@ public class Md4PasswordEncoderTests extends TestCase { assertThat(encodedPassword).isEqualTo("8zobtq72iAt0W6KNqavGwg=="); } + @Test public void testEncodeSaltedPassword() { Md4PasswordEncoder md4 = new Md4PasswordEncoder(); md4.setEncodeHashAsBase64(true); @@ -34,6 +37,7 @@ public class Md4PasswordEncoderTests extends TestCase { assertThat(encodedPassword).isEqualTo("ZplT6P5Kv6Rlu6W4FIoYNA=="); } + @Test public void testEncodeNullPassword() { Md4PasswordEncoder md4 = new Md4PasswordEncoder(); md4.setEncodeHashAsBase64(true); @@ -41,6 +45,7 @@ public class Md4PasswordEncoderTests extends TestCase { assertThat(encodedPassword).isEqualTo("MdbP4NFq6TG3PFnX4MCJwA=="); } + @Test public void testEncodeEmptyPassword() { Md4PasswordEncoder md4 = new Md4PasswordEncoder(); md4.setEncodeHashAsBase64(true); @@ -48,27 +53,33 @@ public class Md4PasswordEncoderTests extends TestCase { assertThat(encodedPassword).isEqualTo("MdbP4NFq6TG3PFnX4MCJwA=="); } + @Test public void testNonAsciiPasswordHasCorrectHash() { Md4PasswordEncoder md4 = new Md4PasswordEncoder(); String encodedPassword = md4.encodePassword("\u4F60\u597d", null); assertThat(encodedPassword).isEqualTo("a7f1196539fd1f85f754ffd185b16e6e"); } + @Test public void testIsHexPasswordValid() { Md4PasswordEncoder md4 = new Md4PasswordEncoder(); - assertThat(md4.isPasswordValid("31d6cfe0d16ae931b73c59d7e0c089c0", "", null)).isTrue(); + assertThat(md4.isPasswordValid("31d6cfe0d16ae931b73c59d7e0c089c0", "", + null)).isTrue(); } + @Test public void testIsPasswordValid() { Md4PasswordEncoder md4 = new Md4PasswordEncoder(); md4.setEncodeHashAsBase64(true); - assertThat(md4.isPasswordValid("8zobtq72iAt0W6KNqavGwg==", "ww_uni123", null)).isTrue(); + assertThat(md4.isPasswordValid("8zobtq72iAt0W6KNqavGwg==", "ww_uni123", + null)).isTrue(); } + @Test public void testIsSaltedPasswordValid() { Md4PasswordEncoder md4 = new Md4PasswordEncoder(); md4.setEncodeHashAsBase64(true); - assertTrue(md4.isPasswordValid("ZplT6P5Kv6Rlu6W4FIoYNA==", "ww_uni123", - "Alan K Stewart")); + assertThat(md4.isPasswordValid("ZplT6P5Kv6Rlu6W4FIoYNA==", "ww_uni123", + "Alan K Stewart")).isTrue(); } } diff --git a/core/src/test/java/org/springframework/security/authentication/encoding/Md5PasswordEncoderTests.java b/core/src/test/java/org/springframework/security/authentication/encoding/Md5PasswordEncoderTests.java index 2df6a0f16d..5ce785185d 100644 --- a/core/src/test/java/org/springframework/security/authentication/encoding/Md5PasswordEncoderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/encoding/Md5PasswordEncoderTests.java @@ -74,7 +74,6 @@ public class Md5PasswordEncoderTests { pe.setIterations(2); // Calculate value using: // echo -n password{salt} | openssl md5 -binary | openssl md5 - assertEquals("eb753fb0c370582b4ee01b30f304b9fc", - pe.encodePassword("password", "salt")); + assertThat(pe.encodePassword("password", "salt")).isEqualTo("eb753fb0c370582b4ee01b30f304b9fc"); } } diff --git a/core/src/test/java/org/springframework/security/authentication/encoding/PlaintextPasswordEncoderTests.java b/core/src/test/java/org/springframework/security/authentication/encoding/PlaintextPasswordEncoderTests.java index 77d5755bda..48b2e20a31 100644 --- a/core/src/test/java/org/springframework/security/authentication/encoding/PlaintextPasswordEncoderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/encoding/PlaintextPasswordEncoderTests.java @@ -15,9 +15,9 @@ package org.springframework.security.authentication.encoding; -import org.springframework.security.authentication.encoding.PlaintextPasswordEncoder; +import static org.assertj.core.api.Assertions.assertThat; -import junit.framework.TestCase; +import org.junit.Test; /** *

@@ -27,10 +27,11 @@ import junit.framework.TestCase; * @author colin sampaleanu * @author Ben Alex */ -public class PlaintextPasswordEncoderTests extends TestCase { +public class PlaintextPasswordEncoderTests { + // ~ Methods // ======================================================================================================== - + @Test public void testBasicFunctionality() { PlaintextPasswordEncoder pe = new PlaintextPasswordEncoder(); @@ -59,6 +60,7 @@ public class PlaintextPasswordEncoderTests extends TestCase { assertThat(pe.isPasswordValid(encoded, badRaw, salt)).isFalse(); } + @Test public void testMergeDemerge() { PlaintextPasswordEncoder pwd = new PlaintextPasswordEncoder(); diff --git a/core/src/test/java/org/springframework/security/authentication/encoding/ShaPasswordEncoderTests.java b/core/src/test/java/org/springframework/security/authentication/encoding/ShaPasswordEncoderTests.java index 1dc7f6c71e..b51fbbf899 100644 --- a/core/src/test/java/org/springframework/security/authentication/encoding/ShaPasswordEncoderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/encoding/ShaPasswordEncoderTests.java @@ -15,9 +15,10 @@ package org.springframework.security.authentication.encoding; -import org.springframework.security.authentication.encoding.ShaPasswordEncoder; +import static org.assertj.core.api.Assertions.*; -import junit.framework.TestCase; +import org.junit.Test; +import org.springframework.security.authentication.encoding.ShaPasswordEncoder; /** *

@@ -28,10 +29,11 @@ import junit.framework.TestCase; * @author Ben Alex * @author Ray Krueger */ -public class ShaPasswordEncoderTests extends TestCase { +public class ShaPasswordEncoderTests { // ~ Methods // ======================================================================================================== + @Test public void testBasicFunctionality() { ShaPasswordEncoder pe = new ShaPasswordEncoder(); String raw = "abc123"; @@ -43,7 +45,7 @@ public class ShaPasswordEncoderTests extends TestCase { assertThat(encoded).isEqualTo("b2f50ffcbd3407fe9415c062d55f54731f340d32"); } - + @Test public void testBase64() throws Exception { ShaPasswordEncoder pe = new ShaPasswordEncoder(); pe.setEncodeHashAsBase64(true); @@ -55,17 +57,15 @@ public class ShaPasswordEncoderTests extends TestCase { assertThat(pe.isPasswordValid(encoded, badRaw, salt)).isFalse(); assertThat(encoded.length() != 40).isTrue(); } - + @Test public void test256() throws Exception { ShaPasswordEncoder pe = new ShaPasswordEncoder(256); String encoded = pe.encodePassword("abc123", null); - assertEquals("6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090", - encoded); + assertThat(encoded).isEqualTo("6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090"); String encodedWithSalt = pe.encodePassword("abc123", "THIS_IS_A_SALT"); - assertEquals("4b79b7de23eb23b78cc5ede227d532b8a51f89b2ec166f808af76b0dbedc47d7", - encodedWithSalt); + assertThat(encodedWithSalt).isEqualTo("4b79b7de23eb23b78cc5ede227d532b8a51f89b2ec166f808af76b0dbedc47d7"); } - + @Test public void testInvalidStrength() throws Exception { try { new ShaPasswordEncoder(666); diff --git a/core/src/test/java/org/springframework/security/authentication/event/AuthenticationEventTests.java b/core/src/test/java/org/springframework/security/authentication/event/AuthenticationEventTests.java index 6c615ad916..73f9ed6963 100644 --- a/core/src/test/java/org/springframework/security/authentication/event/AuthenticationEventTests.java +++ b/core/src/test/java/org/springframework/security/authentication/event/AuthenticationEventTests.java @@ -15,14 +15,12 @@ package org.springframework.security.authentication.event; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import org.junit.Test; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.authentication.event.AbstractAuthenticationEvent; -import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent; -import org.springframework.security.authentication.event.AuthenticationFailureDisabledEvent; -import org.springframework.security.authentication.event.AuthenticationSuccessEvent; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; @@ -31,7 +29,7 @@ import org.springframework.security.core.AuthenticationException; * * @author Ben Alex */ -public class AuthenticationEventTests extends TestCase { +public class AuthenticationEventTests { // ~ Methods // ======================================================================================================== @@ -43,20 +41,14 @@ public class AuthenticationEventTests extends TestCase { return authentication; } - public static void main(String[] args) { - junit.textui.TestRunner.run(AuthenticationEventTests.class); - } - - public final void setUp() throws Exception { - super.setUp(); - } - + @Test public void testAbstractAuthenticationEvent() { Authentication auth = getAuthentication(); AbstractAuthenticationEvent event = new AuthenticationSuccessEvent(auth); assertThat(event.getAuthentication()).isEqualTo(auth); } + @Test public void testAbstractAuthenticationFailureEvent() { Authentication auth = getAuthentication(); AuthenticationException exception = new DisabledException("TEST"); @@ -66,6 +58,7 @@ public class AuthenticationEventTests extends TestCase { assertThat(event.getException()).isEqualTo(exception); } + @Test public void testRejectsNullAuthentication() { AuthenticationException exception = new DisabledException("TEST"); @@ -78,6 +71,7 @@ public class AuthenticationEventTests extends TestCase { } } + @Test public void testRejectsNullAuthenticationException() { try { new AuthenticationFailureDisabledEvent(getAuthentication(), null); diff --git a/core/src/test/java/org/springframework/security/authentication/event/LoggerListenerTests.java b/core/src/test/java/org/springframework/security/authentication/event/LoggerListenerTests.java index 4b12341a0b..3207ae3274 100644 --- a/core/src/test/java/org/springframework/security/authentication/event/LoggerListenerTests.java +++ b/core/src/test/java/org/springframework/security/authentication/event/LoggerListenerTests.java @@ -15,12 +15,9 @@ package org.springframework.security.authentication.event; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.security.authentication.LockedException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.authentication.event.AuthenticationFailureDisabledEvent; -import org.springframework.security.authentication.event.LoggerListener; import org.springframework.security.core.Authentication; /** @@ -28,7 +25,7 @@ import org.springframework.security.core.Authentication; * * @author Ben Alex */ -public class LoggerListenerTests extends TestCase { +public class LoggerListenerTests { // ~ Methods // ======================================================================================================== @@ -40,14 +37,7 @@ public class LoggerListenerTests extends TestCase { return authentication; } - public static void main(String[] args) { - junit.textui.TestRunner.run(LoggerListenerTests.class); - } - - public final void setUp() throws Exception { - super.setUp(); - } - + @Test public void testLogsEvents() { AuthenticationFailureDisabledEvent event = new AuthenticationFailureDisabledEvent( getAuthentication(), new LockedException("TEST")); diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java index 660e282893..db68e7fd51 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java @@ -94,8 +94,7 @@ public class DefaultJaasAuthenticationProviderTests { @Test public void authenticateUnsupportedAuthentication() { - assertEquals(null, - provider.authenticate(new TestingAuthenticationToken("user", "password"))); + assertThat(provider.authenticate(new TestingAuthenticationToken("user", "password"))).isNull(); } @Test diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java index 13713a1f24..a96d2eacc2 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java @@ -40,10 +40,8 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.core.session.SessionDestroyedEvent; /** @@ -82,8 +80,7 @@ public class JaasAuthenticationProviderTests { } assertThat(eventCheck.failedEvent).as("Failure event not fired").isNotNull(); - assertNotNull("Failure event exception was null", - eventCheck.failedEvent.getException()); + assertThat(eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null").isNotNull(); assertThat(eventCheck.successEvent).as("Success event was fired").isNull(); } @@ -98,8 +95,7 @@ public class JaasAuthenticationProviderTests { } assertThat(eventCheck.failedEvent).as("Failure event not fired").isNotNull(); - assertNotNull("Failure event exception was null", - eventCheck.failedEvent.getException()); + assertThat(eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null").isNotNull(); assertThat(eventCheck.successEvent).as("Success event was fired").isNull(); } @@ -178,8 +174,7 @@ public class JaasAuthenticationProviderTests { fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage().isTrue() - .startsWith("loginContextName must be set on")); + assertThat(expected.getMessage()).startsWith("loginContextName must be set on"); } myJaasProvider.setLoginContextName(""); @@ -189,8 +184,7 @@ public class JaasAuthenticationProviderTests { fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage().isTrue() - .startsWith("loginContextName must be set on")); + assertThat(expected.getMessage().startsWith("loginContextName must be set on")); } } @@ -211,20 +205,15 @@ public class JaasAuthenticationProviderTests { Collection list = auth.getAuthorities(); Set set = AuthorityUtils.authorityListToSet(list); - assertFalse("GrantedAuthorities should not contain ROLE_1", - set.contains("ROLE_ONE")); - assertTrue("GrantedAuthorities should contain ROLE_TEST1", - set.contains("ROLE_TEST1")); - assertTrue("GrantedAuthorities should contain ROLE_TEST2", - set.contains("ROLE_TEST2")); - + assertThat(set.contains("ROLE_ONE")).withFailMessage("GrantedAuthorities should not contain ROLE_ONE").isFalse(); + assertThat(set.contains("ROLE_TEST1")).withFailMessage("GrantedAuthorities should contain ROLE_TEST1").isTrue(); + assertThat(set.contains("ROLE_TEST2")).withFailMessage("GrantedAuthorities should contain ROLE_TEST2").isTrue(); boolean foundit = false; for (GrantedAuthority a : list) { if (a instanceof JaasGrantedAuthority) { JaasGrantedAuthority grant = (JaasGrantedAuthority) a; - assertNotNull("Principal was null on JaasGrantedAuthority", - grant.getPrincipal()); + assertThat(grant.getPrincipal()).withFailMessage("Principal was null on JaasGrantedAuthority").isNotNull(); foundit = true; } } @@ -232,8 +221,7 @@ public class JaasAuthenticationProviderTests { assertThat(foundit).as("Could not find a JaasGrantedAuthority").isTrue(); assertThat(eventCheck.successEvent).as("Success event should be fired").isNotNull(); - assertEquals("Auth objects should be equal", auth, - eventCheck.successEvent.getAuthentication()); + assertThat(eventCheck.successEvent.getAuthentication()).withFailMessage("Auth objects should be equal").isEqualTo(auth); assertThat(eventCheck.failedEvent).as("Failure event should not be fired").isNull(); } @@ -289,14 +277,14 @@ public class JaasAuthenticationProviderTests { assertThat(jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue(); Authentication auth = jaasProvider.authenticate(token); - assertTrue("Only ROLE_TEST1 and ROLE_TEST2 should have been returned", auth - .getAuthorities().size() == 2); + assertThat(auth + .getAuthorities()).withFailMessage("Only ROLE_TEST1 and ROLE_TEST2 should have been returned").hasSize(2); } @Test public void testUnsupportedAuthenticationObjectReturnsNull() { - assertNull(jaasProvider.authenticate(new TestingAuthenticationToken("foo", "bar", - AuthorityUtils.NO_AUTHORITIES))); + assertThat(jaasProvider.authenticate(new TestingAuthenticationToken("foo", "bar", + AuthorityUtils.NO_AUTHORITIES))).isNull(); } // ~ Inner Classes diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/Sec760Tests.java b/core/src/test/java/org/springframework/security/authentication/jaas/Sec760Tests.java index e688108a01..4369d3be92 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/Sec760Tests.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/Sec760Tests.java @@ -1,6 +1,6 @@ package org.springframework.security.authentication.jaas; -import junit.framework.Assert; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.springframework.core.io.ClassPathResource; @@ -54,7 +54,7 @@ public class Sec760Tests { "ROLE_TWO")); Authentication auth = p1.authenticate(token); - Assert.assertThat(auth).isNotNull(); + assertThat(auth).isNotNull(); } @Test diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/SecurityContextLoginModuleTests.java b/core/src/test/java/org/springframework/security/authentication/jaas/SecurityContextLoginModuleTests.java index ea5a7d7e40..ef30da068f 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/SecurityContextLoginModuleTests.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/SecurityContextLoginModuleTests.java @@ -15,8 +15,11 @@ package org.springframework.security.authentication.jaas; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.jaas.SecurityContextLoginModule; import org.springframework.security.core.context.SecurityContextHolder; @@ -34,30 +37,33 @@ import javax.security.auth.login.LoginException; * * @author Ray Krueger */ -public class SecurityContextLoginModuleTests extends TestCase { +public class SecurityContextLoginModuleTests { // ~ Instance fields // ================================================================================================ private SecurityContextLoginModule module = null; - private Subject subject = new Subject(false, new HashSet(), - new HashSet(), new HashSet()); - private UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken( - "principal", "credentials"); + private Subject subject = new Subject(false, new HashSet(), new HashSet(), + new HashSet()); + private UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("principal", + "credentials"); // ~ Methods // ======================================================================================================== - protected void setUp() throws Exception { + @Before + public void setUp() throws Exception { module = new SecurityContextLoginModule(); module.initialize(subject, null, null, null); SecurityContextHolder.clearContext(); } - protected void tearDown() throws Exception { + @After + public void tearDown() throws Exception { SecurityContextHolder.clearContext(); module = null; } + @Test public void testAbort() throws Exception { assertThat(module.abort()).as("Should return false, no auth is set").isFalse(); SecurityContextHolder.getContext().setAuthentication(auth); @@ -65,45 +71,46 @@ public class SecurityContextLoginModuleTests extends TestCase { module.commit(); assertThat(module.abort()).isTrue(); } - + + @Test public void testLoginException() throws Exception { try { module.login(); fail("LoginException expected, there is no Authentication in the SecurityContext"); - } - catch (LoginException e) { + } catch (LoginException e) { } } + @Test public void testLoginSuccess() throws Exception { SecurityContextHolder.getContext().setAuthentication(auth); assertThat(module.login()).as("Login should succeed, there is an authentication set").isTrue(); - assertTrue("The authentication is not null, this should return true", - module.commit()); - assertTrue("Principals should contain the authentication", subject - .getPrincipals().contains(auth)); + assertThat(module.commit()).withFailMessage("The authentication is not null, this should return true").isTrue(); + assertThat(subject.getPrincipals().contains(auth)) + .withFailMessage("Principals should contain the authentication").isTrue(); } - + + @Test public void testLogout() throws Exception { SecurityContextHolder.getContext().setAuthentication(auth); module.login(); assertThat(module.logout()).as("Should return true as it succeeds").isTrue(); assertThat(module.getAuthentication()).as("Authentication should be null").isEqualTo(null); - assertFalse("Principals should not contain the authentication after logout", - subject.getPrincipals().contains(auth)); + assertThat(subject.getPrincipals().contains(auth)).withFailMessage("Principals should not contain the authentication after logout").isFalse(); } - + + @Test public void testNullAuthenticationInSecurityContext() throws Exception { try { SecurityContextHolder.getContext().setAuthentication(null); module.login(); fail("LoginException expected, the authentication is null in the SecurityContext"); - } - catch (Exception e) { + } catch (Exception e) { } } - + + @Test public void testNullAuthenticationInSecurityContextIgnored() throws Exception { module = new SecurityContextLoginModule(); @@ -114,7 +121,8 @@ public class SecurityContextLoginModuleTests extends TestCase { SecurityContextHolder.getContext().setAuthentication(null); assertThat(module.login()).as("Should return false and ask to be ignored").isFalse(); } - + + @Test public void testNullLogout() throws Exception { assertThat(module.logout()).isFalse(); } diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/memory/InMemoryConfigurationTests.java b/core/src/test/java/org/springframework/security/authentication/jaas/memory/InMemoryConfigurationTests.java index 3a53f5892e..c532c0afa8 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/memory/InMemoryConfigurationTests.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/memory/InMemoryConfigurationTests.java @@ -15,9 +15,7 @@ */ package org.springframework.security.authentication.jaas.memory; -import static org.junit.Assert.assertArrayEquals; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNull; import java.lang.reflect.Method; import java.util.Collections; @@ -54,8 +52,7 @@ public class InMemoryConfigurationTests { @Test public void constructorNullDefault() { - assertThat(new InMemoryConfiguration((AppConfigurationEntry[]) null).isNull() - .getAppConfigurationEntry("name")); + assertThat(new InMemoryConfiguration((AppConfigurationEntry[]) null).getAppConfigurationEntry("name")).isNull(); } @Test(expected = IllegalArgumentException.class) @@ -65,16 +62,16 @@ public class InMemoryConfigurationTests { @Test public void constructorEmptyMap() { - assertNull(new InMemoryConfiguration( + assertThat(new InMemoryConfiguration( Collections. emptyMap()) - .getAppConfigurationEntry("name")); + .getAppConfigurationEntry("name")).isNull(); } @Test public void constructorEmptyMapNullDefault() { - assertNull(new InMemoryConfiguration( + assertThat(new InMemoryConfiguration( Collections. emptyMap(), null) - .getAppConfigurationEntry("name")); + .getAppConfigurationEntry("name")).isNull(); } @Test(expected = IllegalArgumentException.class) @@ -92,10 +89,8 @@ public class InMemoryConfigurationTests { public void mappedNonnullDefault() { InMemoryConfiguration configuration = new InMemoryConfiguration(mappedEntries, defaultEntries); - assertArrayEquals(defaultEntries, - configuration.getAppConfigurationEntry("missing")); - assertArrayEquals(mappedEntries.get("name"), - configuration.getAppConfigurationEntry("name")); + assertThat(defaultEntries).isEqualTo(configuration.getAppConfigurationEntry("missing")); + assertThat(mappedEntries.get("name")).isEqualTo(configuration.getAppConfigurationEntry("name")); } @Test diff --git a/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProviderTests.java index 2cc3b1b279..8a49bfbf00 100644 --- a/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProviderTests.java @@ -15,13 +15,13 @@ package org.springframework.security.authentication.rcp; +import static org.assertj.core.api.Assertions.*; + import java.util.Collection; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; @@ -30,10 +30,11 @@ import org.springframework.security.core.authority.AuthorityUtils; * * @author Ben Alex */ -public class RemoteAuthenticationProviderTests extends TestCase { +public class RemoteAuthenticationProviderTests { // ~ Methods // ======================================================================================================== + @Test public void testExceptionsGetPassedBackToCaller() { RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false)); @@ -47,13 +48,15 @@ public class RemoteAuthenticationProviderTests extends TestCase { } } - + + @Test public void testGettersSetters() { RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(true)); assertThat(provider.getRemoteAuthenticationManager()).isNotNull(); } + @Test public void testStartupChecksAuthenticationManagerSet() throws Exception { RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); @@ -70,6 +73,7 @@ public class RemoteAuthenticationProviderTests extends TestCase { } + @Test public void testSuccessfulAuthenticationCreatesObject() { RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(true)); @@ -78,10 +82,10 @@ public class RemoteAuthenticationProviderTests extends TestCase { .authenticate(new UsernamePasswordAuthenticationToken("rod", "password")); assertThat(result.getPrincipal()).isEqualTo("rod"); assertThat(result.getCredentials()).isEqualTo("password"); - assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities()).isTrue().contains( - "foo")); + assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities()).contains("foo")); } + @Test public void testNullCredentialsDoesNotCauseNullPointerException() { RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false)); @@ -95,6 +99,7 @@ public class RemoteAuthenticationProviderTests extends TestCase { } + @Test public void testSupports() { RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); assertThat(provider.supports(UsernamePasswordAuthenticationToken.class)).isTrue(); diff --git a/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationProviderTests.java index 64265cfa32..ecd5fa13ca 100644 --- a/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationProviderTests.java @@ -15,8 +15,9 @@ package org.springframework.security.authentication.rememberme; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.*; +import org.junit.Test; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.RememberMeAuthenticationProvider; import org.springframework.security.authentication.RememberMeAuthenticationToken; @@ -29,10 +30,10 @@ import org.springframework.security.core.authority.AuthorityUtils; * * @author Ben Alex */ -public class RememberMeAuthenticationProviderTests extends TestCase { +public class RememberMeAuthenticationProviderTests { // ~ Methods // ======================================================================================================== - + @Test public void testDetectsAnInvalidKey() throws Exception { RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider( "qwerty"); @@ -48,7 +49,8 @@ public class RememberMeAuthenticationProviderTests extends TestCase { catch (BadCredentialsException expected) { } } - + + @Test public void testDetectsMissingKey() throws Exception { try { new RememberMeAuthenticationProvider(null); @@ -58,7 +60,8 @@ public class RememberMeAuthenticationProviderTests extends TestCase { } } - + + @Test public void testGettersSetters() throws Exception { RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider( "qwerty"); @@ -66,6 +69,7 @@ public class RememberMeAuthenticationProviderTests extends TestCase { assertThat(aap.getKey()).isEqualTo("qwerty"); } + @Test public void testIgnoresClassesItDoesNotSupport() throws Exception { RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider( "qwerty"); @@ -78,6 +82,7 @@ public class RememberMeAuthenticationProviderTests extends TestCase { assertThat(aap.authenticate(token)).isNull(); } + @Test public void testNormalOperation() throws Exception { RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider( "qwerty"); @@ -90,6 +95,7 @@ public class RememberMeAuthenticationProviderTests extends TestCase { assertThat(token).isEqualTo(result); } + @Test public void testSupports() { RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider( "qwerty"); diff --git a/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationTokenTests.java b/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationTokenTests.java index aa871972a5..0758fe8ed4 100644 --- a/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationTokenTests.java +++ b/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationTokenTests.java @@ -15,11 +15,13 @@ package org.springframework.security.authentication.rememberme; + +import static org.assertj.core.api.Assertions.*; + import java.util.ArrayList; import java.util.List; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.security.authentication.RememberMeAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.GrantedAuthority; @@ -30,13 +32,13 @@ import org.springframework.security.core.authority.AuthorityUtils; * * @author Ben Alex */ -public class RememberMeAuthenticationTokenTests extends TestCase { +public class RememberMeAuthenticationTokenTests { private static final List ROLES_12 = AuthorityUtils .createAuthorityList("ROLE_ONE", "ROLE_TWO"); // ~ Methods // ======================================================================================================== - + @Test public void testConstructorRejectsNulls() { try { new RememberMeAuthenticationToken(null, "Test", ROLES_12); @@ -65,6 +67,7 @@ public class RememberMeAuthenticationTokenTests extends TestCase { } } + @Test public void testEqualsWhenEqual() { RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", ROLES_12); @@ -74,6 +77,7 @@ public class RememberMeAuthenticationTokenTests extends TestCase { assertThat(token2).isEqualTo(token1); } + @Test public void testGetters() { RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("key", "Test", ROLES_12); @@ -81,13 +85,14 @@ public class RememberMeAuthenticationTokenTests extends TestCase { assertThat(token.getKeyHash()).isEqualTo("key".hashCode()); assertThat(token.getPrincipal()).isEqualTo("Test"); assertThat(token.getCredentials()).isEqualTo(""); - assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities()).isTrue().contains( + assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities()).contains( "ROLE_ONE")); - assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities()).isTrue().contains( + assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities()).contains( "ROLE_TWO")); assertThat(token.isAuthenticated()).isTrue(); } + @Test public void testNotEqualsDueToAbstractParentEqualsCheck() { RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", ROLES_12); @@ -97,6 +102,7 @@ public class RememberMeAuthenticationTokenTests extends TestCase { assertThat(token1.equals(token2)).isFalse(); } + @Test public void testNotEqualsDueToDifferentAuthenticationClass() { RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", ROLES_12); @@ -106,6 +112,7 @@ public class RememberMeAuthenticationTokenTests extends TestCase { assertThat(token1.equals(token2)).isFalse(); } + @Test public void testNotEqualsDueToKey() { RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", ROLES_12); @@ -115,6 +122,7 @@ public class RememberMeAuthenticationTokenTests extends TestCase { assertThat(token1.equals(token2)).isFalse(); } + @Test public void testSetAuthenticatedIgnored() { RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("key", "Test", ROLES_12); diff --git a/core/src/test/java/org/springframework/security/core/SpringSecurityMessageSourceTests.java b/core/src/test/java/org/springframework/security/core/SpringSecurityMessageSourceTests.java index 9b9986fca1..d76e5a026d 100644 --- a/core/src/test/java/org/springframework/security/core/SpringSecurityMessageSourceTests.java +++ b/core/src/test/java/org/springframework/security/core/SpringSecurityMessageSourceTests.java @@ -15,28 +15,30 @@ package org.springframework.security.core; -import junit.framework.TestCase; - -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.context.support.MessageSourceAccessor; -import org.springframework.security.core.SpringSecurityMessageSource; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Locale; +import org.junit.Test; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.context.support.MessageSourceAccessor; + /** * Tests {@link org.springframework.security.core.SpringSecurityMessageSource}. */ -public class SpringSecurityMessageSourceTests extends TestCase { +public class SpringSecurityMessageSourceTests { + // ~ Methods // ======================================================================================================== - + @Test public void testOperation() { SpringSecurityMessageSource msgs = new SpringSecurityMessageSource(); - assertEquals("\u4E0D\u5141\u8BB8\u8BBF\u95EE", msgs.getMessage( - "AbstractAccessDecisionManager.accessDenied", null, - Locale.SIMPLIFIED_CHINESE)); + assertThat("\u4E0D\u5141\u8BB8\u8BBF\u95EE").isEqualTo( + msgs.getMessage("AbstractAccessDecisionManager.accessDenied", null, + Locale.SIMPLIFIED_CHINESE)); } + @Test public void testReplacableLookup() { // Change Locale to English Locale before = LocaleContextHolder.getLocale(); @@ -44,15 +46,16 @@ public class SpringSecurityMessageSourceTests extends TestCase { // Cause a message to be generated MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); - assertEquals("Le jeton nonce est compromis FOOBAR", messages.getMessage( - "DigestAuthenticationFilter.nonceCompromised", new Object[] { "FOOBAR" }, - "ERROR - FAILED TO LOOKUP")); + assertThat("Le jeton nonce est compromis FOOBAR").isEqualTo( + messages.getMessage("DigestAuthenticationFilter.nonceCompromised", + new Object[] { "FOOBAR" }, "ERROR - FAILED TO LOOKUP")); // Revert to original Locale LocaleContextHolder.setLocale(before); } // SEC-3013 + @Test public void germanSystemLocaleWithEnglishLocaleContextHolder() { Locale beforeSystem = Locale.getDefault(); Locale.setDefault(Locale.GERMAN); @@ -61,8 +64,8 @@ public class SpringSecurityMessageSourceTests extends TestCase { LocaleContextHolder.setLocale(Locale.US); MessageSourceAccessor msgs = SpringSecurityMessageSource.getAccessor(); - assertEquals("Access is denied", msgs.getMessage( - "AbstractAccessDecisionManager.accessDenied", "Ooops")); + assertThat("Access is denied").isEqualTo( + msgs.getMessage("AbstractAccessDecisionManager.accessDenied", "Ooops")); // Revert to original Locale Locale.setDefault(beforeSystem); diff --git a/core/src/test/java/org/springframework/security/core/authority/AuthorityUtilsTests.java b/core/src/test/java/org/springframework/security/core/authority/AuthorityUtilsTests.java index 88bb302d91..c9c5aa9964 100644 --- a/core/src/test/java/org/springframework/security/core/authority/AuthorityUtilsTests.java +++ b/core/src/test/java/org/springframework/security/core/authority/AuthorityUtilsTests.java @@ -1,6 +1,6 @@ package org.springframework.security.core.authority; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.*; import java.util.List; import java.util.Set; diff --git a/core/src/test/java/org/springframework/security/core/authority/mapping/MapBasedAttributes2GrantedAuthoritiesMapperTests.java b/core/src/test/java/org/springframework/security/core/authority/mapping/MapBasedAttributes2GrantedAuthoritiesMapperTests.java index 8d11823488..843359c4a0 100644 --- a/core/src/test/java/org/springframework/security/core/authority/mapping/MapBasedAttributes2GrantedAuthoritiesMapperTests.java +++ b/core/src/test/java/org/springframework/security/core/authority/mapping/MapBasedAttributes2GrantedAuthoritiesMapperTests.java @@ -1,6 +1,6 @@ package org.springframework.security.core.authority.mapping; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.springframework.security.core.GrantedAuthority; @@ -192,8 +192,7 @@ public class MapBasedAttributes2GrantedAuthoritiesMapperTests { resultColl.add(auth.getAuthority()); } Collection expectedColl = Arrays.asList(expectedGas); - assertTrue("Role collections should match; result: " + resultColl - + ", expected: " + expectedColl, expectedColl.containsAll(resultColl) - && resultColl.containsAll(expectedColl)); + assertThat(resultColl.containsAll(expectedColl)).withFailMessage("Role collections should match; result: " + resultColl + + ", expected: " + expectedColl).isTrue(); } } diff --git a/core/src/test/java/org/springframework/security/core/authority/mapping/SimpleMappableRolesRetrieverTests.java b/core/src/test/java/org/springframework/security/core/authority/mapping/SimpleMappableRolesRetrieverTests.java index ff1aa0ebd8..791f2620ba 100644 --- a/core/src/test/java/org/springframework/security/core/authority/mapping/SimpleMappableRolesRetrieverTests.java +++ b/core/src/test/java/org/springframework/security/core/authority/mapping/SimpleMappableRolesRetrieverTests.java @@ -1,10 +1,11 @@ + package org.springframework.security.core.authority.mapping; +import static org.assertj.core.api.Assertions.assertThat; + import java.util.Set; -import junit.framework.TestCase; - -import org.springframework.security.core.authority.mapping.SimpleMappableAttributesRetriever; +import org.junit.Test; import org.springframework.util.StringUtils; /** @@ -12,15 +13,18 @@ import org.springframework.util.StringUtils; * @author TSARDD * @since 18-okt-2007 */ -public class SimpleMappableRolesRetrieverTests extends TestCase { +public class SimpleMappableRolesRetrieverTests { + @Test public final void testGetSetMappableRoles() { Set roles = StringUtils.commaDelimitedListToSet("Role1,Role2"); SimpleMappableAttributesRetriever r = new SimpleMappableAttributesRetriever(); r.setMappableAttributes(roles); Set result = r.getMappableAttributes(); - assertTrue("Role collections do not match; result: " + result + ", expected: " - + roles, roles.containsAll(result) && result.containsAll(roles)); + assertThat( + roles.containsAll(result) && result.containsAll(roles)).withFailMessage( + "Role collections do not match; result: " + result + + ", expected: " + roles).isTrue(); } } diff --git a/core/src/test/java/org/springframework/security/core/authority/mapping/SimpleRoles2GrantedAuthoritiesMapperTests.java b/core/src/test/java/org/springframework/security/core/authority/mapping/SimpleRoles2GrantedAuthoritiesMapperTests.java index 7b7d2de75d..bd4da44ff8 100644 --- a/core/src/test/java/org/springframework/security/core/authority/mapping/SimpleRoles2GrantedAuthoritiesMapperTests.java +++ b/core/src/test/java/org/springframework/security/core/authority/mapping/SimpleRoles2GrantedAuthoritiesMapperTests.java @@ -1,6 +1,8 @@ package org.springframework.security.core.authority.mapping; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.*; + +import org.junit.Test; import org.springframework.security.core.GrantedAuthority; import java.util.*; @@ -10,8 +12,9 @@ import java.util.*; * @author TSARDD * @since 18-okt-2007 */ -public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase { +public class SimpleRoles2GrantedAuthoritiesMapperTests { + @Test public final void testAfterPropertiesSetConvertToUpperAndLowerCase() { SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper(); mapper.setConvertAttributeToLowerCase(true); @@ -27,6 +30,7 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase { } } + @Test public final void testAfterPropertiesSet() { SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper(); try { @@ -37,6 +41,7 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase { } } + @Test public final void testGetGrantedAuthoritiesNoConversion() { String[] roles = { "Role1", "Role2" }; String[] expectedGas = { "Role1", "Role2" }; @@ -44,6 +49,7 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase { testGetGrantedAuthorities(mapper, roles, expectedGas); } + @Test public final void testGetGrantedAuthoritiesToUpperCase() { String[] roles = { "Role1", "Role2" }; String[] expectedGas = { "ROLE1", "ROLE2" }; @@ -52,6 +58,7 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase { testGetGrantedAuthorities(mapper, roles, expectedGas); } + @Test public final void testGetGrantedAuthoritiesToLowerCase() { String[] roles = { "Role1", "Role2" }; String[] expectedGas = { "role1", "role2" }; @@ -60,6 +67,7 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase { testGetGrantedAuthorities(mapper, roles, expectedGas); } + @Test public final void testGetGrantedAuthoritiesAddPrefixIfAlreadyExisting() { String[] roles = { "Role1", "Role2", "ROLE_Role3" }; String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_ROLE_Role3" }; @@ -69,6 +77,7 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase { testGetGrantedAuthorities(mapper, roles, expectedGas); } + @Test public final void testGetGrantedAuthoritiesDontAddPrefixIfAlreadyExisting1() { String[] roles = { "Role1", "Role2", "ROLE_Role3" }; String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_Role3" }; @@ -78,6 +87,7 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase { testGetGrantedAuthorities(mapper, roles, expectedGas); } + @Test public final void testGetGrantedAuthoritiesDontAddPrefixIfAlreadyExisting2() { String[] roles = { "Role1", "Role2", "role_Role3" }; String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_role_Role3" }; @@ -87,6 +97,7 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase { testGetGrantedAuthorities(mapper, roles, expectedGas); } + @Test public final void testGetGrantedAuthoritiesCombination1() { String[] roles = { "Role1", "Role2", "role_Role3" }; String[] expectedGas = { "ROLE_ROLE1", "ROLE_ROLE2", "ROLE_ROLE3" }; @@ -107,9 +118,9 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase { resultColl.add(result.get(i).getAuthority()); } Collection expectedColl = Arrays.asList(expectedGas); - assertTrue("Role collections do not match; result: " + resultColl - + ", expected: " + expectedColl, expectedColl.containsAll(resultColl) - && resultColl.containsAll(expectedColl)); + assertThat(expectedColl.containsAll(resultColl) + && resultColl.containsAll(expectedColl)).withFailMessage("Role collections do not match; result: " + resultColl + + ", expected: " + expectedColl).isTrue(); } private SimpleAttributes2GrantedAuthoritiesMapper getDefaultMapper() { diff --git a/core/src/test/java/org/springframework/security/core/context/SecurityContextHolderTests.java b/core/src/test/java/org/springframework/security/core/context/SecurityContextHolderTests.java index 60abdfa35f..166affd5ac 100644 --- a/core/src/test/java/org/springframework/security/core/context/SecurityContextHolderTests.java +++ b/core/src/test/java/org/springframework/security/core/context/SecurityContextHolderTests.java @@ -15,8 +15,10 @@ package org.springframework.security.core.context; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.*; +import org.junit.Before; +import org.junit.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextImpl; @@ -25,16 +27,17 @@ import org.springframework.security.core.context.SecurityContextImpl; * * @author Ben Alex */ -public class SecurityContextHolderTests extends TestCase { +public class SecurityContextHolderTests { // ~ Methods // ======================================================================================================== - + @Before public final void setUp() throws Exception { SecurityContextHolder .setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL); } + @Test public void testContextHolderGetterSetterClearer() { SecurityContext sc = new SecurityContextImpl(); sc.setAuthentication(new UsernamePasswordAuthenticationToken("Foobar", "pass")); @@ -45,11 +48,13 @@ public class SecurityContextHolderTests extends TestCase { SecurityContextHolder.clearContext(); } + @Test public void testNeverReturnsNull() { assertThat(SecurityContextHolder.getContext()).isNotNull(); SecurityContextHolder.clearContext(); } + @Test public void testRejectsNulls() { try { SecurityContextHolder.setContext(null); diff --git a/core/src/test/java/org/springframework/security/core/context/SecurityContextImplTests.java b/core/src/test/java/org/springframework/security/core/context/SecurityContextImplTests.java index abdd9f9c47..4f05931027 100644 --- a/core/src/test/java/org/springframework/security/core/context/SecurityContextImplTests.java +++ b/core/src/test/java/org/springframework/security/core/context/SecurityContextImplTests.java @@ -15,18 +15,18 @@ package org.springframework.security.core.context; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextImpl; /** * Tests {@link SecurityContextImpl}. * * @author Ben Alex */ -public class SecurityContextImplTests extends TestCase { +public class SecurityContextImplTests { // ~ Constructors // =================================================================================================== @@ -34,19 +34,16 @@ public class SecurityContextImplTests extends TestCase { super(); } - public SecurityContextImplTests(String arg0) { - super(arg0); - } - // ~ Methods // ======================================================================================================== - + @Test public void testEmptyObjectsAreEquals() { SecurityContextImpl obj1 = new SecurityContextImpl(); SecurityContextImpl obj2 = new SecurityContextImpl(); assertThat(obj1.equals(obj2)).isTrue(); } + @Test public void testSecurityContextCorrectOperation() { SecurityContext context = new SecurityContextImpl(); Authentication auth = new UsernamePasswordAuthenticationToken("rod", "koala"); diff --git a/core/src/test/java/org/springframework/security/core/session/SessionInformationTests.java b/core/src/test/java/org/springframework/security/core/session/SessionInformationTests.java index 907d3e3f28..b67933af79 100644 --- a/core/src/test/java/org/springframework/security/core/session/SessionInformationTests.java +++ b/core/src/test/java/org/springframework/security/core/session/SessionInformationTests.java @@ -15,21 +15,22 @@ package org.springframework.security.core.session; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Date; -import org.springframework.security.core.session.SessionInformation; +import org.junit.Test; /** * Tests {@link SessionInformation}. * * @author Ben Alex */ -public class SessionInformationTests extends TestCase { +public class SessionInformationTests { + // ~ Methods // ======================================================================================================== - + @Test public void testObject() throws Exception { Object principal = "Some principal object"; String sessionId = "1234567890"; diff --git a/core/src/test/java/org/springframework/security/core/session/SessionRegistryImplTests.java b/core/src/test/java/org/springframework/security/core/session/SessionRegistryImplTests.java index fd443118db..1b0af8ea35 100644 --- a/core/src/test/java/org/springframework/security/core/session/SessionRegistryImplTests.java +++ b/core/src/test/java/org/springframework/security/core/session/SessionRegistryImplTests.java @@ -95,10 +95,8 @@ public class SessionRegistryImplTests { // Retrieve existing session by session ID Date currentDateTime = sessionRegistry.getSessionInformation(sessionId) .getLastRequest(); - assertThat(sessionRegistry.getSessionInformation(sessionId).isEqualTo(principal) - .getPrincipal()); - assertThat(sessionRegistry.getSessionInformation(sessionId).isEqualTo(sessionId) - .getSessionId()); + assertThat(sessionRegistry.getSessionInformation(sessionId).getPrincipal()).isEqualTo(principal); + assertThat(sessionRegistry.getSessionInformation(sessionId).getSessionId()).isEqualTo(sessionId); assertThat(sessionRegistry.getSessionInformation(sessionId).getLastRequest()).isNotNull(); // Retrieve existing session by principal @@ -115,8 +113,7 @@ public class SessionRegistryImplTests { assertThat(retrieved.after(currentDateTime)).isTrue(); // Check it retrieves correctly when looked up via principal - assertThat(sessionRegistry.getAllSessions(principal).isCloseTo(retrieved, within(false).get(0)) - .getLastRequest()); + assertThat(sessionRegistry.getAllSessions(principal, false).get(0).getLastRequest()).isCloseTo(retrieved, 2000L); // Clear session information sessionRegistry.removeSessionInformation(sessionId); diff --git a/core/src/test/java/org/springframework/security/core/token/DefaultTokenTests.java b/core/src/test/java/org/springframework/security/core/token/DefaultTokenTests.java index e175ce14e1..959c71f303 100644 --- a/core/src/test/java/org/springframework/security/core/token/DefaultTokenTests.java +++ b/core/src/test/java/org/springframework/security/core/token/DefaultTokenTests.java @@ -2,7 +2,7 @@ package org.springframework.security.core.token; import java.util.Date; -import junit.framework.Assert; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.springframework.security.core.token.DefaultToken; @@ -22,7 +22,7 @@ public class DefaultTokenTests { DefaultToken t1 = new DefaultToken(key, created, extendedInformation); DefaultToken t2 = new DefaultToken(key, created, extendedInformation); - Assert.assertThat(t2).isEqualTo(t1); + assertThat(t2).isEqualTo(t1); } @Test(expected = IllegalArgumentException.class) @@ -39,6 +39,6 @@ public class DefaultTokenTests { DefaultToken t1 = new DefaultToken(key, created, "length1"); DefaultToken t2 = new DefaultToken(key, created, "longerLength2"); - Assert.assertThat(t1.equals(t2)).isFalse(); + assertThat(t1).isNotEqualTo(t2); } } diff --git a/core/src/test/java/org/springframework/security/core/token/KeyBasedPersistenceTokenServiceTests.java b/core/src/test/java/org/springframework/security/core/token/KeyBasedPersistenceTokenServiceTests.java index aa4c863cb7..1a71673bf5 100644 --- a/core/src/test/java/org/springframework/security/core/token/KeyBasedPersistenceTokenServiceTests.java +++ b/core/src/test/java/org/springframework/security/core/token/KeyBasedPersistenceTokenServiceTests.java @@ -1,10 +1,10 @@ package org.springframework.security.core.token; +import static org.assertj.core.api.Assertions.*; + import java.security.SecureRandom; import java.util.Date; -import junit.framework.Assert; - import org.junit.Test; import org.springframework.security.core.token.DefaultToken; import org.springframework.security.core.token.KeyBasedPersistenceTokenService; @@ -40,7 +40,7 @@ public class KeyBasedPersistenceTokenServiceTests { KeyBasedPersistenceTokenService service = getService(); Token token = service.allocateToken("Hello world"); Token result = service.verifyToken(token.getKey()); - Assert.assertThat(result).isEqualTo(token); + assertThat(result).isEqualTo(token); } @Test @@ -48,7 +48,7 @@ public class KeyBasedPersistenceTokenServiceTests { KeyBasedPersistenceTokenService service = getService(); Token token = service.allocateToken("Hello:world:::"); Token result = service.verifyToken(token.getKey()); - Assert.assertThat(result).isEqualTo(token); + assertThat(result).isEqualTo(token); } @Test @@ -57,7 +57,7 @@ public class KeyBasedPersistenceTokenServiceTests { service.setPseudoRandomNumberBytes(0); Token token = service.allocateToken("Hello:world:::"); Token result = service.verifyToken(token.getKey()); - Assert.assertThat(result).isEqualTo(token); + assertThat(result).isEqualTo(token); } @Test @@ -65,7 +65,7 @@ public class KeyBasedPersistenceTokenServiceTests { KeyBasedPersistenceTokenService service = getService(); Token token = service.allocateToken(""); Token result = service.verifyToken(token.getKey()); - Assert.assertThat(result).isEqualTo(token); + assertThat(result).isEqualTo(token); } @Test(expected = IllegalArgumentException.class) diff --git a/core/src/test/java/org/springframework/security/core/token/SecureRandomFactoryBeanTests.java b/core/src/test/java/org/springframework/security/core/token/SecureRandomFactoryBeanTests.java index 4ae78812cd..92be463989 100644 --- a/core/src/test/java/org/springframework/security/core/token/SecureRandomFactoryBeanTests.java +++ b/core/src/test/java/org/springframework/security/core/token/SecureRandomFactoryBeanTests.java @@ -1,5 +1,7 @@ package org.springframework.security.core.token; +import static org.assertj.core.api.Assertions.*; + import java.security.SecureRandom; import org.junit.Test; @@ -7,8 +9,6 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.security.core.token.SecureRandomFactoryBean; -import junit.framework.Assert; - /** * Tests {@link SecureRandomFactoryBean}. * @@ -19,22 +19,22 @@ public class SecureRandomFactoryBeanTests { @Test public void testObjectType() { SecureRandomFactoryBean factory = new SecureRandomFactoryBean(); - Assert.assertThat(factory.getObjectType()).isEqualTo(SecureRandom.class); + assertThat(factory.getObjectType()).isEqualTo(SecureRandom.class); } @Test public void testIsSingleton() { SecureRandomFactoryBean factory = new SecureRandomFactoryBean(); - Assert.assertThat(factory.isSingleton()).isFalse(); + assertThat(factory.isSingleton()).isFalse(); } @Test public void testCreatesUsingDefaults() throws Exception { SecureRandomFactoryBean factory = new SecureRandomFactoryBean(); Object result = factory.getObject(); - Assert.assertThat(result instanceof SecureRandom).isTrue(); + assertThat(result).isInstanceOf(SecureRandom.class); int rnd = ((SecureRandom) result).nextInt(); - Assert.assertThat(rnd != 0).isTrue(); + assertThat(rnd).isNotEqualTo(0); } @Test @@ -42,12 +42,12 @@ public class SecureRandomFactoryBeanTests { SecureRandomFactoryBean factory = new SecureRandomFactoryBean(); Resource resource = new ClassPathResource( "org/springframework/security/core/token/SecureRandomFactoryBeanTests.class"); - Assert.assertThat(resource).isNotNull(); + assertThat(resource).isNotNull(); factory.setSeed(resource); Object result = factory.getObject(); - Assert.assertThat(result instanceof SecureRandom).isTrue(); + assertThat(result).isInstanceOf(SecureRandom.class); int rnd = ((SecureRandom) result).nextInt(); - Assert.assertThat(rnd != 0).isTrue(); + assertThat(rnd).isNotEqualTo(0); } } diff --git a/core/src/test/java/org/springframework/security/core/userdetails/UserDetailsByNameServiceWrapperTests.java b/core/src/test/java/org/springframework/security/core/userdetails/UserDetailsByNameServiceWrapperTests.java index 332241f2a5..61dba279db 100644 --- a/core/src/test/java/org/springframework/security/core/userdetails/UserDetailsByNameServiceWrapperTests.java +++ b/core/src/test/java/org/springframework/security/core/userdetails/UserDetailsByNameServiceWrapperTests.java @@ -1,7 +1,8 @@ package org.springframework.security.core.userdetails; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.*; +import org.junit.Test; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.authority.AuthorityUtils; @@ -11,8 +12,9 @@ import org.springframework.security.core.authority.AuthorityUtils; * @since 18-okt-2007 */ @SuppressWarnings("unchecked") -public class UserDetailsByNameServiceWrapperTests extends TestCase { +public class UserDetailsByNameServiceWrapperTests { + @Test public final void testAfterPropertiesSet() { UserDetailsByNameServiceWrapper svc = new UserDetailsByNameServiceWrapper(); try { @@ -26,6 +28,7 @@ public class UserDetailsByNameServiceWrapperTests extends TestCase { } } + @Test public final void testGetUserDetails() throws Exception { UserDetailsByNameServiceWrapper svc = new UserDetailsByNameServiceWrapper(); final User user = new User("dummy", "dummy", true, true, true, true, diff --git a/core/src/test/java/org/springframework/security/core/userdetails/UserTests.java b/core/src/test/java/org/springframework/security/core/userdetails/UserTests.java index 3b62bcf51e..1c2ddf954d 100644 --- a/core/src/test/java/org/springframework/security/core/userdetails/UserTests.java +++ b/core/src/test/java/org/springframework/security/core/userdetails/UserTests.java @@ -44,10 +44,10 @@ public class UserTests { public void equalsReturnsTrueIfUsernamesAreTheSame() { User user1 = new User("rod", "koala", true, true, true, true, ROLE_12); - assertThat(user1.equals(null)).isFalse(); - assertThat(user1.equals("A STRING")).isFalse(); - assertThat(user1.equals(user1)).isTrue(); - assertTrue(user1.equals(new User("rod", "notthesame", true, true, true, true, + assertThat(user1).isNotNull(); + assertThat(user1).isNotEqualTo("A STRING"); + assertThat(user1).isEqualTo(user1); + assertThat(user1).isEqualTo((new User("rod", "notthesame", true, true, true, true, ROLE_12))); } @@ -57,12 +57,12 @@ public class UserTests { Set users = new HashSet(); users.add(user1); - assertTrue(users.contains(new User("rod", "koala", true, true, true, true, - ROLE_12))); - assertTrue(users.contains(new User("rod", "anotherpass", false, false, false, - false, AuthorityUtils.createAuthorityList("ROLE_X")))); - assertFalse(users.contains(new User("bod", "koala", true, true, true, true, - ROLE_12))); + assertThat(users).contains(new User("rod", "koala", true, true, true, true, + ROLE_12)); + assertThat(users).contains(new User("rod", "anotherpass", false, false, false, + false, AuthorityUtils.createAuthorityList("ROLE_X"))); + assertThat(users).doesNotContain(new User("bod", "koala", true, true, true, true, + ROLE_12)); } @Test @@ -123,10 +123,10 @@ public class UserTests { assertThat(user.getUsername()).isEqualTo("rod"); assertThat(user.getPassword()).isEqualTo("koala"); assertThat(user.isEnabled()).isTrue(); - assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains( - "ROLE_ONE")); - assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains( - "ROLE_TWO")); + assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities())).contains( + "ROLE_ONE"); + assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities())).contains( + "ROLE_TWO"); assertThat(user.toString().indexOf("rod") != -1).isTrue(); } diff --git a/core/src/test/java/org/springframework/security/core/userdetails/cache/EhCacheBasedUserCacheTests.java b/core/src/test/java/org/springframework/security/core/userdetails/cache/EhCacheBasedUserCacheTests.java index 15739f0bc8..d76ac191cc 100644 --- a/core/src/test/java/org/springframework/security/core/userdetails/cache/EhCacheBasedUserCacheTests.java +++ b/core/src/test/java/org/springframework/security/core/userdetails/cache/EhCacheBasedUserCacheTests.java @@ -70,8 +70,7 @@ public class EhCacheBasedUserCacheTests { // Check it gets stored in the cache cache.putUserInCache(getUser()); - assertEquals(getUser().getPassword(), - cache.getUserFromCache(getUser().getUsername()).getPassword()); + assertThat(getUser().getPassword()).isEqualTo(cache.getUserFromCache(getUser().getUsername()).getPassword()); // Check it gets removed from the cache cache.removeUserFromCache(getUser()); diff --git a/core/src/test/java/org/springframework/security/core/userdetails/cache/NullUserCacheTests.java b/core/src/test/java/org/springframework/security/core/userdetails/cache/NullUserCacheTests.java index 5331f3eb21..c890ab562e 100644 --- a/core/src/test/java/org/springframework/security/core/userdetails/cache/NullUserCacheTests.java +++ b/core/src/test/java/org/springframework/security/core/userdetails/cache/NullUserCacheTests.java @@ -15,18 +15,18 @@ package org.springframework.security.core.userdetails.cache; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.cache.NullUserCache; /** * Tests {@link NullUserCache}. * * @author Ben Alex */ -public class NullUserCacheTests extends TestCase { +public class NullUserCacheTests { // ~ Methods // ======================================================================================================== @@ -36,6 +36,7 @@ public class NullUserCacheTests extends TestCase { AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); } + @Test public void testCacheOperation() throws Exception { NullUserCache cache = new NullUserCache(); cache.putUserInCache(getUser()); diff --git a/core/src/test/java/org/springframework/security/core/userdetails/cache/SpringCacheBasedUserCacheTests.java b/core/src/test/java/org/springframework/security/core/userdetails/cache/SpringCacheBasedUserCacheTests.java index 6f725be75e..5b957bab8b 100644 --- a/core/src/test/java/org/springframework/security/core/userdetails/cache/SpringCacheBasedUserCacheTests.java +++ b/core/src/test/java/org/springframework/security/core/userdetails/cache/SpringCacheBasedUserCacheTests.java @@ -66,8 +66,7 @@ public class SpringCacheBasedUserCacheTests { // Check it gets stored in the cache cache.putUserInCache(getUser()); - assertEquals(getUser().getPassword(), - cache.getUserFromCache(getUser().getUsername()).getPassword()); + assertThat(getUser().getPassword()).isEqualTo(cache.getUserFromCache(getUser().getUsername()).getPassword()); // Check it gets removed from the cache cache.removeUserFromCache(getUser()); diff --git a/core/src/test/java/org/springframework/security/core/userdetails/jdbc/JdbcDaoImplTests.java b/core/src/test/java/org/springframework/security/core/userdetails/jdbc/JdbcDaoImplTests.java index 543c993719..85bb893cf1 100644 --- a/core/src/test/java/org/springframework/security/core/userdetails/jdbc/JdbcDaoImplTests.java +++ b/core/src/test/java/org/springframework/security/core/userdetails/jdbc/JdbcDaoImplTests.java @@ -15,7 +15,9 @@ package org.springframework.security.core.userdetails.jdbc; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.*; + +import org.junit.Test; import org.springframework.security.PopulatedDatabase; import org.springframework.security.core.authority.AuthorityUtils; @@ -27,7 +29,7 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; * * @author Ben Alex */ -public class JdbcDaoImplTests extends TestCase { +public class JdbcDaoImplTests { // ~ Methods // ======================================================================================================== @@ -49,6 +51,7 @@ public class JdbcDaoImplTests extends TestCase { return dao; } + @Test public void testCheckDaoAccessUserSuccess() throws Exception { JdbcDaoImpl dao = makePopulatedJdbcDao(); UserDetails user = dao.loadUserByUsername("rod"); @@ -56,26 +59,29 @@ public class JdbcDaoImplTests extends TestCase { assertThat(user.getPassword()).isEqualTo("koala"); assertThat(user.isEnabled()).isTrue(); - assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains( + assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains( "ROLE_TELLER")); - assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains( + assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains( "ROLE_SUPERVISOR")); } + @Test public void testCheckDaoOnlyReturnsGrantedAuthoritiesGrantedToUser() throws Exception { JdbcDaoImpl dao = makePopulatedJdbcDao(); UserDetails user = dao.loadUserByUsername("scott"); assertThat(user.getAuthorities()).hasSize(1); - assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains( + assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains( "ROLE_TELLER")); } + @Test public void testCheckDaoReturnsCorrectDisabledProperty() throws Exception { JdbcDaoImpl dao = makePopulatedJdbcDao(); UserDetails user = dao.loadUserByUsername("peter"); - assertThat(!user.isEnabled()).isTrue(); + assertThat(user.isEnabled()).isFalse(); } + @Test public void testGettersSetters() { JdbcDaoImpl dao = new JdbcDaoImpl(); dao.setAuthoritiesByUsernameQuery("SELECT * FROM FOO"); @@ -85,6 +91,7 @@ public class JdbcDaoImplTests extends TestCase { assertThat(dao.getUsersByUsernameQuery()).isEqualTo("SELECT USERS FROM FOO"); } + @Test public void testLookupFailsIfUserHasNoGrantedAuthorities() throws Exception { JdbcDaoImpl dao = makePopulatedJdbcDao(); @@ -96,6 +103,7 @@ public class JdbcDaoImplTests extends TestCase { } } + @Test public void testLookupFailsWithWrongUsername() throws Exception { JdbcDaoImpl dao = makePopulatedJdbcDao(); @@ -108,12 +116,14 @@ public class JdbcDaoImplTests extends TestCase { } } + @Test public void testLookupSuccessWithMixedCase() throws Exception { JdbcDaoImpl dao = makePopulatedJdbcDao(); assertThat(dao.loadUserByUsername("rod").getPassword()).isEqualTo("koala"); assertThat(dao.loadUserByUsername("ScOTt").getPassword()).isEqualTo("wombat"); } + @Test public void testRolePrefixWorks() throws Exception { JdbcDaoImpl dao = makePopulatedJdbcDaoWithRolePrefix(); assertThat(dao.getRolePrefix()).isEqualTo("ARBITRARY_PREFIX_"); @@ -122,12 +132,13 @@ public class JdbcDaoImplTests extends TestCase { assertThat(user.getUsername()).isEqualTo("rod"); assertThat(user.getAuthorities()).hasSize(2); - assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains( + assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains( "ARBITRARY_PREFIX_ROLE_TELLER")); - assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains( + assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains( "ARBITRARY_PREFIX_ROLE_SUPERVISOR")); } + @Test public void testGroupAuthoritiesAreLoadedCorrectly() throws Exception { JdbcDaoImpl dao = makePopulatedJdbcDao(); dao.setEnableAuthorities(false); @@ -137,6 +148,7 @@ public class JdbcDaoImplTests extends TestCase { assertThat(jerry.getAuthorities()).hasSize(3); } + @Test public void testDuplicateGroupAuthoritiesAreRemoved() throws Exception { JdbcDaoImpl dao = makePopulatedJdbcDao(); dao.setEnableAuthorities(false); @@ -146,6 +158,7 @@ public class JdbcDaoImplTests extends TestCase { assertThat(tom.getAuthorities()).hasSize(3); } + @Test public void testStartupFailsIfDataSourceNotSet() throws Exception { JdbcDaoImpl dao = new JdbcDaoImpl(); @@ -158,6 +171,7 @@ public class JdbcDaoImplTests extends TestCase { } } + @Test public void testStartupFailsIfUserMapSetToNull() throws Exception { JdbcDaoImpl dao = new JdbcDaoImpl(); diff --git a/core/src/test/java/org/springframework/security/core/userdetails/memory/UserAttributeEditorTests.java b/core/src/test/java/org/springframework/security/core/userdetails/memory/UserAttributeEditorTests.java index 10de291765..10b9f552a0 100644 --- a/core/src/test/java/org/springframework/security/core/userdetails/memory/UserAttributeEditorTests.java +++ b/core/src/test/java/org/springframework/security/core/userdetails/memory/UserAttributeEditorTests.java @@ -15,18 +15,18 @@ package org.springframework.security.core.userdetails.memory; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.assertThat; -import org.springframework.security.core.userdetails.memory.UserAttribute; -import org.springframework.security.core.userdetails.memory.UserAttributeEditor; +import org.junit.Test; /** * Tests {@link UserAttributeEditor} and associated {@link UserAttribute}. * * @author Ben Alex */ -public class UserAttributeEditorTests extends TestCase { +public class UserAttributeEditorTests { + @Test public void testCorrectOperationWithTrailingSpaces() { UserAttributeEditor editor = new UserAttributeEditor(); editor.setAsText("password ,ROLE_ONE,ROLE_TWO "); @@ -38,6 +38,7 @@ public class UserAttributeEditorTests extends TestCase { assertThat(user.getAuthorities().get(1).getAuthority()).isEqualTo("ROLE_TWO"); } + @Test public void testCorrectOperationWithoutEnabledDisabledKeyword() { UserAttributeEditor editor = new UserAttributeEditor(); editor.setAsText("password,ROLE_ONE,ROLE_TWO"); @@ -51,6 +52,7 @@ public class UserAttributeEditorTests extends TestCase { assertThat(user.getAuthorities().get(1).getAuthority()).isEqualTo("ROLE_TWO"); } + @Test public void testDisabledKeyword() { UserAttributeEditor editor = new UserAttributeEditor(); editor.setAsText("password,disabled,ROLE_ONE,ROLE_TWO"); @@ -64,6 +66,7 @@ public class UserAttributeEditorTests extends TestCase { assertThat(user.getAuthorities().get(1).getAuthority()).isEqualTo("ROLE_TWO"); } + @Test public void testEmptyStringReturnsNull() { UserAttributeEditor editor = new UserAttributeEditor(); editor.setAsText(""); @@ -72,6 +75,7 @@ public class UserAttributeEditorTests extends TestCase { assertThat(user == null).isTrue(); } + @Test public void testEnabledKeyword() { UserAttributeEditor editor = new UserAttributeEditor(); editor.setAsText("password,ROLE_ONE,enabled,ROLE_TWO"); @@ -85,6 +89,7 @@ public class UserAttributeEditorTests extends TestCase { assertThat(user.getAuthorities().get(1).getAuthority()).isEqualTo("ROLE_TWO"); } + @Test public void testMalformedStringReturnsNull() { UserAttributeEditor editor = new UserAttributeEditor(); editor.setAsText("MALFORMED_STRING"); @@ -93,6 +98,7 @@ public class UserAttributeEditorTests extends TestCase { assertThat(user == null).isTrue(); } + @Test public void testNoPasswordOrRolesReturnsNull() { UserAttributeEditor editor = new UserAttributeEditor(); editor.setAsText("disabled"); @@ -101,6 +107,7 @@ public class UserAttributeEditorTests extends TestCase { assertThat(user == null).isTrue(); } + @Test public void testNoRolesReturnsNull() { UserAttributeEditor editor = new UserAttributeEditor(); editor.setAsText("password,enabled"); @@ -109,6 +116,7 @@ public class UserAttributeEditorTests extends TestCase { assertThat(user == null).isTrue(); } + @Test public void testNullReturnsNull() { UserAttributeEditor editor = new UserAttributeEditor(); editor.setAsText(null); diff --git a/core/src/test/java/org/springframework/security/provisioning/JdbcUserDetailsManagerTests.java b/core/src/test/java/org/springframework/security/provisioning/JdbcUserDetailsManagerTests.java index 5d78a7e04e..241dbf28e6 100644 --- a/core/src/test/java/org/springframework/security/provisioning/JdbcUserDetailsManagerTests.java +++ b/core/src/test/java/org/springframework/security/provisioning/JdbcUserDetailsManagerTests.java @@ -193,8 +193,7 @@ public class JdbcUserDetailsManagerTests { // Check password hasn't changed. UserDetails newJoe = manager.loadUserByUsername("joe"); assertThat(newJoe.getPassword()).isEqualTo("password"); - assertThat(SecurityContextHolder.getContext().getAuthentication().isEqualTo("password") - .getCredentials()); + assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("password"); assertThat(cache.getUserMap().containsKey("joe")).isTrue(); } @@ -248,37 +247,31 @@ public class JdbcUserDetailsManagerTests { public void renameGroupIsSuccessful() throws Exception { manager.renameGroup("GROUP_0", "GROUP_X"); - assertEquals( - 0, - (int) template.queryForObject("select id from groups where group_name = 'GROUP_X'", - Integer.class)); + assertThat(template.queryForObject("select id from groups where group_name = 'GROUP_X'", + Integer.class)).isEqualTo(0); } @Test public void addingGroupUserSetsCorrectData() throws Exception { manager.addUserToGroup("tom", "GROUP_0"); - assertEquals( - 2, + assertThat( template.queryForList( - "select username from group_members where group_id = 0").size()); + "select username from group_members where group_id = 0")).hasSize(2); } @Test public void removeUserFromGroupDeletesGroupMemberRow() throws Exception { manager.removeUserFromGroup("jerry", "GROUP_1"); - assertEquals( - 1, - template.queryForList( - "select group_id from group_members where username = 'jerry'") - .size()); + assertThat( + template.queryForList( + "select group_id from group_members where username = 'jerry'")).hasSize(1); } @Test public void findGroupAuthoritiesReturnsCorrectAuthorities() throws Exception { - assertEquals(AuthorityUtils.createAuthorityList("ROLE_A"), - manager.findGroupAuthorities("GROUP_0")); + assertThat(AuthorityUtils.createAuthorityList("ROLE_A")).isEqualTo(manager.findGroupAuthorities("GROUP_0")); } @Test @@ -295,18 +288,14 @@ public class JdbcUserDetailsManagerTests { public void deleteGroupAuthorityRemovesCorrectRows() throws Exception { GrantedAuthority auth = new SimpleGrantedAuthority("ROLE_A"); manager.removeGroupAuthority("GROUP_0", auth); - assertEquals( - 0, + assertThat( template.queryForList( - "select authority from group_authorities where group_id = 0") - .size()); + "select authority from group_authorities where group_id = 0")).isEmpty(); manager.removeGroupAuthority("GROUP_2", auth); - assertEquals( - 2, + assertThat( template.queryForList( - "select authority from group_authorities where group_id = 2") - .size()); + "select authority from group_authorities where group_id = 2")).hasSize(2); } // SEC-1156 diff --git a/crypto/src/test/java/org/springframework/security/crypto/bcrypt/BCryptPasswordEncoderTests.java b/crypto/src/test/java/org/springframework/security/crypto/bcrypt/BCryptPasswordEncoderTests.java index ab961bd6d9..a792a6b299 100644 --- a/crypto/src/test/java/org/springframework/security/crypto/bcrypt/BCryptPasswordEncoderTests.java +++ b/crypto/src/test/java/org/springframework/security/crypto/bcrypt/BCryptPasswordEncoderTests.java @@ -15,8 +15,7 @@ */ package org.springframework.security.crypto.bcrypt; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; diff --git a/crypto/src/test/java/org/springframework/security/crypto/bcrypt/BCryptTests.java b/crypto/src/test/java/org/springframework/security/crypto/bcrypt/BCryptTests.java index 41efeebf42..411bbac026 100644 --- a/crypto/src/test/java/org/springframework/security/crypto/bcrypt/BCryptTests.java +++ b/crypto/src/test/java/org/springframework/security/crypto/bcrypt/BCryptTests.java @@ -209,9 +209,9 @@ public class BCryptTests { @Test public void testBase64EncodeSimpleByteArrays() { - assertThat(1)).as("..").isEqualTo(encode_base64(new byte[] { 0 }); - assertThat(0 }).as("...").isCloseTo(encode_base64(new byte[] { 0, within(2))); - assertThat(0 }).as("....").isCloseTo(encode_base64(new byte[] { 0, 0, within(3))); + assertThat(encode_base64(new byte[] { 0 }, 1)).isEqualTo(".."); + assertThat(encode_base64(new byte[] { 0, 0 }, 2)).isEqualTo("..."); + assertThat(encode_base64(new byte[] { 0, 0 , 0 }, 3)).isEqualTo("...."); } @Test @@ -222,16 +222,16 @@ public class BCryptTests { @Test public void decodingStopsWithFirstInvalidCharacter() { - assertThat(1).length).isEqualTo(1, BCrypt.decode_base64("...."); - assertThat(1).length).isEqualTo(0, BCrypt.decode_base64(" ...."); + assertThat(BCrypt.decode_base64("....", 1).length).isEqualTo(1); + assertThat(BCrypt.decode_base64(" ....", 1).length).isEqualTo(0); } @Test public void decodingOnlyProvidesAvailableBytes() { - assertThat(1).length).isEqualTo(0, BCrypt.decode_base64(""); - assertThat(3).length).isEqualTo(3, BCrypt.decode_base64("......"); - assertThat(4).length).isEqualTo(4, BCrypt.decode_base64("......"); - assertThat(5).length).isEqualTo(4, BCrypt.decode_base64("......"); + assertThat(BCrypt.decode_base64("", 1).length).isEqualTo(0); + assertThat(BCrypt.decode_base64("......", 3).length).isEqualTo(3); + assertThat(BCrypt.decode_base64("......", 4).length).isEqualTo(4); + assertThat(BCrypt.decode_base64("......", 5).length).isEqualTo(4); } /** @@ -288,8 +288,8 @@ public class BCryptTests { @Test public void hashpwWorksWithOldRevision() { - assertEquals("$2$05$......................bvpG2UfzdyW/S0ny/4YyEZrmczoJfVm", - BCrypt.hashpw("password", "$2$05$......................")); + assertThat(BCrypt.hashpw("password", "$2$05$......................")).isEqualTo( + "$2$05$......................bvpG2UfzdyW/S0ny/4YyEZrmczoJfVm"); } @Test diff --git a/crypto/src/test/java/org/springframework/security/crypto/codec/Base64Tests.java b/crypto/src/test/java/org/springframework/security/crypto/codec/Base64Tests.java index 3440bf751f..72b6dce637 100644 --- a/crypto/src/test/java/org/springframework/security/crypto/codec/Base64Tests.java +++ b/crypto/src/test/java/org/springframework/security/crypto/codec/Base64Tests.java @@ -13,15 +13,15 @@ public class Base64Tests { public void isBase64ReturnsTrueForValidBase64() { new Base64(); // unused - assertThat(Base64.isBase64(new byte[] { (byte) 'A', (byte) 'B', (byte).isTrue() 'C', - (byte) 'D' })); + assertThat(Base64.isBase64(new byte[] { (byte) 'A', (byte) 'B', (byte) 'C', + (byte) 'D' })).isTrue(); } @Test public void isBase64ReturnsFalseForInvalidBase64() throws Exception { // Include invalid '`' character - assertThat(Base64.isBase64(new byte[] { (byte) 'A', (byte) 'B', (byte).isFalse() 'C', - (byte) '`' })); + assertThat(Base64.isBase64(new byte[] { (byte) 'A', (byte) 'B', (byte) 'C', + (byte) '`' })).isFalse(); } @Test(expected = NullPointerException.class) diff --git a/crypto/src/test/java/org/springframework/security/crypto/encrypt/EncryptorsTests.java b/crypto/src/test/java/org/springframework/security/crypto/encrypt/EncryptorsTests.java index 1c631d2855..0dd0fff497 100644 --- a/crypto/src/test/java/org/springframework/security/crypto/encrypt/EncryptorsTests.java +++ b/crypto/src/test/java/org/springframework/security/crypto/encrypt/EncryptorsTests.java @@ -1,9 +1,7 @@ + package org.springframework.security.crypto.encrypt; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import java.security.GeneralSecurityException; @@ -23,8 +21,8 @@ public class EncryptorsTests { assertThat(result).isNotNull(); assertThat(new String(result).equals("text")).isFalse(); assertThat(new String(encryptor.decrypt(result))).isEqualTo("text"); - assertThat(new String(result).isFalse().equals(new String(encryptor.encrypt("text" - .getBytes())))); + assertThat(new String(result)).isNotEqualTo( + new String(encryptor.encrypt("text".getBytes()))); } @Test @@ -34,8 +32,8 @@ public class EncryptorsTests { assertThat(result).isNotNull(); assertThat(new String(result).equals("text")).isFalse(); assertThat(new String(encryptor.decrypt(result))).isEqualTo("text"); - assertThat(new String(result).isFalse().equals(new String(encryptor.encrypt("text" - .getBytes())))); + assertThat(new String(result)).isNotEqualTo( + new String(encryptor.encrypt("text".getBytes()))); } @Test @@ -62,8 +60,8 @@ public class EncryptorsTests { @Test public void queryableText() { - TextEncryptor encryptor = Encryptors - .queryableText("password", "5c0744940b5c369b"); + TextEncryptor encryptor = Encryptors.queryableText("password", + "5c0744940b5c369b"); String result = encryptor.encrypt("text"); assertThat(result).isNotNull(); assertThat(result.equals("text")).isFalse(); @@ -82,7 +80,8 @@ public class EncryptorsTests { try { Cipher.getInstance("AES/GCM/NoPadding"); return true; - } catch (GeneralSecurityException e) { + } + catch (GeneralSecurityException e) { return false; } } diff --git a/crypto/src/test/java/org/springframework/security/crypto/password/DigesterTests.java b/crypto/src/test/java/org/springframework/security/crypto/password/DigesterTests.java index ee37106dd0..2a77d99494 100644 --- a/crypto/src/test/java/org/springframework/security/crypto/password/DigesterTests.java +++ b/crypto/src/test/java/org/springframework/security/crypto/password/DigesterTests.java @@ -1,10 +1,6 @@ package org.springframework.security.crypto.password; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; - -import java.security.MessageDigest; -import java.util.Arrays; import org.junit.Test; import org.springframework.security.crypto.codec.Hex; @@ -18,8 +14,7 @@ public class DigesterTests { Digester digester = new Digester("SHA-1", 3); byte[] result = digester.digest(Utf8.encode("text")); // echo -n text | openssl sha1 -binary | openssl sha1 -binary | openssl sha1 - assertEquals("3cfa28da425eca5b894f0af2b158adf7001e000f", - new String(Hex.encode(result))); + assertThat(new String(Hex.encode(result))).isEqualTo("3cfa28da425eca5b894f0af2b158adf7001e000f"); } } diff --git a/crypto/src/test/java/org/springframework/security/crypto/password/StandardPasswordEncoderTests.java b/crypto/src/test/java/org/springframework/security/crypto/password/StandardPasswordEncoderTests.java index 17c36b7bcc..cb453e8a50 100644 --- a/crypto/src/test/java/org/springframework/security/crypto/password/StandardPasswordEncoderTests.java +++ b/crypto/src/test/java/org/springframework/security/crypto/password/StandardPasswordEncoderTests.java @@ -1,7 +1,6 @@ package org.springframework.security.crypto.password; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -12,7 +11,7 @@ public class StandardPasswordEncoderTests { @Test public void matches() { String result = encoder.encode("password"); - assertThat(result.equals("password")).isFalse(); + assertThat(result).isNotEqualTo("password"); assertThat(encoder.matches("password", result)).isTrue(); } diff --git a/crypto/src/test/java/org/springframework/security/crypto/util/EncodingUtilsTests.java b/crypto/src/test/java/org/springframework/security/crypto/util/EncodingUtilsTests.java index 856b674260..8ee7f2f197 100644 --- a/crypto/src/test/java/org/springframework/security/crypto/util/EncodingUtilsTests.java +++ b/crypto/src/test/java/org/springframework/security/crypto/util/EncodingUtilsTests.java @@ -1,7 +1,7 @@ + package org.springframework.security.crypto.util; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; import java.util.Arrays; @@ -13,7 +13,7 @@ public class EncodingUtilsTests { @Test public void hexEncode() { byte[] bytes = new byte[] { (byte) 0x01, (byte) 0xFF, (byte) 65, (byte) 66, - (byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 }; + (byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 }; String result = new String(Hex.encode(bytes)); assertThat(result).isEqualTo("01ff414243c0c1c2"); } @@ -21,7 +21,7 @@ public class EncodingUtilsTests { @Test public void hexDecode() { byte[] bytes = new byte[] { (byte) 0x01, (byte) 0xFF, (byte) 65, (byte) 66, - (byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 }; + (byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 }; byte[] result = Hex.decode("01ff414243c0c1c2"); assertThat(Arrays.equals(bytes, result)).isTrue(); } @@ -29,17 +29,18 @@ public class EncodingUtilsTests { @Test public void concatenate() { byte[] bytes = new byte[] { (byte) 0x01, (byte) 0xFF, (byte) 65, (byte) 66, - (byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 }; + (byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 }; byte[] one = new byte[] { (byte) 0x01 }; byte[] two = new byte[] { (byte) 0xFF, (byte) 65, (byte) 66 }; byte[] three = new byte[] { (byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 }; - assertThat(Arrays.equals(bytes, EncodingUtils.concatenate(one, two, three))).isTrue(); + assertThat(Arrays.equals(bytes, + EncodingUtils.concatenate(one, two, three))).isTrue(); } @Test public void subArray() { byte[] bytes = new byte[] { (byte) 0x01, (byte) 0xFF, (byte) 65, (byte) 66, - (byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 }; + (byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 }; byte[] two = new byte[] { (byte) 0xFF, (byte) 65, (byte) 66 }; byte[] subArray = EncodingUtils.subArray(bytes, 1, 4); assertThat(subArray.length).isEqualTo(3); diff --git a/itest/context/src/integration-test/java/org/springframework/security/performance/ProtectPointcutPerformanceTests.java b/itest/context/src/integration-test/java/org/springframework/security/performance/ProtectPointcutPerformanceTests.java index 9fc6c19be3..fbbb93208c 100644 --- a/itest/context/src/integration-test/java/org/springframework/security/performance/ProtectPointcutPerformanceTests.java +++ b/itest/context/src/integration-test/java/org/springframework/security/performance/ProtectPointcutPerformanceTests.java @@ -1,6 +1,7 @@ + package org.springframework.security.performance; -import static junit.framework.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import org.junit.Before; import org.junit.Test; @@ -21,6 +22,7 @@ import org.springframework.util.StopWatch; @ContextConfiguration(locations = { "/protect-pointcut-performance-app-context.xml" }) @RunWith(SpringJUnit4ClassRunner.class) public class ProtectPointcutPerformanceTests implements ApplicationContextAware { + ApplicationContext ctx; @Before @@ -35,8 +37,8 @@ public class ProtectPointcutPerformanceTests implements ApplicationContextAware sw.start(); for (int i = 0; i < 1000; i++) { try { - SessionRegistry reg = (SessionRegistry) ctx - .getBean("sessionRegistryPrototype"); + SessionRegistry reg = (SessionRegistry) ctx.getBean( + "sessionRegistryPrototype"); reg.getAllPrincipals(); fail("Expected AuthenticationCredentialsNotFoundException"); } diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/DefaultSpringSecurityContextSourceTests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/DefaultSpringSecurityContextSourceTests.java index 766de161ed..a13bcbb3a0 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/DefaultSpringSecurityContextSourceTests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/DefaultSpringSecurityContextSourceTests.java @@ -39,8 +39,8 @@ public class DefaultSpringSecurityContextSourceTests extends AbstractLdapIntegra ctxSrc.setUserDn("manager"); ctxSrc.setPassword("password"); ctxSrc.afterPropertiesSet(); - assertThat(ctxSrc.getAuthenticatedEnvForTest("manager", "password").isTrue().containsKey( - AbstractContextSource.SUN_LDAP_POOLING_FLAG)); + assertThat(ctxSrc.getAuthenticatedEnvForTest("manager", "password")).containsKey( + AbstractContextSource.SUN_LDAP_POOLING_FLAG); } @Test @@ -51,8 +51,8 @@ public class DefaultSpringSecurityContextSourceTests extends AbstractLdapIntegra ctxSrc.setUserDn("manager"); ctxSrc.setPassword("password"); ctxSrc.afterPropertiesSet(); - assertThat(ctxSrc.getAuthenticatedEnvForTest("user", "password").isFalse().containsKey( - AbstractContextSource.SUN_LDAP_POOLING_FLAG)); + assertThat(ctxSrc.getAuthenticatedEnvForTest("user", "password")).doesNotContainKey( + AbstractContextSource.SUN_LDAP_POOLING_FLAG); } // SEC-1145. Confirms that there is no issue here with pooling. diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateITests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateITests.java index 4ff927a54e..2a74eeb03a 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateITests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateITests.java @@ -56,14 +56,14 @@ public class SpringSecurityLdapTemplateITests extends AbstractLdapIntegrationTes @Test public void compareOfCorrectByteValueSucceeds() { - assertTrue(template.compare("uid=bob,ou=people", "userPassword", - Utf8.encode("bobspassword"))); + assertThat(template.compare("uid=bob,ou=people", "userPassword", + Utf8.encode("bobspassword"))).isTrue(); } @Test public void compareOfWrongByteValueFails() { - assertFalse(template.compare("uid=bob,ou=people", "userPassword", - Utf8.encode("wrongvalue"))); + assertThat(template.compare("uid=bob,ou=people", "userPassword", + Utf8.encode("wrongvalue"))).isFalse(); } @Test diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorTests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorTests.java index c5c2abd22b..b82424a783 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorTests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorTests.java @@ -59,14 +59,13 @@ public class PasswordComparisonAuthenticatorTests extends AbstractLdapIntegratio public void testAllAttributesAreRetrievedByDefault() { DirContextAdapter user = (DirContextAdapter) authenticator.authenticate(bob); // System.out.println(user.getAttributes().toString()); - assertThat(user.getAttributes()).as("User should have 5 attributes").hasSize(5); + assertThat(user.getAttributes().size()).withFailMessage("User should have 5 attributes").isEqualTo(5); } @Test public void testFailedSearchGivesUserNotFoundException() throws Exception { authenticator = new PasswordComparisonAuthenticator(getContextSource()); - assertTrue("User DN matches shouldn't be available", - authenticator.getUserDns("Bob").isEmpty()); + assertThat(authenticator.getUserDns("Bob")).withFailMessage("User DN matches shouldn't be available").isEmpty(); authenticator.setUserSearch(new MockUserSearch(null)); authenticator.afterPropertiesSet(); @@ -99,8 +98,8 @@ public class PasswordComparisonAuthenticatorTests extends AbstractLdapIntegratio authenticator.setUserAttributes(new String[] { "uid", "userPassword" }); DirContextAdapter user = (DirContextAdapter) authenticator.authenticate(bob); - assertThat(userPassword).isEqualTo("Should have retrieved 2 attribute (uid)", 2, user - .getAttributes().size()); + assertThat(user + .getAttributes().size()).withFailMessage("Should have retrieved 2 attribute (uid)").isEqualTo(2); } @Test @@ -141,8 +140,7 @@ public class PasswordComparisonAuthenticatorTests extends AbstractLdapIntegratio public void testWithUserSearch() { authenticator = new PasswordComparisonAuthenticator(getContextSource()); authenticator.setPasswordEncoder(new PlaintextPasswordEncoder()); - assertTrue("User DN matches shouldn't be available", - authenticator.getUserDns("Bob").isEmpty()); + assertThat(authenticator.getUserDns("Bob")).withFailMessage("User DN matches shouldn't be available").isEmpty(); DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName( "uid=Bob,ou=people")); diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/server/ApacheDSContainerTests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/server/ApacheDSContainerTests.java index a41ed30aa8..2547823cda 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/server/ApacheDSContainerTests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/server/ApacheDSContainerTests.java @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.security.ldap.server; -import static junit.framework.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import java.io.IOException; import java.net.ServerSocket; diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerTests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerTests.java index 080ce7ca80..055b612587 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerTests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerTests.java @@ -12,16 +12,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.security.ldap.userdetails; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import static org.assertj.core.api.Assertions.fail; import java.util.List; -import org.junit.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.springframework.ldap.core.DirContextAdapter; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -32,19 +33,17 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.ldap.AbstractLdapIntegrationTests; import org.springframework.security.ldap.DefaultLdapUsernameToDnMapper; import org.springframework.security.ldap.SpringSecurityLdapTemplate; -import org.springframework.security.ldap.userdetails.InetOrgPerson; -import org.springframework.security.ldap.userdetails.InetOrgPersonContextMapper; -import org.springframework.security.ldap.userdetails.LdapUserDetails; -import org.springframework.security.ldap.userdetails.LdapUserDetailsManager; -import org.springframework.security.ldap.userdetails.PersonContextMapper; /** * @author Luke Taylor */ public class LdapUserDetailsManagerTests extends AbstractLdapIntegrationTests { - private static final List TEST_AUTHORITIES = AuthorityUtils - .createAuthorityList("ROLE_CLOWNS", "ROLE_ACROBATS"); + + private static final List TEST_AUTHORITIES = AuthorityUtils.createAuthorityList( + "ROLE_CLOWNS", "ROLE_ACROBATS"); + private LdapUserDetailsManager mgr; + private SpringSecurityLdapTemplate template; @Before @@ -173,8 +172,9 @@ public class LdapUserDetailsManagerTests extends AbstractLdapIntegrationTests { } // Check that no authorities are left - assertThat("don").isEqualTo(0, mgr.getUserAuthorities(mgr.usernameMapper.buildDn("don")) - .size()); + assertThat( + mgr.getUserAuthorities(mgr.usernameMapper.buildDn("don"), "don")).hasSize( + 0); } @Test @@ -195,8 +195,8 @@ public class LdapUserDetailsManagerTests extends AbstractLdapIntegrationTests { mgr.changePassword("yossarianspassword", "yossariansnewpassword"); - assertTrue(template.compare("uid=johnyossarian,ou=test people", "userPassword", - "yossariansnewpassword")); + assertThat(template.compare("uid=johnyossarian,ou=test people", "userPassword", + "yossariansnewpassword")).isTrue(); } @Test(expected = BadCredentialsException.class) diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/NestedLdapAuthoritiesPopulatorTests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/NestedLdapAuthoritiesPopulatorTests.java index 9e863bf123..e4e867c606 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/NestedLdapAuthoritiesPopulatorTests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/NestedLdapAuthoritiesPopulatorTests.java @@ -72,8 +72,8 @@ public class NestedLdapAuthoritiesPopulatorTests extends AbstractLdapIntegration Collection authorities = populator.getGrantedAuthorities(ctx, "scaladude"); assertThat(authorities).hasSize(5); - assertEquals(Arrays.asList(javaDevelopers, scalaDevelopers, - circularJavaDevelopers, jDevelopers, groovyDevelopers), authorities); + assertThat(Arrays.asList(javaDevelopers, scalaDevelopers, + circularJavaDevelopers, jDevelopers, groovyDevelopers)).isEqualTo(authorities); } @Test @@ -83,8 +83,7 @@ public class NestedLdapAuthoritiesPopulatorTests extends AbstractLdapIntegration Collection authorities = populator.getGrantedAuthorities(ctx, "javadude"); assertThat(authorities).hasSize(3); - assertThat(circularJavaDevelopers).isCloseTo(Arrays.asList(javaDevelopers, within(jDevelopers)), - authorities); + assertThat(authorities).contains(javaDevelopers); } @Test @@ -105,8 +104,8 @@ public class NestedLdapAuthoritiesPopulatorTests extends AbstractLdapIntegration Collection authorities = populator.getGrantedAuthorities(ctx, "groovydude"); assertThat(authorities).hasSize(4); - assertEquals(Arrays.asList(javaDevelopers, circularJavaDevelopers, jDevelopers, - groovyDevelopers), authorities); + assertThat(authorities).isEqualTo(Arrays.asList(javaDevelopers, circularJavaDevelopers, jDevelopers, + groovyDevelopers)); } @Test @@ -118,8 +117,8 @@ public class NestedLdapAuthoritiesPopulatorTests extends AbstractLdapIntegration Collection authorities = populator.getGrantedAuthorities(ctx, "closuredude"); assertThat(authorities).hasSize(5); - assertEquals(Arrays.asList(closureDevelopers, javaDevelopers, - circularJavaDevelopers, jDevelopers, groovyDevelopers), authorities); + assertThat(authorities).isEqualTo(Arrays.asList(closureDevelopers, javaDevelopers, + circularJavaDevelopers, jDevelopers, groovyDevelopers)); LdapAuthority[] ldapAuthorities = authorities.toArray(new LdapAuthority[0]); assertThat(ldapAuthorities.length).isEqualTo(5); @@ -127,17 +126,14 @@ public class NestedLdapAuthoritiesPopulatorTests extends AbstractLdapIntegration assertThat(ldapAuthorities[0].getAttributes().containsKey("member")).isTrue(); assertThat(ldapAuthorities[0].getAttributes().get("member")).isNotNull(); assertThat(ldapAuthorities[0].getAttributes().get("member")).hasSize(1); - assertEquals("uid=closuredude,ou=people,dc=springframework,dc=org", - ldapAuthorities[0].getFirstAttributeValue("member")); + assertThat(ldapAuthorities[0].getFirstAttributeValue("member")).isEqualTo("uid=closuredude,ou=people,dc=springframework,dc=org"); // java group assertThat(ldapAuthorities[1].getAttributes().containsKey("member")).isTrue(); assertThat(ldapAuthorities[1].getAttributes().get("member")).isNotNull(); assertThat(ldapAuthorities[1].getAttributes().get("member")).hasSize(3); - assertEquals(groovyDevelopers.getDn(), - ldapAuthorities[1].getFirstAttributeValue("member")); - assertThat(scalaDevelopers.getDn().isEqualTo(new String[] { groovyDevelopers.getDn()), - "uid=javadude,ou=people,dc=springframework,dc=org" }, ldapAuthorities[1] + assertThat(groovyDevelopers.getDn()).isEqualTo(ldapAuthorities[1].getFirstAttributeValue("member")); + assertThat(scalaDevelopers.getDn()).isEqualTo(ldapAuthorities[2] .getAttributes().get("member")); // test non existent attribute diff --git a/ldap/src/test/java/org/springframework/security/ldap/LdapUtilsTests.java b/ldap/src/test/java/org/springframework/security/ldap/LdapUtilsTests.java index 3423f8ffd9..c141dd70f6 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/LdapUtilsTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/LdapUtilsTests.java @@ -48,7 +48,7 @@ public class LdapUtilsTests { when(mockCtx.getNameInNamespace()).thenReturn("dc=springframework,dc=org"); - assertThat(dc=org").as("").isCloseTo(LdapUtils.getRelativeName("dc=springframework, within(mockCtx))); + assertThat(LdapUtils.getRelativeName("dc=springframework,dc=org",mockCtx)).isEqualTo(""); } @Test @@ -56,8 +56,7 @@ public class LdapUtilsTests { final DirContext mockCtx = mock(DirContext.class); when(mockCtx.getNameInNamespace()).thenReturn(""); - assertEquals("cn=jane,dc=springframework,dc=org", - LdapUtils.getRelativeName("cn=jane,dc=springframework,dc=org", mockCtx)); + assertThat(LdapUtils.getRelativeName("cn=jane,dc=springframework,dc=org", mockCtx)).isEqualTo("cn=jane,dc=springframework,dc=org"); } @Test @@ -65,8 +64,8 @@ public class LdapUtilsTests { final DirContext mockCtx = mock(DirContext.class); when(mockCtx.getNameInNamespace()).thenReturn("dc=springsecurity,dc = org"); - assertEquals("cn=jane smith", LdapUtils.getRelativeName( - "cn=jane smith, dc = springsecurity , dc=org", mockCtx)); + assertThat(LdapUtils.getRelativeName( + "cn=jane smith, dc = springsecurity , dc=org", mockCtx)).isEqualTo("cn=jane smith"); } @Test @@ -75,23 +74,19 @@ public class LdapUtilsTests { assertThat(LdapUtils.parseRootDnFromUrl("ldap://monkeymachine:11389")).isEqualTo(""); assertThat(LdapUtils.parseRootDnFromUrl("ldap://monkeymachine/")).isEqualTo(""); assertThat(LdapUtils.parseRootDnFromUrl("ldap://monkeymachine.co.uk/")).isEqualTo(""); - assertEquals( - "dc=springframework,dc=org", + assertThat( LdapUtils - .parseRootDnFromUrl("ldaps://monkeymachine.co.uk/dc=springframework,dc=org")); - assertEquals("dc=springframework,dc=org", - LdapUtils.parseRootDnFromUrl("ldap:///dc=springframework,dc=org")); - assertEquals( - "dc=springframework,dc=org", + .parseRootDnFromUrl("ldaps://monkeymachine.co.uk/dc=springframework,dc=org")).isEqualTo("dc=springframework,dc=org"); + assertThat( + LdapUtils.parseRootDnFromUrl("ldap:///dc=springframework,dc=org")).isEqualTo("dc=springframework,dc=org"); + assertThat( LdapUtils - .parseRootDnFromUrl("ldap://monkeymachine/dc=springframework,dc=org")); - assertEquals( - "dc=springframework,dc=org/ou=blah", + .parseRootDnFromUrl("ldap://monkeymachine/dc=springframework,dc=org")).isEqualTo("dc=springframework,dc=org"); + assertThat( LdapUtils - .parseRootDnFromUrl("ldap://monkeymachine.co.uk/dc=springframework,dc=org/ou=blah")); - assertEquals( - "dc=springframework,dc=org/ou=blah", + .parseRootDnFromUrl("ldap://monkeymachine.co.uk/dc=springframework,dc=org/ou=blah")).isEqualTo("dc=springframework,dc=org/ou=blah"); + assertThat( LdapUtils - .parseRootDnFromUrl("ldap://monkeymachine.co.uk:389/dc=springframework,dc=org/ou=blah")); + .parseRootDnFromUrl("ldap://monkeymachine.co.uk:389/dc=springframework,dc=org/ou=blah")).isEqualTo("dc=springframework,dc=org/ou=blah"); } } diff --git a/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java b/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java index 9794ddd399..e19c4a76ba 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java @@ -136,9 +136,9 @@ public class LdapAuthenticationProviderTests { assertThat(user.getUsername()).isEqualTo("ben"); assertThat(populator.getRequestedUsername()).isEqualTo("ben"); - assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains( + assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains( "ROLE_FROM_ENTRY")); - assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains( + assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains( "ROLE_FROM_POPULATOR")); } @@ -167,7 +167,7 @@ public class LdapAuthenticationProviderTests { UserDetails user = (UserDetails) ldapProvider.authenticate(authRequest) .getPrincipal(); assertThat(user.getAuthorities()).hasSize(1); - assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains( + assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains( "ROLE_FROM_ENTRY")); } diff --git a/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapShaPasswordEncoderTests.java b/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapShaPasswordEncoderTests.java index 89770cc289..13c260ef24 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapShaPasswordEncoderTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapShaPasswordEncoderTests.java @@ -42,16 +42,16 @@ public class LdapShaPasswordEncoderTests { @Test public void invalidPasswordFails() { - assertFalse(sha.isPasswordValid("{SHA}ddSFGmjXYPbZC+NXR2kCzBRjqiE=", - "wrongpassword", null)); + assertThat(sha.isPasswordValid("{SHA}ddSFGmjXYPbZC+NXR2kCzBRjqiE=", + "wrongpassword", null)).isFalse(); } @Test public void invalidSaltedPasswordFails() { - assertFalse(sha.isPasswordValid("{SSHA}25ro4PKC8jhQZ26jVsozhX/xaP0suHgX", - "wrongpassword", null)); - assertFalse(sha.isPasswordValid("{SSHA}PQy2j+6n5ytA+YlAKkM8Fh4p6u2JxfVd", - "wrongpassword", null)); + assertThat(sha.isPasswordValid("{SSHA}25ro4PKC8jhQZ26jVsozhX/xaP0suHgX", + "wrongpassword", null)).isFalse(); + assertThat(sha.isPasswordValid("{SSHA}PQy2j+6n5ytA+YlAKkM8Fh4p6u2JxfVd", + "wrongpassword", null)).isFalse(); } @Test(expected = IllegalArgumentException.class) @@ -65,15 +65,15 @@ public class LdapShaPasswordEncoderTests { @Test public void validPasswordSucceeds() { sha.setForceLowerCasePrefix(false); - assertTrue(sha.isPasswordValid("{SHA}ddSFGmjXYPbZC+NXR2kCzBRjqiE=", - "boabspasswurd", null)); - assertTrue(sha.isPasswordValid("{sha}ddSFGmjXYPbZC+NXR2kCzBRjqiE=", - "boabspasswurd", null)); + assertThat(sha.isPasswordValid("{SHA}ddSFGmjXYPbZC+NXR2kCzBRjqiE=", + "boabspasswurd", null)).isTrue(); + assertThat(sha.isPasswordValid("{sha}ddSFGmjXYPbZC+NXR2kCzBRjqiE=", + "boabspasswurd", null)).isTrue(); sha.setForceLowerCasePrefix(true); - assertTrue(sha.isPasswordValid("{SHA}ddSFGmjXYPbZC+NXR2kCzBRjqiE=", - "boabspasswurd", null)); - assertTrue(sha.isPasswordValid("{sha}ddSFGmjXYPbZC+NXR2kCzBRjqiE=", - "boabspasswurd", null)); + assertThat(sha.isPasswordValid("{SHA}ddSFGmjXYPbZC+NXR2kCzBRjqiE=", + "boabspasswurd", null)).isTrue(); + assertThat(sha.isPasswordValid("{sha}ddSFGmjXYPbZC+NXR2kCzBRjqiE=", + "boabspasswurd", null)).isTrue(); } /** @@ -82,40 +82,40 @@ public class LdapShaPasswordEncoderTests { @Test public void validSaltedPasswordSucceeds() { sha.setForceLowerCasePrefix(false); - assertTrue(sha.isPasswordValid("{SSHA}25ro4PKC8jhQZ26jVsozhX/xaP0suHgX", - "boabspasswurd", null)); - assertTrue(sha.isPasswordValid("{ssha}PQy2j+6n5ytA+YlAKkM8Fh4p6u2JxfVd", - "boabspasswurd", null)); + assertThat(sha.isPasswordValid("{SSHA}25ro4PKC8jhQZ26jVsozhX/xaP0suHgX", + "boabspasswurd", null)).isTrue(); + assertThat(sha.isPasswordValid("{ssha}PQy2j+6n5ytA+YlAKkM8Fh4p6u2JxfVd", + "boabspasswurd", null)).isTrue(); sha.setForceLowerCasePrefix(true); - assertTrue(sha.isPasswordValid("{SSHA}25ro4PKC8jhQZ26jVsozhX/xaP0suHgX", - "boabspasswurd", null)); - assertTrue(sha.isPasswordValid("{ssha}PQy2j+6n5ytA+YlAKkM8Fh4p6u2JxfVd", - "boabspasswurd", null)); + assertThat(sha.isPasswordValid("{SSHA}25ro4PKC8jhQZ26jVsozhX/xaP0suHgX", + "boabspasswurd", null)).isTrue(); + assertThat(sha.isPasswordValid("{ssha}PQy2j+6n5ytA+YlAKkM8Fh4p6u2JxfVd", + "boabspasswurd", null)).isTrue(); } @Test // SEC-1031 public void fullLengthOfHashIsUsedInComparison() throws Exception { // Change the first hash character from '2' to '3' - assertFalse(sha.isPasswordValid("{SSHA}35ro4PKC8jhQZ26jVsozhX/xaP0suHgX", - "boabspasswurd", null)); + assertThat(sha.isPasswordValid("{SSHA}35ro4PKC8jhQZ26jVsozhX/xaP0suHgX", + "boabspasswurd", null)).isFalse(); // Change the last hash character from 'X' to 'Y' - assertFalse(sha.isPasswordValid("{SSHA}25ro4PKC8jhQZ26jVsozhX/xaP0suHgY", - "boabspasswurd", null)); + assertThat(sha.isPasswordValid("{SSHA}25ro4PKC8jhQZ26jVsozhX/xaP0suHgY", + "boabspasswurd", null)).isFalse(); } @Test public void correctPrefixCaseIsUsed() { sha.setForceLowerCasePrefix(false); - assertEquals("{SHA}ddSFGmjXYPbZC+NXR2kCzBRjqiE=", + assertThat("{SHA}ddSFGmjXYPbZC+NXR2kCzBRjqiE=").isEqualTo( sha.encodePassword("boabspasswurd", null)); - assertThat(sha.encodePassword("somepassword", "salt".getBytes()).isTrue().startsWith( + assertThat(sha.encodePassword("somepassword", "salt".getBytes()).startsWith( "{SSHA}")); sha.setForceLowerCasePrefix(true); - assertEquals("{sha}ddSFGmjXYPbZC+NXR2kCzBRjqiE=", + assertThat("{sha}ddSFGmjXYPbZC+NXR2kCzBRjqiE=").isEqualTo( sha.encodePassword("boabspasswurd", null)); - assertThat(sha.encodePassword("somepassword", "salt".getBytes()).isTrue().startsWith( + assertThat(sha.encodePassword("somepassword", "salt".getBytes()).startsWith( "{ssha}")); } diff --git a/ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java b/ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java index 302a08606b..9f790ea5cc 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java @@ -46,8 +46,6 @@ import javax.naming.directory.SearchResult; import java.util.Hashtable; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.*; import static org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider.ContextFactory; @@ -327,7 +325,7 @@ public class ActiveDirectoryLdapAuthenticationProviderTests { try { provider.authenticate(joe); - fail(); + fail("BadCredentialsException should had been thrown"); } catch (BadCredentialsException expected) { } diff --git a/ldap/src/test/java/org/springframework/security/ldap/ppolicy/OpenLDAPIntegrationTestSuite.java b/ldap/src/test/java/org/springframework/security/ldap/ppolicy/OpenLDAPIntegrationTestSuite.java index 521ed1b285..6e2612e651 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/ppolicy/OpenLDAPIntegrationTestSuite.java +++ b/ldap/src/test/java/org/springframework/security/ldap/ppolicy/OpenLDAPIntegrationTestSuite.java @@ -1,26 +1,17 @@ + package org.springframework.security.ldap.ppolicy; -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.LockedException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.ldap.authentication.BindAuthenticator; -import org.springframework.security.ldap.authentication.LdapAuthenticationProvider; -import org.springframework.security.ldap.userdetails.LdapUserDetailsImpl; - /** * Test cases which run against an OpenLDAP server. *

* Run the script in the module root to start the server and import the data before * running. + * * @author Luke Taylor * @since 3.0 */ public class OpenLDAPIntegrationTestSuite { + PasswordPolicyAwareContextSource cs; /* * @Before public void createContextSource() throws Exception { cs = new diff --git a/ldap/src/test/java/org/springframework/security/ldap/ppolicy/PasswordPolicyAwareContextSourceTests.java b/ldap/src/test/java/org/springframework/security/ldap/ppolicy/PasswordPolicyAwareContextSourceTests.java index 00a606921c..f80c7d070e 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/ppolicy/PasswordPolicyAwareContextSourceTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/ppolicy/PasswordPolicyAwareContextSourceTests.java @@ -1,6 +1,6 @@ package org.springframework.security.ldap.ppolicy; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import org.junit.*; diff --git a/ldap/src/test/java/org/springframework/security/ldap/ppolicy/PasswordPolicyControlFactoryTests.java b/ldap/src/test/java/org/springframework/security/ldap/ppolicy/PasswordPolicyControlFactoryTests.java index cc86d44ced..2837c362e9 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/ppolicy/PasswordPolicyControlFactoryTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/ppolicy/PasswordPolicyControlFactoryTests.java @@ -32,7 +32,6 @@ public class PasswordPolicyControlFactoryTests { PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL); Control result = ctrlFactory.getControlInstance(control); assertThat(result).isNotNull(); - assertTrue(Arrays.equals(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL, - result.getEncodedValue())); + assertThat(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL).isEqualTo(result.getEncodedValue()); } } diff --git a/ldap/src/test/java/org/springframework/security/ldap/userdetails/LdapAuthorityTests.java b/ldap/src/test/java/org/springframework/security/ldap/userdetails/LdapAuthorityTests.java index fa8b6dc288..3d3a19b9e4 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/userdetails/LdapAuthorityTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/userdetails/LdapAuthorityTests.java @@ -10,7 +10,6 @@ import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotNull; /** * @author Filip Hanik @@ -33,10 +32,8 @@ public class LdapAuthorityTests { public void testGetDn() throws Exception { assertThat(authority.getDn()).isEqualTo(DN); assertThat(authority.getAttributeValues(SpringSecurityLdapTemplate.DN_KEY)).isNotNull(); - assertThat(authority.getAttributeValues(SpringSecurityLdapTemplate.DN_KEY).isEqualTo(1) - .size()); - assertEquals(DN, - authority.getFirstAttributeValue(SpringSecurityLdapTemplate.DN_KEY)); + assertThat(authority.getAttributeValues(SpringSecurityLdapTemplate.DN_KEY)).hasSize(1); + assertThat(authority.getFirstAttributeValue(SpringSecurityLdapTemplate.DN_KEY)).isEqualTo(DN); } @Test diff --git a/ldap/src/test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsMapperTests.java b/ldap/src/test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsMapperTests.java index 90466ea453..f47153c72d 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsMapperTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsMapperTests.java @@ -15,11 +15,12 @@ package org.springframework.security.ldap.userdetails; +import static org.assertj.core.api.Assertions.assertThat; + import javax.naming.directory.BasicAttribute; import javax.naming.directory.BasicAttributes; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.ldap.core.DirContextAdapter; import org.springframework.ldap.core.DistinguishedName; import org.springframework.security.core.authority.AuthorityUtils; @@ -29,8 +30,9 @@ import org.springframework.security.core.authority.AuthorityUtils; * * @author Luke Taylor */ -public class LdapUserDetailsMapperTests extends TestCase { +public class LdapUserDetailsMapperTests { + @Test public void testMultipleRoleAttributeValuesAreMappedToAuthorities() throws Exception { LdapUserDetailsMapper mapper = new LdapUserDetailsMapper(); mapper.setConvertToUpperCase(false); @@ -52,6 +54,7 @@ public class LdapUserDetailsMapperTests extends TestCase { /** * SEC-303. Non-retrieved role attribute causes NullPointerException */ + @Test public void testNonRetrievedRoleAttributeIsIgnored() throws Exception { LdapUserDetailsMapper mapper = new LdapUserDetailsMapper(); @@ -60,18 +63,19 @@ public class LdapUserDetailsMapperTests extends TestCase { BasicAttributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("userRole", "x")); - DirContextAdapter ctx = new DirContextAdapter(attrs, new DistinguishedName( - "cn=someName")); + DirContextAdapter ctx = new DirContextAdapter(attrs, + new DistinguishedName("cn=someName")); ctx.setAttributeValue("uid", "ani"); LdapUserDetailsImpl user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, "ani", AuthorityUtils.NO_AUTHORITIES); assertThat(user.getAuthorities()).hasSize(1); - assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains( + assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains( "ROLE_X")); } + @Test public void testPasswordAttributeIsMappedCorrectly() throws Exception { LdapUserDetailsMapper mapper = new LdapUserDetailsMapper(); @@ -79,12 +83,12 @@ public class LdapUserDetailsMapperTests extends TestCase { BasicAttributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("myappsPassword", "mypassword".getBytes())); - DirContextAdapter ctx = new DirContextAdapter(attrs, new DistinguishedName( - "cn=someName")); + DirContextAdapter ctx = new DirContextAdapter(attrs, + new DistinguishedName("cn=someName")); ctx.setAttributeValue("uid", "ani"); - LdapUserDetails user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, - "ani", AuthorityUtils.NO_AUTHORITIES); + LdapUserDetails user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, "ani", + AuthorityUtils.NO_AUTHORITIES); assertThat(user.getPassword()).isEqualTo("mypassword"); } diff --git a/messaging/src/test/java/org/springframework/security/messaging/context/SecurityContextChannelInterceptorTests.java b/messaging/src/test/java/org/springframework/security/messaging/context/SecurityContextChannelInterceptorTests.java index 0141bc3965..bad9317e56 100644 --- a/messaging/src/test/java/org/springframework/security/messaging/context/SecurityContextChannelInterceptorTests.java +++ b/messaging/src/test/java/org/springframework/security/messaging/context/SecurityContextChannelInterceptorTests.java @@ -250,8 +250,8 @@ public class SecurityContextChannelInterceptorTests { AnonymousAuthenticationToken anonymous = (AnonymousAuthenticationToken) currentAuthentication; assertThat(anonymous.getName()).isEqualTo(expectedAnonymous.getName()); - assertThat(anonymous.getAuthorities()).containsOnly( - expectedAnonymous.getAuthorities().toArray()); + assertThat(anonymous.getAuthorities()).containsOnlyElementsOf( + expectedAnonymous.getAuthorities()); assertThat(anonymous.getKeyHash()).isEqualTo(expectedAnonymous.getKeyHash()); } } \ No newline at end of file diff --git a/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java b/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java index 27d3ad3d9d..9033c6e374 100644 --- a/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java +++ b/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java @@ -47,12 +47,10 @@ public class OpenID4JavaConsumerTests { MockHttpServletRequest request = new MockHttpServletRequest(); consumer.beginConsumption(request, "", "", ""); - assertEquals( - attributes, - request.getSession().getAttribute( - "SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST")); - assertSame(di, - request.getSession().getAttribute(DiscoveryInformation.class.getName())); + assertThat(request.getSession().getAttribute( + "SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST")).isEqualTo(attributes); + assertThat( + request.getSession().getAttribute(DiscoveryInformation.class.getName())).isEqualTo(di); // Check with empty attribute fetch list consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); @@ -82,14 +80,14 @@ public class OpenID4JavaConsumerTests { try { consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""); - fail(); + fail("OpenIDConsumerException was not thrown"); } catch (OpenIDConsumerException expected) { } try { consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""); - fail(); + fail("OpenIDConsumerException was not thrown"); } catch (OpenIDConsumerException expected) { } @@ -134,21 +132,21 @@ public class OpenID4JavaConsumerTests { try { consumer.endConsumption(request); - fail(); + fail("OpenIDConsumerException was not thrown"); } catch (OpenIDConsumerException expected) { } try { consumer.endConsumption(request); - fail(); + fail("OpenIDConsumerException was not thrown"); } catch (OpenIDConsumerException expected) { } try { consumer.endConsumption(request); - fail(); + fail("OpenIDConsumerException was not thrown"); } catch (OpenIDConsumerException expected) { } diff --git a/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java b/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java index 24bd64ae9e..44a49dc33f 100644 --- a/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java +++ b/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java @@ -88,8 +88,8 @@ public class OpenIDAuthenticationFilterTests { URI returnTo = new URI(filter.buildReturnToUrl(req)); String query = returnTo.getRawQuery(); - assertThat(count(query).isCloseTo(1, within('='))); - assertThat(count(query).isCloseTo(0, within('&'))); + assertThat(count(query, '=')).isEqualTo(1); + assertThat(count(query, '&')).isEqualTo(0); } /** diff --git a/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationProviderTests.java b/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationProviderTests.java index 3132a6e551..ff05badba7 100644 --- a/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationProviderTests.java +++ b/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationProviderTests.java @@ -12,10 +12,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.security.openid; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import org.junit.Test; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -33,7 +36,7 @@ import org.springframework.security.core.userdetails.UserDetailsService; * * @author Robin Bramley, Opsera Ltd */ -public class OpenIDAuthenticationProviderTests extends TestCase { +public class OpenIDAuthenticationProviderTests { // ~ Static fields/initializers // ===================================================================================== @@ -44,8 +47,10 @@ public class OpenIDAuthenticationProviderTests extends TestCase { /* * Test method for - * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.authenticate(Authentication)' + * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider. + * authenticate(Authentication)' */ + @Test public void testAuthenticateCancel() { OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); provider.setUserDetailsService(new MockUserDetailsService()); @@ -67,8 +72,10 @@ public class OpenIDAuthenticationProviderTests extends TestCase { /* * Test method for - * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.authenticate(Authentication)' + * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider. + * authenticate(Authentication)' */ + @Test public void testAuthenticateError() { OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); provider.setUserDetailsService(new MockUserDetailsService()); @@ -89,12 +96,15 @@ public class OpenIDAuthenticationProviderTests extends TestCase { /* * Test method for - * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.authenticate(Authentication)' + * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider. + * authenticate(Authentication)' */ + @Test public void testAuthenticateFailure() { OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); - provider.setAuthenticationUserDetailsService(new UserDetailsByNameServiceWrapper( - new MockUserDetailsService())); + provider.setAuthenticationUserDetailsService( + new UserDetailsByNameServiceWrapper( + new MockUserDetailsService())); Authentication preAuth = new OpenIDAuthenticationToken( OpenIDAuthenticationStatus.FAILURE, USERNAME, "", null); @@ -106,15 +116,17 @@ public class OpenIDAuthenticationProviderTests extends TestCase { fail("Should throw an AuthenticationException"); } catch (BadCredentialsException expected) { - assertEquals("Log in failed - identity could not be verified", + assertThat("Log in failed - identity could not be verified").isEqualTo( expected.getMessage()); } } /* * Test method for - * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.authenticate(Authentication)' + * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider. + * authenticate(Authentication)' */ + @Test public void testAuthenticateSetupNeeded() { OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); provider.setUserDetailsService(new MockUserDetailsService()); @@ -129,15 +141,18 @@ public class OpenIDAuthenticationProviderTests extends TestCase { fail("Should throw an AuthenticationException"); } catch (AuthenticationServiceException expected) { - assertEquals("The server responded setup was needed, which shouldn't happen", - expected.getMessage()); + assertThat( + "The server responded setup was needed, which shouldn't happen").isEqualTo( + expected.getMessage()); } } /* * Test method for - * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.authenticate(Authentication)' + * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider. + * authenticate(Authentication)' */ + @Test public void testAuthenticateSuccess() { OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); provider.setUserDetailsService(new MockUserDetailsService()); @@ -156,10 +171,12 @@ public class OpenIDAuthenticationProviderTests extends TestCase { assertThat(postAuth.getPrincipal() instanceof UserDetails).isTrue(); assertThat(postAuth.getAuthorities()).isNotNull(); assertThat(postAuth.getAuthorities().size() > 0).isTrue(); - assertThat(((OpenIDAuthenticationToken) postAuth).getStatus() == OpenIDAuthenticationStatus.SUCCESS).isTrue(); + assertThat( + ((OpenIDAuthenticationToken) postAuth).getStatus() == OpenIDAuthenticationStatus.SUCCESS).isTrue(); assertThat(((OpenIDAuthenticationToken) postAuth).getMessage() == null).isTrue(); } + @Test public void testDetectsMissingAuthoritiesPopulator() throws Exception { OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); @@ -174,19 +191,24 @@ public class OpenIDAuthenticationProviderTests extends TestCase { /* * Test method for - * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.supports(Class)' + * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider. + * supports(Class)' */ + @Test public void testDoesntSupport() { OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); provider.setUserDetailsService(new MockUserDetailsService()); - assertThat(provider.supports(UsernamePasswordAuthenticationToken.class)).isFalse(); + assertThat( + provider.supports(UsernamePasswordAuthenticationToken.class)).isFalse(); } /* * Test method for - * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.authenticate(Authentication)' + * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider. + * authenticate(Authentication)' */ + @Test public void testIgnoresUserPassAuthToken() { OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); provider.setUserDetailsService(new MockUserDetailsService()); @@ -198,8 +220,10 @@ public class OpenIDAuthenticationProviderTests extends TestCase { /* * Test method for - * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.supports(Class)' + * 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider. + * supports(Class)' */ + @Test public void testSupports() { OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); provider.setUserDetailsService(new MockUserDetailsService()); @@ -207,6 +231,7 @@ public class OpenIDAuthenticationProviderTests extends TestCase { assertThat(provider.supports(OpenIDAuthenticationToken.class)).isTrue(); } + @Test public void testValidation() throws Exception { OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); try { @@ -223,6 +248,7 @@ public class OpenIDAuthenticationProviderTests extends TestCase { } static class MockUserDetailsService implements UserDetailsService { + public UserDetails loadUserByUsername(String ssoUserId) throws AuthenticationException { return new User(ssoUserId, "password", true, true, true, true, diff --git a/remoting/src/test/java/org/springframework/security/remoting/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutorTests.java b/remoting/src/test/java/org/springframework/security/remoting/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutorTests.java index 13ae5cfef6..dd9fafd426 100644 --- a/remoting/src/test/java/org/springframework/security/remoting/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutorTests.java +++ b/remoting/src/test/java/org/springframework/security/remoting/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutorTests.java @@ -15,40 +15,38 @@ package org.springframework.security.remoting.httpinvoker; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.assertThat; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +import org.junit.After; +import org.junit.Test; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.remoting.httpinvoker.AuthenticationSimpleHttpInvokerRequestExecutor; - -import java.io.IOException; - -import java.net.HttpURLConnection; -import java.net.URL; - -import java.util.HashMap; -import java.util.Map; - /** * Tests {@link AuthenticationSimpleHttpInvokerRequestExecutor}. * * @author Ben Alex * @author Rob Winch */ -public class AuthenticationSimpleHttpInvokerRequestExecutorTests extends TestCase { +public class AuthenticationSimpleHttpInvokerRequestExecutorTests { // ~ Methods // ======================================================================================================== - - protected void tearDown() throws Exception { - super.tearDown(); + @After + public void tearDown() throws Exception { SecurityContextHolder.clearContext(); } + @Test public void testNormalOperation() throws Exception { // Setup client-side context Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken( @@ -64,10 +62,11 @@ public class AuthenticationSimpleHttpInvokerRequestExecutorTests extends TestCas // Check connection properties // See http://www.faqs.org/rfcs/rfc1945.html section 11.1 for example // we are comparing against - assertEquals("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", - conn.getRequestProperty("Authorization")); + assertThat(conn.getRequestProperty("Authorization")).isEqualTo( + "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); } + @Test public void testNullContextHolderIsNull() throws Exception { SecurityContextHolder.getContext().setAuthentication(null); @@ -82,6 +81,7 @@ public class AuthenticationSimpleHttpInvokerRequestExecutorTests extends TestCas } // SEC-1975 + @Test public void testNullContextHolderWhenAnonymous() throws Exception { AnonymousAuthenticationToken anonymous = new AnonymousAuthenticationToken("key", "principal", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); @@ -101,6 +101,7 @@ public class AuthenticationSimpleHttpInvokerRequestExecutorTests extends TestCas // ================================================================================================== private class MockHttpURLConnection extends HttpURLConnection { + private Map requestProperties = new HashMap(); public MockHttpURLConnection(URL u) { diff --git a/remoting/src/test/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocationTests.java b/remoting/src/test/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocationTests.java index 99338e03d3..ed0151c492 100644 --- a/remoting/src/test/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocationTests.java +++ b/remoting/src/test/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocationTests.java @@ -15,8 +15,14 @@ package org.springframework.security.remoting.rmi; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +import java.lang.reflect.Method; + import org.aopalliance.intercept.MethodInvocation; +import org.junit.After; +import org.junit.Test; import org.springframework.security.TargetObject; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; @@ -24,21 +30,18 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.util.SimpleMethodInvocation; import org.springframework.test.util.ReflectionTestUtils; -import java.lang.reflect.Method; - /** * Tests {@link ContextPropagatingRemoteInvocation} and * {@link ContextPropagatingRemoteInvocationFactory}. * * @author Ben Alex */ -public class ContextPropagatingRemoteInvocationTests extends TestCase { +public class ContextPropagatingRemoteInvocationTests { // ~ Methods // ======================================================================================================== - - protected void tearDown() throws Exception { - super.tearDown(); + @After + public void tearDown() throws Exception { SecurityContextHolder.clearContext(); } @@ -53,6 +56,7 @@ public class ContextPropagatingRemoteInvocationTests extends TestCase { return (ContextPropagatingRemoteInvocation) factory.createRemoteInvocation(mi); } + @Test public void testContextIsResetEvenIfExceptionOccurs() throws Exception { // Setup client-side context Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken( @@ -71,10 +75,12 @@ public class ContextPropagatingRemoteInvocationTests extends TestCase { // expected } - assertThat(SecurityContextHolder.getContext().as("Authentication must be null ").isNull() - .getAuthentication()); + assertThat( + SecurityContextHolder.getContext().getAuthentication()).withFailMessage( + "Authentication must be null").isNull(); } + @Test public void testNormalOperation() throws Exception { // Setup client-side context Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken( @@ -90,28 +96,31 @@ public class ContextPropagatingRemoteInvocationTests extends TestCase { // The result from invoking the TargetObject should contain the // Authentication class delivered via the SecurityContextHolder - assertEquals( - "some_string org.springframework.security.authentication.UsernamePasswordAuthenticationToken false", - remoteInvocation.invoke(new TargetObject())); + assertThat(remoteInvocation.invoke(new TargetObject())).isEqualTo( + "some_string org.springframework.security.authentication.UsernamePasswordAuthenticationToken false"); } + @Test public void testNullContextHolderDoesNotCauseInvocationProblems() throws Exception { SecurityContextHolder.clearContext(); // just to be explicit ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation(); - SecurityContextHolder.clearContext(); // unnecessary, but for explicitness + SecurityContextHolder.clearContext(); // unnecessary, but for + // explicitness - assertEquals("some_string Authentication empty", - remoteInvocation.invoke(new TargetObject())); + assertThat(remoteInvocation.invoke(new TargetObject())).isEqualTo( + "some_string Authentication empty"); } // SEC-1867 + @Test public void testNullCredentials() throws Exception { Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken( "rod", null); SecurityContextHolder.getContext().setAuthentication(clientSideAuthentication); ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation(); - assertThat("credentials")).isEqualTo(null, ReflectionTestUtils.getField(remoteInvocation); + assertThat( + ReflectionTestUtils.getField(remoteInvocation, "credentials")).isNull(); } } diff --git a/samples/dms-xml/src/test/java/DmsIntegrationTests.java b/samples/dms-xml/src/test/java/DmsIntegrationTests.java index 7fb84a471b..793b2ff05a 100644 --- a/samples/dms-xml/src/test/java/DmsIntegrationTests.java +++ b/samples/dms-xml/src/test/java/DmsIntegrationTests.java @@ -40,8 +40,8 @@ public class DmsIntegrationTests extends AbstractTransactionalJUnit4SpringContex @Test public void testBasePopulation() { - assertThat(Integer.class)).isEqualTo(9, (int) jdbcTemplate.queryForObject("select count(id) from DIRECTORY"); - assertThat(Integer.class)).isEqualTo(90, (int) jdbcTemplate.queryForObject("select count(id) from FILE"); + assertThat(jdbcTemplate.queryForObject("select count(id) from DIRECTORY", Integer.class)).isEqualTo(9); + assertThat((int) jdbcTemplate.queryForObject("select count(id) from FILE", Integer.class)).isEqualTo(90); assertThat(documentDao.findElements(Directory.ROOT_DIRECTORY).length).isEqualTo(3); } @@ -104,8 +104,7 @@ public class DmsIntegrationTests extends AbstractTransactionalJUnit4SpringContex } if (shouldBeFiltered) { - assertNull("Found confidential directory when we should not have", - nonHomeConfidentialDir); + assertThat(nonHomeConfidentialDir).withFailMessage("Found confidential directory when we should not have").isNull(); } else { System.out.println("Inaccessible dir....: " diff --git a/samples/dms-xml/src/test/java/SecureDmsIntegrationTests.java b/samples/dms-xml/src/test/java/SecureDmsIntegrationTests.java index a676e24942..2b9aff149a 100644 --- a/samples/dms-xml/src/test/java/SecureDmsIntegrationTests.java +++ b/samples/dms-xml/src/test/java/SecureDmsIntegrationTests.java @@ -1,4 +1,4 @@ -import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.springframework.test.context.ContextConfiguration; @@ -14,24 +14,16 @@ import org.springframework.test.context.ContextConfiguration; public class SecureDmsIntegrationTests extends DmsIntegrationTests { @Test - public void testBasePopulation() { - assertEquals(9, - (int) jdbcTemplate.queryForObject("select count(id) from DIRECTORY", Integer.class)); - assertEquals(90, - (int) jdbcTemplate.queryForObject("select count(id) from FILE", Integer.class)); - assertEquals(4, - (int) jdbcTemplate.queryForObject("select count(id) from ACL_SID", Integer.class)); // 3 - // users - // + 1 - // role - assertEquals(2, - (int) jdbcTemplate.queryForObject("select count(id) from ACL_CLASS", Integer.class)); // Directory - // and - // File - assertEquals(100, - (int) jdbcTemplate.queryForObject("select count(id) from ACL_OBJECT_IDENTITY", Integer.class)); - assertEquals(115, - (int) jdbcTemplate.queryForObject("select count(id) from ACL_ENTRY", Integer.class)); + public void testBasePopulation() { + assertThat(jdbcTemplate.queryForObject("select count(id) from DIRECTORY", Integer.class)).isEqualTo(9); + assertThat(jdbcTemplate.queryForObject("select count(id) from FILE", Integer.class)).isEqualTo(90); + assertThat(jdbcTemplate.queryForObject("select count(id) from ACL_SID", Integer.class)).isEqualTo(4); // 3 users + 1 role + assertThat(jdbcTemplate.queryForObject("select count(id) from ACL_CLASS", Integer.class)).isEqualTo(2); // Directory + // and + // File + assertThat(jdbcTemplate.queryForObject("select count(id) from ACL_OBJECT_IDENTITY", Integer.class)) + .isEqualTo(100); + assertThat(jdbcTemplate.queryForObject("select count(id) from ACL_ENTRY", Integer.class)).isEqualTo(115); } public void testMarissaRetrieval() { diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/csrf/AbstractCsrfTagTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/csrf/AbstractCsrfTagTests.java index f8848af398..72eaec7cee 100644 --- a/taglibs/src/test/java/org/springframework/security/taglibs/csrf/AbstractCsrfTagTests.java +++ b/taglibs/src/test/java/org/springframework/security/taglibs/csrf/AbstractCsrfTagTests.java @@ -44,8 +44,7 @@ public class AbstractCsrfTagTests { int returned = this.tag.doEndTag(); assertThat(returned).as("The returned value is not correct.").isEqualTo(TagSupport.EVAL_PAGE); - assertEquals("The output value is not correct.", "", - this.response.getContentAsString()); + assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.").isEqualTo(""); } @Test @@ -61,8 +60,7 @@ public class AbstractCsrfTagTests { int returned = this.tag.doEndTag(); assertThat(returned).as("The returned value is not correct.").isEqualTo(TagSupport.EVAL_PAGE); - assertEquals("The output value is not correct.", "fooBarBazQux", - this.response.getContentAsString()); + assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.").isEqualTo("fooBarBazQux"); assertThat(this.tag.token).as("The token is not correct.").isSameAs(token); } @@ -79,8 +77,7 @@ public class AbstractCsrfTagTests { int returned = this.tag.doEndTag(); assertThat(returned).as("The returned value is not correct.").isEqualTo(TagSupport.EVAL_PAGE); - assertEquals("The output value is not correct.", "", - this.response.getContentAsString()); + assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.").isEqualTo(""); assertThat(this.tag.token).as("The token is not correct.").isSameAs(token); } diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/csrf/CsrfInputTagTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/csrf/CsrfInputTagTests.java index 2978202eb3..0f717fe8c0 100644 --- a/taglibs/src/test/java/org/springframework/security/taglibs/csrf/CsrfInputTagTests.java +++ b/taglibs/src/test/java/org/springframework/security/taglibs/csrf/CsrfInputTagTests.java @@ -27,9 +27,8 @@ public class CsrfInputTagTests { String value = this.tag.handleToken(token); assertThat(value).as("The returned value should not be null.").isNotNull(); - assertEquals("The output is not correct.", - "", - value); + assertThat( + value).withFailMessage("The output is not correct.").isEqualTo(""); } @Test @@ -40,9 +39,6 @@ public class CsrfInputTagTests { String value = this.tag.handleToken(token); assertThat(value).as("The returned value should not be null.").isNotNull(); - assertEquals( - "The output is not correct.", - "", - value); + assertThat(value).withFailMessage("The output is not correct.").isEqualTo(""); } } diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/csrf/CsrfMetaTagsTagTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/csrf/CsrfMetaTagsTagTests.java index 03b9e8a056..02106712df 100644 --- a/taglibs/src/test/java/org/springframework/security/taglibs/csrf/CsrfMetaTagsTagTests.java +++ b/taglibs/src/test/java/org/springframework/security/taglibs/csrf/CsrfMetaTagsTagTests.java @@ -27,10 +27,9 @@ public class CsrfMetaTagsTagTests { String value = this.tag.handleToken(token); assertThat(value).as("The returned value should not be null.").isNotNull(); - assertEquals("The output is not correct.", - "" - + "" - + "", value); + assertThat(value).withFailMessage("The output is not correct.").isEqualTo("" + + "" + + ""); } @Test @@ -41,9 +40,8 @@ public class CsrfMetaTagsTagTests { String value = this.tag.handleToken(token); assertThat(value).as("The returned value should not be null.").isNotNull(); - assertEquals("The output is not correct.", - "" - + "" - + "", value); + assertThat(value).withFailMessage("The output is not correct.").isEqualTo("" + + "" + + ""); } } diff --git a/test/src/test/java/org/springframework/security/test/context/support/WithMockUserSecurityContextFactoryTests.java b/test/src/test/java/org/springframework/security/test/context/support/WithMockUserSecurityContextFactoryTests.java index 062f78ae8d..7b1743c57e 100644 --- a/test/src/test/java/org/springframework/security/test/context/support/WithMockUserSecurityContextFactoryTests.java +++ b/test/src/test/java/org/springframework/security/test/context/support/WithMockUserSecurityContextFactoryTests.java @@ -74,7 +74,7 @@ public class WithMockUserSecurityContextFactoryTests { assertThat( factory.createSecurityContext(withUser).getAuthentication() - .getAuthorities()).onProperty("authority").containsOnly( + .getAuthorities()).extracting("authority").containsOnly( "ROLE_USER", "ROLE_CUSTOM"); } @@ -87,7 +87,7 @@ public class WithMockUserSecurityContextFactoryTests { assertThat( factory.createSecurityContext(withUser).getAuthentication() - .getAuthorities()).onProperty("authority").containsOnly( + .getAuthorities()).extracting("authority").containsOnly( "USER", "CUSTOM"); } diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserTests.java index 1ad2a3b4e5..5c83bb75db 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserTests.java @@ -83,7 +83,7 @@ public class SecurityMockMvcRequestPostProcessorsUserTests { UsernamePasswordAuthenticationToken.class); assertThat(context.getAuthentication().getName()).isEqualTo(username); assertThat(context.getAuthentication().getCredentials()).isEqualTo("password"); - assertThat(context.getAuthentication().getAuthorities()).onProperty("authority") + assertThat(context.getAuthentication().getAuthorities()).extracting("authority") .containsOnly("ROLE_USER"); } @@ -101,7 +101,7 @@ public class SecurityMockMvcRequestPostProcessorsUserTests { UsernamePasswordAuthenticationToken.class); assertThat(context.getAuthentication().getName()).isEqualTo(username); assertThat(context.getAuthentication().getCredentials()).isEqualTo("newpass"); - assertThat(context.getAuthentication().getAuthorities()).onProperty("authority") + assertThat(context.getAuthentication().getAuthorities()).extracting("authority") .containsOnly("ROLE_CUSTOM", "ROLE_ADMIN"); } diff --git a/web/src/test/java/org/springframework/security/web/PortMapperImplTests.java b/web/src/test/java/org/springframework/security/web/PortMapperImplTests.java index ac5da21b74..27308aaeca 100644 --- a/web/src/test/java/org/springframework/security/web/PortMapperImplTests.java +++ b/web/src/test/java/org/springframework/security/web/PortMapperImplTests.java @@ -16,34 +16,36 @@ package org.springframework.security.web; import static org.assertj.core.api.Assertions.assertThat; - -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.fail; import java.util.HashMap; import java.util.Map; -import org.springframework.security.web.PortMapperImpl; +import org.junit.Test; /** * Tests {@link PortMapperImpl}. * * @author Ben Alex */ -public class PortMapperImplTests extends TestCase { +public class PortMapperImplTests { + // ~ Methods // ======================================================================================================== - + @Test public void testDefaultMappingsAreKnown() throws Exception { PortMapperImpl portMapper = new PortMapperImpl(); - assertThat(portMapper.lookupHttpPort(Integer.valueOf(443))).isEqualTo(Integer.valueOf(80)); - assertEquals(Integer.valueOf(8080), + assertThat(portMapper.lookupHttpPort(Integer.valueOf(443))).isEqualTo( + Integer.valueOf(80)); + assertThat(Integer.valueOf(8080)).isEqualTo( portMapper.lookupHttpPort(Integer.valueOf(8443))); - assertEquals(Integer.valueOf(443), + assertThat(Integer.valueOf(443)).isEqualTo( portMapper.lookupHttpsPort(Integer.valueOf(80))); - assertEquals(Integer.valueOf(8443), + assertThat(Integer.valueOf(8443)).isEqualTo( portMapper.lookupHttpsPort(Integer.valueOf(8080))); } + @Test public void testDetectsEmptyMap() throws Exception { PortMapperImpl portMapper = new PortMapperImpl(); @@ -56,6 +58,7 @@ public class PortMapperImplTests extends TestCase { } } + @Test public void testDetectsNullMap() throws Exception { PortMapperImpl portMapper = new PortMapperImpl(); @@ -68,11 +71,13 @@ public class PortMapperImplTests extends TestCase { } } + @Test public void testGetTranslatedPortMappings() { PortMapperImpl portMapper = new PortMapperImpl(); assertThat(portMapper.getTranslatedPortMappings()).hasSize(2); } + @Test public void testRejectsOutOfRangeMappings() { PortMapperImpl portMapper = new PortMapperImpl(); Map map = new HashMap(); @@ -87,11 +92,13 @@ public class PortMapperImplTests extends TestCase { } } + @Test public void testReturnsNullIfHttpPortCannotBeFound() { PortMapperImpl portMapper = new PortMapperImpl(); assertThat(portMapper.lookupHttpPort(Integer.valueOf("34343")) == null).isTrue(); } + @Test public void testSupportsCustomMappings() { PortMapperImpl portMapper = new PortMapperImpl(); Map map = new HashMap(); @@ -99,8 +106,9 @@ public class PortMapperImplTests extends TestCase { portMapper.setPortMappings(map); - assertThat(portMapper.lookupHttpPort(Integer.valueOf(442))).isEqualTo(Integer.valueOf(79)); - assertEquals(Integer.valueOf(442), + assertThat(portMapper.lookupHttpPort(Integer.valueOf(442))).isEqualTo( + Integer.valueOf(79)); + assertThat(Integer.valueOf(442)).isEqualTo( portMapper.lookupHttpsPort(Integer.valueOf(79))); } } diff --git a/web/src/test/java/org/springframework/security/web/PortResolverImplTests.java b/web/src/test/java/org/springframework/security/web/PortResolverImplTests.java index 45f5d2b149..e8f1262845 100644 --- a/web/src/test/java/org/springframework/security/web/PortResolverImplTests.java +++ b/web/src/test/java/org/springframework/security/web/PortResolverImplTests.java @@ -16,19 +16,17 @@ package org.springframework.security.web; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.security.web.PortMapperImpl; -import org.springframework.security.web.PortResolverImpl; /** * Tests {@link PortResolverImpl}. * * @author Ben Alex */ -public class PortResolverImplTests extends TestCase { +public class PortResolverImplTests { // ~ Constructors // =================================================================================================== @@ -36,17 +34,9 @@ public class PortResolverImplTests extends TestCase { super(); } - public PortResolverImplTests(String arg0) { - super(arg0); - } - // ~ Methods // ======================================================================================================== - - public final void setUp() throws Exception { - super.setUp(); - } - + @Test public void testDetectsBuggyIeHttpRequest() throws Exception { PortResolverImpl pr = new PortResolverImpl(); @@ -56,6 +46,7 @@ public class PortResolverImplTests extends TestCase { assertThat(pr.getServerPort(request)).isEqualTo(8080); } + @Test public void testDetectsBuggyIeHttpsRequest() throws Exception { PortResolverImpl pr = new PortResolverImpl(); @@ -65,6 +56,7 @@ public class PortResolverImplTests extends TestCase { assertThat(pr.getServerPort(request)).isEqualTo(8443); } + @Test public void testDetectsEmptyPortMapper() throws Exception { PortResolverImpl pr = new PortResolverImpl(); @@ -77,6 +69,7 @@ public class PortResolverImplTests extends TestCase { } } + @Test public void testGettersSetters() throws Exception { PortResolverImpl pr = new PortResolverImpl(); assertThat(pr.getPortMapper() != null).isTrue(); @@ -84,6 +77,7 @@ public class PortResolverImplTests extends TestCase { assertThat(pr.getPortMapper() != null).isTrue(); } + @Test public void testNormalOperation() throws Exception { PortResolverImpl pr = new PortResolverImpl(); diff --git a/web/src/test/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImplTests.java b/web/src/test/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImplTests.java index 0a7f51c34c..2c9950c0c6 100644 --- a/web/src/test/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImplTests.java +++ b/web/src/test/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImplTests.java @@ -16,6 +16,7 @@ package org.springframework.security.web.access.channel; import static org.mockito.Mockito.mock; +import static org.assertj.core.api.Assertions.*; import java.io.IOException; import java.util.Collection; @@ -26,8 +27,7 @@ import java.util.Vector; import javax.servlet.FilterChain; import javax.servlet.ServletException; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.access.ConfigAttribute; @@ -42,10 +42,10 @@ import org.springframework.security.web.access.channel.ChannelProcessor; * @author Ben Alex */ @SuppressWarnings("unchecked") -public class ChannelDecisionManagerImplTests extends TestCase { +public class ChannelDecisionManagerImplTests { // ~ Methods // ======================================================================================================== - + @Test public void testCannotSetEmptyChannelProcessorsList() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); @@ -58,7 +58,8 @@ public class ChannelDecisionManagerImplTests extends TestCase { assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required"); } } - + + @Test public void testCannotSetIncorrectObjectTypesIntoChannelProcessorsList() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); @@ -73,7 +74,8 @@ public class ChannelDecisionManagerImplTests extends TestCase { } } - + + @Test public void testCannotSetNullChannelProcessorsList() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); @@ -86,7 +88,8 @@ public class ChannelDecisionManagerImplTests extends TestCase { assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required"); } } - + + @Test public void testDecideIsOperational() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false); @@ -107,7 +110,8 @@ public class ChannelDecisionManagerImplTests extends TestCase { cdm.decide(fi, cad); assertThat(fi.getResponse().isCommitted()).isTrue(); } - + + @Test public void testAnyChannelAttributeCausesProcessorsToBeSkipped() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); MockChannelProcessor cpAbc = new MockChannelProcessor("abc", true); @@ -124,7 +128,8 @@ public class ChannelDecisionManagerImplTests extends TestCase { cdm.decide(fi, SecurityConfig.createList(new String[] { "abc", "ANY_CHANNEL" })); assertThat(fi.getResponse().isCommitted()).isFalse(); } - + + @Test public void testDecideIteratesAllProcessorsIfNoneCommitAResponse() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false); @@ -143,7 +148,8 @@ public class ChannelDecisionManagerImplTests extends TestCase { cdm.decide(fi, SecurityConfig.createList("SOME_ATTRIBUTE_NO_PROCESSORS_SUPPORT")); assertThat(fi.getResponse().isCommitted()).isFalse(); } - + + @Test public void testDelegatesSupports() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false); @@ -158,7 +164,8 @@ public class ChannelDecisionManagerImplTests extends TestCase { assertThat(cdm.supports(new SecurityConfig("abc"))).isTrue(); assertThat(cdm.supports(new SecurityConfig("UNSUPPORTED"))).isFalse(); } - + + @Test public void testGettersSetters() { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); assertThat(cdm.getChannelProcessors()).isNull(); @@ -172,7 +179,8 @@ public class ChannelDecisionManagerImplTests extends TestCase { assertThat(cdm.getChannelProcessors()).isEqualTo(list); } - + + @Test public void testStartupFailsWithEmptyChannelProcessorsList() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); diff --git a/web/src/test/java/org/springframework/security/web/access/channel/InsecureChannelProcessorTests.java b/web/src/test/java/org/springframework/security/web/access/channel/InsecureChannelProcessorTests.java index 841fe68327..f08546c5bf 100644 --- a/web/src/test/java/org/springframework/security/web/access/channel/InsecureChannelProcessorTests.java +++ b/web/src/test/java/org/springframework/security/web/access/channel/InsecureChannelProcessorTests.java @@ -16,11 +16,11 @@ package org.springframework.security.web.access.channel; import static org.mockito.Mockito.mock; +import static org.assertj.core.api.Assertions.*; import javax.servlet.FilterChain; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.access.SecurityConfig; @@ -32,8 +32,9 @@ import org.springframework.security.web.access.channel.InsecureChannelProcessor; * * @author Ben Alex */ -public class InsecureChannelProcessorTests extends TestCase { - +public class InsecureChannelProcessorTests { + + @Test public void testDecideDetectsAcceptableChannel() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("info=true"); @@ -53,7 +54,8 @@ public class InsecureChannelProcessorTests extends TestCase { assertThat(fi.getResponse().isCommitted()).isFalse(); } - + + @Test public void testDecideDetectsUnacceptableChannel() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("info=true"); @@ -76,7 +78,8 @@ public class InsecureChannelProcessorTests extends TestCase { assertThat(fi.getResponse().isCommitted()).isTrue(); } - + + @Test public void testDecideRejectsNulls() throws Exception { InsecureChannelProcessor processor = new InsecureChannelProcessor(); processor.afterPropertiesSet(); @@ -89,7 +92,8 @@ public class InsecureChannelProcessorTests extends TestCase { } } - + + @Test public void testGettersSetters() { InsecureChannelProcessor processor = new InsecureChannelProcessor(); assertThat(processor.getInsecureKeyword()).isEqualTo("REQUIRES_INSECURE_CHANNEL"); @@ -100,7 +104,8 @@ public class InsecureChannelProcessorTests extends TestCase { processor.setEntryPoint(null); assertThat(processor.getEntryPoint() == null).isTrue(); } - + + @Test public void testMissingEntryPoint() throws Exception { InsecureChannelProcessor processor = new InsecureChannelProcessor(); processor.setEntryPoint(null); @@ -113,7 +118,8 @@ public class InsecureChannelProcessorTests extends TestCase { assertThat(expected.getMessage()).isEqualTo("entryPoint required"); } } - + + @Test public void testMissingSecureChannelKeyword() throws Exception { InsecureChannelProcessor processor = new InsecureChannelProcessor(); processor.setInsecureKeyword(null); @@ -136,7 +142,8 @@ public class InsecureChannelProcessorTests extends TestCase { assertThat(expected.getMessage()).isEqualTo("insecureKeyword required"); } } - + + @Test public void testSupports() { InsecureChannelProcessor processor = new InsecureChannelProcessor(); assertThat(processor.supports(new SecurityConfig("REQUIRES_INSECURE_CHANNEL"))).isTrue(); diff --git a/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpEntryPointTests.java b/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpEntryPointTests.java index 70a148f507..a89228b1c2 100644 --- a/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpEntryPointTests.java +++ b/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpEntryPointTests.java @@ -16,8 +16,7 @@ package org.springframework.security.web.access.channel; import static org.mockito.Mockito.mock; - -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.*; import org.springframework.security.MockPortResolver; @@ -26,7 +25,7 @@ import org.springframework.security.web.PortMapperImpl; import org.springframework.security.web.PortResolver; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.access.channel.RetryWithHttpEntryPoint; - +import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; @@ -38,10 +37,10 @@ import java.util.Map; * * @author Ben Alex */ -public class RetryWithHttpEntryPointTests extends TestCase { +public class RetryWithHttpEntryPointTests { // ~ Methods // ======================================================================================================== - + @Test public void testDetectsMissingPortMapper() throws Exception { RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint(); @@ -52,7 +51,8 @@ public class RetryWithHttpEntryPointTests extends TestCase { catch (IllegalArgumentException expected) { } } - + + @Test public void testDetectsMissingPortResolver() throws Exception { RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint(); @@ -63,7 +63,8 @@ public class RetryWithHttpEntryPointTests extends TestCase { catch (IllegalArgumentException expected) { } } - + + @Test public void testGettersSetters() { RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint(); PortMapper portMapper = mock(PortMapper.class); @@ -76,7 +77,8 @@ public class RetryWithHttpEntryPointTests extends TestCase { assertThat(ep.getPortResolver()).isSameAs(portResolver); assertThat(ep.getRedirectStrategy()).isSameAs(redirector); } - + + @Test public void testNormalOperation() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html"); @@ -92,10 +94,10 @@ public class RetryWithHttpEntryPointTests extends TestCase { ep.setPortResolver(new MockPortResolver(80, 443)); ep.commence(request, response); - assertEquals("http://www.example.com/bigWebApp/hello/pathInfo.html?open=true", - response.getRedirectedUrl()); + assertThat(response.getRedirectedUrl()).isEqualTo("http://www.example.com/bigWebApp/hello/pathInfo.html?open=true"); } - + + @Test public void testNormalOperationWithNullQueryString() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello"); @@ -110,10 +112,10 @@ public class RetryWithHttpEntryPointTests extends TestCase { ep.setPortResolver(new MockPortResolver(80, 443)); ep.commence(request, response); - assertEquals("http://www.example.com/bigWebApp/hello", - response.getRedirectedUrl()); + assertThat(response.getRedirectedUrl()).isEqualTo("http://www.example.com/bigWebApp/hello"); } - + + @Test public void testOperationWhenTargetPortIsUnknown() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp"); request.setQueryString("open=true"); @@ -130,7 +132,8 @@ public class RetryWithHttpEntryPointTests extends TestCase { ep.commence(request, response); assertThat(response.getRedirectedUrl()).isEqualTo("/bigWebApp?open=true"); } - + + @Test public void testOperationWithNonStandardPort() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html"); @@ -151,8 +154,7 @@ public class RetryWithHttpEntryPointTests extends TestCase { ep.setPortMapper(portMapper); ep.commence(request, response); - assertEquals( - "http://www.example.com:8888/bigWebApp/hello/pathInfo.html?open=true", - response.getRedirectedUrl()); + assertThat(response.getRedirectedUrl()).isEqualTo( + "http://www.example.com:8888/bigWebApp/hello/pathInfo.html?open=true"); } } diff --git a/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpsEntryPointTests.java b/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpsEntryPointTests.java index 1e2e49cd64..86f9bdfb56 100644 --- a/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpsEntryPointTests.java +++ b/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpsEntryPointTests.java @@ -15,13 +15,13 @@ package org.springframework.security.web.access.channel; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.*; import org.springframework.security.MockPortResolver; import org.springframework.security.web.PortMapperImpl; import org.springframework.security.web.access.channel.RetryWithHttpsEntryPoint; - +import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; @@ -33,10 +33,10 @@ import java.util.Map; * * @author Ben Alex */ -public class RetryWithHttpsEntryPointTests extends TestCase { +public class RetryWithHttpsEntryPointTests { // ~ Methods // ======================================================================================================== - + @Test public void testDetectsMissingPortMapper() throws Exception { RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint(); @@ -48,6 +48,7 @@ public class RetryWithHttpsEntryPointTests extends TestCase { } } + @Test public void testDetectsMissingPortResolver() throws Exception { RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint(); @@ -59,6 +60,7 @@ public class RetryWithHttpsEntryPointTests extends TestCase { } } + @Test public void testGettersSetters() { RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint(); ep.setPortMapper(new PortMapperImpl()); @@ -67,6 +69,7 @@ public class RetryWithHttpsEntryPointTests extends TestCase { assertThat(ep.getPortResolver() != null).isTrue(); } + @Test public void testNormalOperation() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html"); @@ -82,10 +85,11 @@ public class RetryWithHttpsEntryPointTests extends TestCase { ep.setPortResolver(new MockPortResolver(80, 443)); ep.commence(request, response); - assertEquals("https://www.example.com/bigWebApp/hello/pathInfo.html?open=true", - response.getRedirectedUrl()); + assertThat(response.getRedirectedUrl()).isEqualTo( + "https://www.example.com/bigWebApp/hello/pathInfo.html?open=true"); } + @Test public void testNormalOperationWithNullQueryString() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello"); @@ -100,10 +104,10 @@ public class RetryWithHttpsEntryPointTests extends TestCase { ep.setPortResolver(new MockPortResolver(80, 443)); ep.commence(request, response); - assertEquals("https://www.example.com/bigWebApp/hello", - response.getRedirectedUrl()); + assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/hello"); } + @Test public void testOperationWhenTargetPortIsUnknown() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp"); request.setQueryString("open=true"); @@ -121,6 +125,7 @@ public class RetryWithHttpsEntryPointTests extends TestCase { assertThat(response.getRedirectedUrl()).isEqualTo("/bigWebApp?open=true"); } + @Test public void testOperationWithNonStandardPort() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html"); @@ -141,8 +146,7 @@ public class RetryWithHttpsEntryPointTests extends TestCase { ep.setPortMapper(portMapper); ep.commence(request, response); - assertEquals( - "https://www.example.com:9999/bigWebApp/hello/pathInfo.html?open=true", - response.getRedirectedUrl()); + assertThat(response.getRedirectedUrl()).isEqualTo( + "https://www.example.com:9999/bigWebApp/hello/pathInfo.html?open=true"); } } diff --git a/web/src/test/java/org/springframework/security/web/access/channel/SecureChannelProcessorTests.java b/web/src/test/java/org/springframework/security/web/access/channel/SecureChannelProcessorTests.java index 37993600f9..5fd8449ae0 100644 --- a/web/src/test/java/org/springframework/security/web/access/channel/SecureChannelProcessorTests.java +++ b/web/src/test/java/org/springframework/security/web/access/channel/SecureChannelProcessorTests.java @@ -16,11 +16,11 @@ package org.springframework.security.web.access.channel; import static org.mockito.Mockito.mock; +import static org.assertj.core.api.Assertions.*; import javax.servlet.FilterChain; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.access.SecurityConfig; @@ -32,10 +32,10 @@ import org.springframework.security.web.access.channel.SecureChannelProcessor; * * @author Ben Alex */ -public class SecureChannelProcessorTests extends TestCase { +public class SecureChannelProcessorTests { // ~ Methods // ======================================================================================================== - + @Test public void testDecideDetectsAcceptableChannel() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("info=true"); @@ -57,6 +57,7 @@ public class SecureChannelProcessorTests extends TestCase { assertThat(fi.getResponse().isCommitted()).isFalse(); } + @Test public void testDecideDetectsUnacceptableChannel() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("info=true"); @@ -79,6 +80,7 @@ public class SecureChannelProcessorTests extends TestCase { assertThat(fi.getResponse().isCommitted()).isTrue(); } + @Test public void testDecideRejectsNulls() throws Exception { SecureChannelProcessor processor = new SecureChannelProcessor(); processor.afterPropertiesSet(); @@ -92,6 +94,7 @@ public class SecureChannelProcessorTests extends TestCase { } } + @Test public void testGettersSetters() { SecureChannelProcessor processor = new SecureChannelProcessor(); assertThat(processor.getSecureKeyword()).isEqualTo("REQUIRES_SECURE_CHANNEL"); @@ -103,6 +106,7 @@ public class SecureChannelProcessorTests extends TestCase { assertThat(processor.getEntryPoint() == null).isTrue(); } + @Test public void testMissingEntryPoint() throws Exception { SecureChannelProcessor processor = new SecureChannelProcessor(); processor.setEntryPoint(null); @@ -116,6 +120,7 @@ public class SecureChannelProcessorTests extends TestCase { } } + @Test public void testMissingSecureChannelKeyword() throws Exception { SecureChannelProcessor processor = new SecureChannelProcessor(); processor.setSecureKeyword(null); @@ -139,6 +144,7 @@ public class SecureChannelProcessorTests extends TestCase { } } + @Test public void testSupports() { SecureChannelProcessor processor = new SecureChannelProcessor(); assertThat(processor.supports(new SecurityConfig("REQUIRES_SECURE_CHANNEL"))).isTrue(); diff --git a/web/src/test/java/org/springframework/security/web/access/expression/DefaultWebSecurityExpressionHandlerTests.java b/web/src/test/java/org/springframework/security/web/access/expression/DefaultWebSecurityExpressionHandlerTests.java index 6cbe91055a..5250af2be2 100644 --- a/web/src/test/java/org/springframework/security/web/access/expression/DefaultWebSecurityExpressionHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/access/expression/DefaultWebSecurityExpressionHandlerTests.java @@ -13,10 +13,10 @@ * License for the specific language governing permissions and limitations under * the License. */ + package org.springframework.security.web.access.expression; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -39,6 +39,7 @@ import org.springframework.security.web.FilterInvocation; @RunWith(MockitoJUnitRunner.class) public class DefaultWebSecurityExpressionHandlerTests { + @Mock private AuthenticationTrustResolver trustResolver; @@ -71,10 +72,10 @@ public class DefaultWebSecurityExpressionHandlerTests { EvaluationContext ctx = handler.createEvaluationContext( mock(Authentication.class), mock(FilterInvocation.class)); ExpressionParser parser = handler.getExpressionParser(); - assertThat(parser.parseExpression("@role.getAttribute() == 'ROLE_A'").isTrue().getValue( - ctx, Boolean.class)); - assertThat(parser.parseExpression("@role.attribute == 'ROLE_A'").isTrue().getValue(ctx, - Boolean.class)); + assertThat(parser.parseExpression("@role.getAttribute() == 'ROLE_A'").getValue( + ctx, Boolean.class)).isTrue(); + assertThat(parser.parseExpression("@role.attribute == 'ROLE_A'").getValue(ctx, + Boolean.class)).isTrue(); } @Test(expected = IllegalArgumentException.class) @@ -86,8 +87,8 @@ public class DefaultWebSecurityExpressionHandlerTests { public void createEvaluationContextCustomTrustResolver() { handler.setTrustResolver(trustResolver); - Expression expression = handler.getExpressionParser() - .parseExpression("anonymous"); + Expression expression = handler.getExpressionParser().parseExpression( + "anonymous"); EvaluationContext context = handler.createEvaluationContext(authentication, invocation); assertThat(expression.getValue(context, Boolean.class)).isFalse(); diff --git a/web/src/test/java/org/springframework/security/web/access/expression/WebExpressionVoterTests.java b/web/src/test/java/org/springframework/security/web/access/expression/WebExpressionVoterTests.java index 53fe1dfbc7..5b7580ade2 100644 --- a/web/src/test/java/org/springframework/security/web/access/expression/WebExpressionVoterTests.java +++ b/web/src/test/java/org/springframework/security/web/access/expression/WebExpressionVoterTests.java @@ -1,10 +1,16 @@ + package org.springframework.security.web.access.expression; -import static org.assertj.core.api.Assertions.*; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.*; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; + +import javax.servlet.FilterChain; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; import org.aopalliance.intercept.MethodInvocation; import org.junit.Test; @@ -19,24 +25,19 @@ import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.web.FilterInvocation; -import java.util.ArrayList; - -import javax.servlet.FilterChain; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - /** * @author Luke Taylor */ @SuppressWarnings({ "unchecked" }) public class WebExpressionVoterTests { + private Authentication user = new TestingAuthenticationToken("user", "pass", "X"); @Test public void supportsWebConfigAttributeAndFilterInvocation() throws Exception { WebExpressionVoter voter = new WebExpressionVoter(); - assertTrue(voter - .supports(new WebExpressionConfigAttribute(mock(Expression.class), mock(SecurityEvaluationContextPostProcessor.class)))); + assertThat(voter.supports(new WebExpressionConfigAttribute(mock(Expression.class), + mock(SecurityEvaluationContextPostProcessor.class)))).isTrue(); assertThat(voter.supports(FilterInvocation.class)).isTrue(); assertThat(voter.supports(MethodInvocation.class)).isFalse(); @@ -45,23 +46,27 @@ public class WebExpressionVoterTests { @Test public void abstainsIfNoAttributeFound() { WebExpressionVoter voter = new WebExpressionVoter(); - assertEquals( - AccessDecisionVoter.ACCESS_ABSTAIN, - voter.vote(user, new FilterInvocation("/path", "GET"), - SecurityConfig.createList("A", "B", "C"))); + assertThat(voter.vote(user, new FilterInvocation("/path", "GET"), + SecurityConfig.createList("A", "B", "C"))).isEqualTo( + AccessDecisionVoter.ACCESS_ABSTAIN); } @Test public void grantsAccessIfExpressionIsTrueDeniesIfFalse() { WebExpressionVoter voter = new WebExpressionVoter(); Expression ex = mock(Expression.class); - SecurityEvaluationContextPostProcessor postProcessor = mock(SecurityEvaluationContextPostProcessor.class); - when(postProcessor.postProcess(any(EvaluationContext.class), any(FilterInvocation.class))).thenAnswer(new Answer() { - public EvaluationContext answer(InvocationOnMock invocation) throws Throwable { - return invocation.getArgumentAt(0, EvaluationContext.class); - } - }); - WebExpressionConfigAttribute weca = new WebExpressionConfigAttribute(ex,postProcessor); + SecurityEvaluationContextPostProcessor postProcessor = mock( + SecurityEvaluationContextPostProcessor.class); + when(postProcessor.postProcess(any(EvaluationContext.class), + any(FilterInvocation.class))).thenAnswer(new Answer() { + + public EvaluationContext answer(InvocationOnMock invocation) + throws Throwable { + return invocation.getArgumentAt(0, EvaluationContext.class); + } + }); + WebExpressionConfigAttribute weca = new WebExpressionConfigAttribute(ex, + postProcessor); EvaluationContext ctx = mock(EvaluationContext.class); SecurityExpressionHandler eh = mock(SecurityExpressionHandler.class); FilterInvocation fi = new FilterInvocation("/path", "GET"); @@ -73,10 +78,12 @@ public class WebExpressionVoterTests { attributes.addAll(SecurityConfig.createList("A", "B", "C")); attributes.add(weca); - assertThat(fi).isCloseTo(AccessDecisionVoter.ACCESS_GRANTED, voter.vote(user, within(attributes))); + assertThat(voter.vote(user, fi, attributes)).isEqualTo( + AccessDecisionVoter.ACCESS_GRANTED); // Second time false - assertThat(fi).isCloseTo(AccessDecisionVoter.ACCESS_DENIED, voter.vote(user, within(attributes))); + assertThat(voter.vote(user, fi, attributes)).isEqualTo( + AccessDecisionVoter.ACCESS_DENIED); } // SEC-2507 @@ -87,6 +94,7 @@ public class WebExpressionVoterTests { } private static class FilterInvocationChild extends FilterInvocation { + public FilterInvocationChild(ServletRequest request, ServletResponse response, FilterChain chain) { super(request, response, chain); diff --git a/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java index 4e3328ee60..ad1d5d7aaa 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java @@ -16,9 +16,6 @@ package org.springframework.security.web.authentication; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; @@ -66,7 +63,9 @@ import org.springframework.test.util.ReflectionTestUtils; */ @SuppressWarnings("deprecation") public class AbstractAuthenticationProcessingFilterTests { + SavedRequestAwareAuthenticationSuccessHandler successHandler; + SimpleUrlAuthenticationFailureHandler failureHandler; // ~ Methods @@ -137,8 +136,9 @@ public class AbstractAuthenticationProcessingFilterTests { filter.doFilter(request, response, chain); assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp"); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); - assertThat(SecurityContextHolder.getContext().getAuthentication().isEqualTo("test") - .getPrincipal().toString()); + assertThat( + SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo( + "test"); } @Test @@ -151,8 +151,8 @@ public class AbstractAuthenticationProcessingFilterTests { assertThat(filter.getRememberMeServices()).isNotNull(); filter.setRememberMeServices(new TokenBasedRememberMeServices("key", new AbstractRememberMeServicesTests.MockUserDetailsService())); - assertThat(filter.getRememberMeServices().isEqualTo(TokenBasedRememberMeServices.class) - .getClass()); + assertThat(filter.getRememberMeServices().getClass()).isEqualTo( + TokenBasedRememberMeServices.class); assertThat(filter.getAuthenticationManager() != null).isTrue(); } @@ -196,7 +196,8 @@ public class AbstractAuthenticationProcessingFilterTests { MockAuthenticationFilter filter = new MockAuthenticationFilter(true); filter.setFilterProcessesUrl("/j_mock_post"); - filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class)); + filter.setSessionAuthenticationStrategy( + mock(SessionAuthenticationStrategy.class)); filter.setAuthenticationSuccessHandler(successHandler); filter.setAuthenticationFailureHandler(failureHandler); filter.setAuthenticationManager(mock(AuthenticationManager.class)); @@ -206,8 +207,9 @@ public class AbstractAuthenticationProcessingFilterTests { filter.doFilter(request, response, chain); assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp"); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); - assertThat(SecurityContextHolder.getContext().getAuthentication().isEqualTo("test") - .getPrincipal().toString()); + assertThat( + SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo( + "test"); // Should still have the same session assertThat(request.getSession()).isEqualTo(sessionPreAuth); } @@ -225,7 +227,8 @@ public class AbstractAuthenticationProcessingFilterTests { fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("authenticationManager must be specified"); + assertThat(expected.getMessage()).isEqualTo( + "authenticationManager must be specified"); } } @@ -241,7 +244,8 @@ public class AbstractAuthenticationProcessingFilterTests { fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("Pattern cannot be null or empty"); + assertThat(expected.getMessage()).isEqualTo( + "Pattern cannot be null or empty"); } } @@ -268,8 +272,9 @@ public class AbstractAuthenticationProcessingFilterTests { filter.doFilter(request, response, chain); assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp"); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); - assertThat(SecurityContextHolder.getContext().getAuthentication().isEqualTo("test") - .getPrincipal().toString()); + assertThat( + SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo( + "test"); // Now try again but this time have filter deny access // Setup our HTTP request @@ -305,7 +310,8 @@ public class AbstractAuthenticationProcessingFilterTests { // Setup our test object, to grant access MockAuthenticationFilter filter = new MockAuthenticationFilter(true); filter.setFilterProcessesUrl("/j_mock_post"); - AuthenticationSuccessHandler successHandler = mock(AuthenticationSuccessHandler.class); + AuthenticationSuccessHandler successHandler = mock( + AuthenticationSuccessHandler.class); filter.setAuthenticationSuccessHandler(successHandler); // Test @@ -332,7 +338,8 @@ public class AbstractAuthenticationProcessingFilterTests { // Setup our test object, to deny access MockAuthenticationFilter filter = new MockAuthenticationFilter(false); - AuthenticationFailureHandler failureHandler = mock(AuthenticationFailureHandler.class); + AuthenticationFailureHandler failureHandler = mock( + AuthenticationFailureHandler.class); filter.setAuthenticationFailureHandler(failureHandler); // Test @@ -413,15 +420,19 @@ public class AbstractAuthenticationProcessingFilterTests { // ~ Inner Classes // ================================================================================================== - private class MockAuthenticationFilter extends AbstractAuthenticationProcessingFilter { + private class MockAuthenticationFilter + extends AbstractAuthenticationProcessingFilter { + private AuthenticationException exceptionToThrow; + private boolean grantAccess; public MockAuthenticationFilter(boolean grantAccess) { this(); setRememberMeServices(new NullRememberMeServices()); this.grantAccess = grantAccess; - this.exceptionToThrow = new BadCredentialsException("Mock requested to do so"); + this.exceptionToThrow = new BadCredentialsException( + "Mock requested to do so"); } private MockAuthenticationFilter() { @@ -441,6 +452,7 @@ public class AbstractAuthenticationProcessingFilterTests { } private class MockFilterChain implements FilterChain { + private boolean expectToProceed; public MockFilterChain(boolean expectToProceed) { diff --git a/web/src/test/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilterTests.java index 70a0483520..207788d1c9 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilterTests.java @@ -102,7 +102,7 @@ public class AnonymousAuthenticationFilterTests { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); assertThat(auth.getPrincipal()).isEqualTo("anonymousUsername"); - assertThat(AuthorityUtils.authorityListToSet(auth.getAuthorities()).isTrue().contains( + assertThat(AuthorityUtils.authorityListToSet(auth.getAuthorities()).contains( "ROLE_ANONYMOUS")); SecurityContextHolder.getContext().setAuthentication(null); // so anonymous fires // again diff --git a/web/src/test/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPointTests.java b/web/src/test/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPointTests.java index ddce1988cb..619b6fba19 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPointTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPointTests.java @@ -93,22 +93,19 @@ public class LoginUrlAuthenticationEntryPointTests { ep.afterPropertiesSet(); ep.commence(request, response, null); - assertEquals("https://www.example.com/bigWebApp/hello", - response.getRedirectedUrl()); + assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/hello"); request.setServerPort(8080); response = new MockHttpServletResponse(); ep.setPortResolver(new MockPortResolver(8080, 8443)); ep.commence(request, response, null); - assertEquals("https://www.example.com:8443/bigWebApp/hello", - response.getRedirectedUrl()); + assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com:8443/bigWebApp/hello"); // Now test an unusual custom HTTP:HTTPS is handled properly request.setServerPort(8888); response = new MockHttpServletResponse(); ep.commence(request, response, null); - assertEquals("https://www.example.com:8443/bigWebApp/hello", - response.getRedirectedUrl()); + assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com:8443/bigWebApp/hello"); PortMapperImpl portMapper = new PortMapperImpl(); Map map = new HashMap(); @@ -124,8 +121,7 @@ public class LoginUrlAuthenticationEntryPointTests { ep.afterPropertiesSet(); ep.commence(request, response, null); - assertEquals("https://www.example.com:9999/bigWebApp/hello", - response.getRedirectedUrl()); + assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com:9999/bigWebApp/hello"); } @Test @@ -148,15 +144,13 @@ public class LoginUrlAuthenticationEntryPointTests { ep.afterPropertiesSet(); ep.commence(request, response, null); - assertEquals("https://www.example.com/bigWebApp/hello", - response.getRedirectedUrl()); + assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/hello"); request.setServerPort(8443); response = new MockHttpServletResponse(); ep.setPortResolver(new MockPortResolver(8080, 8443)); ep.commence(request, response, null); - assertEquals("https://www.example.com:8443/bigWebApp/hello", - response.getRedirectedUrl()); + assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com:8443/bigWebApp/hello"); } @Test @@ -178,8 +172,7 @@ public class LoginUrlAuthenticationEntryPointTests { MockHttpServletResponse response = new MockHttpServletResponse(); ep.commence(request, response, null); - assertEquals("http://www.example.com/bigWebApp/hello", - response.getRedirectedUrl()); + assertThat(response.getRedirectedUrl()).isEqualTo("http://www.example.com/bigWebApp/hello"); } @Test @@ -204,8 +197,7 @@ public class LoginUrlAuthenticationEntryPointTests { // Response doesn't switch to HTTPS, as we didn't know HTTP port 8888 to HTTP port // mapping - assertEquals("http://www.example.com:8888/bigWebApp/hello", - response.getRedirectedUrl()); + assertThat(response.getRedirectedUrl()).isEqualTo("http://www.example.com:8888/bigWebApp/hello"); } @Test @@ -250,8 +242,7 @@ public class LoginUrlAuthenticationEntryPointTests { MockHttpServletResponse response = new MockHttpServletResponse(); ep.commence(request, response, null); - assertEquals("https://www.example.com/bigWebApp/some_path", - response.getRedirectedUrl()); + assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/some_path"); } // SEC-1498 diff --git a/web/src/test/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationFailureHandlerTests.java b/web/src/test/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationFailureHandlerTests.java index defa7a71e2..09987b6a8e 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationFailureHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationFailureHandlerTests.java @@ -40,8 +40,7 @@ public class SimpleUrlAuthenticationFailureHandlerTests { AuthenticationException e = mock(AuthenticationException.class); afh.onAuthenticationFailure(request, response, e); - assertSame(e, - request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)); + assertThat(request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)).isSameAs(e); assertThat(response.getRedirectedUrl()).isEqualTo("/target"); } diff --git a/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java index 1514eef01d..85fc87e60b 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java @@ -17,11 +17,10 @@ package org.springframework.security.web.authentication; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; +import static org.assertj.core.api.Assertions.*; import javax.servlet.ServletException; -import junit.framework.TestCase; - import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -37,7 +36,7 @@ import org.springframework.security.core.AuthenticationException; * * @author Ben Alex */ -public class UsernamePasswordAuthenticationFilterTests extends TestCase { +public class UsernamePasswordAuthenticationFilterTests { // ~ Methods // ======================================================================================================== @@ -58,8 +57,7 @@ public class UsernamePasswordAuthenticationFilterTests extends TestCase { Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse()); assertThat(result != null).isTrue(); - assertEquals("127.0.0.1", - ((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()); + assertThat(((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()).isEqualTo("127.0.0.1"); } @Test @@ -71,8 +69,8 @@ public class UsernamePasswordAuthenticationFilterTests extends TestCase { UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); - assertNotNull(filter - .attemptAuthentication(request, new MockHttpServletResponse())); + assertThat(filter + .attemptAuthentication(request, new MockHttpServletResponse())).isNotNull(); } @Test @@ -84,8 +82,8 @@ public class UsernamePasswordAuthenticationFilterTests extends TestCase { UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); - assertNotNull(filter - .attemptAuthentication(request, new MockHttpServletResponse())); + assertThat(filter + .attemptAuthentication(request, new MockHttpServletResponse())).isNotNull(); } @Test @@ -102,8 +100,7 @@ public class UsernamePasswordAuthenticationFilterTests extends TestCase { Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse()); assertThat(result).isNotNull(); - assertEquals("127.0.0.1", - ((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()); + assertThat(((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()).isEqualTo("127.0.0.1"); } @Test diff --git a/web/src/test/java/org/springframework/security/web/authentication/logout/HttpStatusReturningLogoutSuccessHandlerTests.java b/web/src/test/java/org/springframework/security/web/authentication/logout/HttpStatusReturningLogoutSuccessHandlerTests.java index 2eddafbef5..31591bd72d 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/logout/HttpStatusReturningLogoutSuccessHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/logout/HttpStatusReturningLogoutSuccessHandlerTests.java @@ -13,12 +13,13 @@ * License for the specific language governing permissions and limitations under * the License. */ + package org.springframework.security.web.authentication.logout; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; -import org.junit.Assert; import org.junit.Test; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletRequest; @@ -47,7 +48,8 @@ public class HttpStatusReturningLogoutSuccessHandlerTests { @Test public void testCustomHttpStatusBeingReturned() throws Exception { - final HttpStatusReturningLogoutSuccessHandler lsh = new HttpStatusReturningLogoutSuccessHandler(HttpStatus.NO_CONTENT); + final HttpStatusReturningLogoutSuccessHandler lsh = new HttpStatusReturningLogoutSuccessHandler( + HttpStatus.NO_CONTENT); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -71,7 +73,7 @@ public class HttpStatusReturningLogoutSuccessHandlerTests { return; } - Assert.fail("Expected an IllegalArgumentException to be thrown."); + fail("Expected an IllegalArgumentException to be thrown."); } } diff --git a/web/src/test/java/org/springframework/security/web/authentication/logout/LogoutHandlerTests.java b/web/src/test/java/org/springframework/security/web/authentication/logout/LogoutHandlerTests.java index 3aac16b1c3..df906d24fa 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/logout/LogoutHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/logout/LogoutHandlerTests.java @@ -1,7 +1,9 @@ package org.springframework.security.web.authentication.logout; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.*; +import org.junit.Before; +import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.web.authentication.logout.LogoutFilter; @@ -11,13 +13,14 @@ import org.springframework.security.web.firewall.DefaultHttpFirewall; /** * @author Luke Taylor */ -public class LogoutHandlerTests extends TestCase { +public class LogoutHandlerTests { LogoutFilter filter; - - protected void setUp() throws Exception { + @Before + public void setUp() throws Exception { filter = new LogoutFilter("/success", new SecurityContextLogoutHandler()); } + @Test public void testRequiresLogoutUrlWorksWithPathParams() { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -30,6 +33,7 @@ public class LogoutHandlerTests extends TestCase { assertThat(filter.requiresLogout(fw.getFirewalledRequest(request), response)).isTrue(); } + @Test public void testRequiresLogoutUrlWorksWithQueryParams() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setContextPath("/context"); diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java index ee764449a5..034bd87bff 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java @@ -13,8 +13,6 @@ package org.springframework.security.web.authentication.preauth; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; @@ -158,8 +156,8 @@ public class AbstractPreAuthenticatedProcessingFilterTests { filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain()); - assertThat(SecurityContextHolder.getContext().isEqualTo(authentication) - .getAuthentication()); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo( + authentication); } @Test @@ -332,8 +330,8 @@ public class AbstractPreAuthenticatedProcessingFilterTests { MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse res = new MockHttpServletResponse(); getFilter(grantAccess).doFilter(req, res, new MockFilterChain()); - assertThat(null != SecurityContextHolder.getContext().isEqualTo(grantAccess) - .getAuthentication()); + assertThat(null != SecurityContextHolder.getContext().getAuthentication()).isEqualTo( + grantAccess); } private static ConcretePreAuthenticatedProcessingFilter getFilter(boolean grantAccess) diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/Http403ForbiddenEntryPointTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/Http403ForbiddenEntryPointTests.java index b996885d9b..ea3540f724 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/Http403ForbiddenEntryPointTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/Http403ForbiddenEntryPointTests.java @@ -1,19 +1,20 @@ + package org.springframework.security.web.authentication.preauth; -import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; -import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; -import junit.framework.TestCase; - import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; +import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint; -public class Http403ForbiddenEntryPointTests extends TestCase { +public class Http403ForbiddenEntryPointTests { public void testCommence() { MockHttpServletRequest req = new MockHttpServletRequest(); @@ -22,7 +23,7 @@ public class Http403ForbiddenEntryPointTests extends TestCase { try { fep.commence(req, resp, new AuthenticationCredentialsNotFoundException("test")); - assertThat(resp.getStatus().isEqualTo("Incorrect status"), + assertThat(resp.getStatus()).withFailMessage("Incorrect status").isEqualTo( HttpServletResponse.SC_FORBIDDEN); } catch (IOException e) { diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationProviderTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationProviderTests.java index a921813e18..950de70174 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationProviderTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationProviderTests.java @@ -1,10 +1,7 @@ + package org.springframework.security.web.authentication.preauth; import static org.assertj.core.api.Assertions.assertThat; -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 org.junit.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -14,8 +11,6 @@ import org.springframework.security.core.userdetails.AuthenticationUserDetailsSe import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider; -import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; /** * @@ -45,7 +40,8 @@ public class PreAuthenticatedAuthenticationProviderTests { @Test public final void nullPrincipalReturnsNullAuthentication() throws Exception { PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider(); - Authentication request = new PreAuthenticatedAuthenticationToken(null, "dummyPwd"); + Authentication request = new PreAuthenticatedAuthenticationToken(null, + "dummyPwd"); Authentication result = provider.authenticate(request); assertThat(result).isNull(); } @@ -108,7 +104,8 @@ public class PreAuthenticatedAuthenticationProviderTests { private PreAuthenticatedAuthenticationProvider getProvider(UserDetails aUserDetails) throws Exception { PreAuthenticatedAuthenticationProvider result = new PreAuthenticatedAuthenticationProvider(); - result.setPreAuthenticatedUserDetailsService(getPreAuthenticatedUserDetailsService(aUserDetails)); + result.setPreAuthenticatedUserDetailsService( + getPreAuthenticatedUserDetailsService(aUserDetails)); result.afterPropertiesSet(); return result; } @@ -116,6 +113,7 @@ public class PreAuthenticatedAuthenticationProviderTests { private AuthenticationUserDetailsService getPreAuthenticatedUserDetailsService( final UserDetails aUserDetails) { return new AuthenticationUserDetailsService() { + public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token) throws UsernameNotFoundException { if (aUserDetails != null diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationTokenTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationTokenTests.java index 6061250586..ed869839fe 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationTokenTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationTokenTests.java @@ -1,21 +1,23 @@ + package org.springframework.security.web.authentication.preauth; +import static org.assertj.core.api.Assertions.assertThat; + import java.util.Collection; import java.util.List; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; /** * * @author TSARDD * @since 18-okt-2007 */ -public class PreAuthenticatedAuthenticationTokenTests extends TestCase { +public class PreAuthenticatedAuthenticationTokenTests { + @Test public void testPreAuthenticatedAuthenticationTokenRequestWithDetails() { Object principal = "dummyUser"; Object credentials = "dummyCredentials"; @@ -29,6 +31,7 @@ public class PreAuthenticatedAuthenticationTokenTests extends TestCase { assertThat(token.getAuthorities().isEmpty()).isTrue(); } + @Test public void testPreAuthenticatedAuthenticationTokenRequestWithoutDetails() { Object principal = "dummyUser"; Object credentials = "dummyCredentials"; @@ -40,6 +43,7 @@ public class PreAuthenticatedAuthenticationTokenTests extends TestCase { assertThat(token.getAuthorities().isEmpty()).isTrue(); } + @Test public void testPreAuthenticatedAuthenticationTokenResponse() { Object principal = "dummyUser"; Object credentials = "dummyCredentials"; @@ -51,9 +55,11 @@ public class PreAuthenticatedAuthenticationTokenTests extends TestCase { assertThat(token.getDetails()).isNull(); assertThat(token.getAuthorities()).isNotNull(); Collection resultColl = token.getAuthorities(); - assertTrue("GrantedAuthority collections do not match; result: " + resultColl - + ", expected: " + gas, - gas.containsAll(resultColl) && resultColl.containsAll(gas)); + assertThat( + + gas.containsAll(resultColl) && resultColl.containsAll(gas)).withFailMessage( + "GrantedAuthority collections do not match; result: " + resultColl + + ", expected: " + gas).isTrue(); } diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests.java index 8f0ab7edac..0c421af929 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests.java @@ -68,11 +68,8 @@ public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests { // PreAuthenticatedGrantedAuthoritiesUserDetailsService // assertThat(password).isEqualTo(ud.getPassword()); - assertTrue( - "GrantedAuthority collections do not match; result: " - + ud.getAuthorities() + ", expected: " + gas, - gas.containsAll(ud.getAuthorities()) - && ud.getAuthorities().containsAll(gas)); + assertThat(gas.containsAll(ud.getAuthorities()) + && ud.getAuthorities().containsAll(gas)).withFailMessage("GrantedAuthority collections do not match; result: "+ ud.getAuthorities() + ", expected: " + gas).isTrue(); } } diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests.java index eb3af81fda..3d90bcfd4b 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests.java @@ -1,6 +1,6 @@ package org.springframework.security.web.authentication.preauth; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; @@ -33,9 +33,9 @@ public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests { PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails( getRequest("testUser", new String[] {}), gas); List returnedGas = details.getGrantedAuthorities(); - assertTrue("Collections do not contain same elements; expected: " + gas - + ", returned: " + returnedGas, gas.containsAll(returnedGas) - && returnedGas.containsAll(gas)); + assertThat(gas.containsAll(returnedGas) && returnedGas.containsAll(gas)) + .withFailMessage("Collections do not contain same elements; expected: " + gas + + ", returned: " + returnedGas).isTrue(); } private HttpServletRequest getRequest(final String userName, final String[] aRoles) { diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/header/RequestHeaderAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/header/RequestHeaderAuthenticationFilterTests.java index 41fe702dca..77de419b1d 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/header/RequestHeaderAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/header/RequestHeaderAuthenticationFilterTests.java @@ -51,10 +51,8 @@ public class RequestHeaderAuthenticationFilterTests { filter.doFilter(request, response, chain); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); - assertThat(SecurityContextHolder.getContext().getAuthentication().isEqualTo("cat") - .getName()); - assertThat(SecurityContextHolder.getContext().getAuthentication().isEqualTo("N/A") - .getCredentials()); + assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("cat"); + assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("N/A"); } @Test @@ -69,8 +67,7 @@ public class RequestHeaderAuthenticationFilterTests { filter.doFilter(request, response, chain); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); - assertThat(SecurityContextHolder.getContext().getAuthentication().isEqualTo("wolfman") - .getName()); + assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("wolfman"); } @Test @@ -86,8 +83,7 @@ public class RequestHeaderAuthenticationFilterTests { filter.doFilter(request, response, chain); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); - assertThat(SecurityContextHolder.getContext().isEqualTo("catspassword") - .getAuthentication().getCredentials()); + assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("catspassword"); } @Test diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests.java index 2451fcd4e8..60e904d0f8 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests.java @@ -1,5 +1,9 @@ + package org.springframework.security.web.authentication.preauth.j2ee; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + import java.util.Arrays; import java.util.Collection; import java.util.HashSet; @@ -8,8 +12,7 @@ import java.util.Set; import javax.servlet.http.HttpServletRequest; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.mapping.Attributes2GrantedAuthoritiesMapper; @@ -22,9 +25,9 @@ import org.springframework.security.web.authentication.preauth.PreAuthenticatedG * * @author TSARDD */ -public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extends - TestCase { +public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests { + @Test public final void testAfterPropertiesSetException() { J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource t = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(); try { @@ -38,6 +41,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend } } + @Test public final void testBuildDetailsHttpServletRequestNoMappedNoUserRoles() { String[] mappedRoles = new String[] {}; String[] roles = new String[] {}; @@ -45,6 +49,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend testDetails(mappedRoles, roles, expectedRoles); } + @Test public final void testBuildDetailsHttpServletRequestNoMappedUnmappedUserRoles() { String[] mappedRoles = new String[] {}; String[] roles = new String[] { "Role1", "Role2" }; @@ -52,6 +57,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend testDetails(mappedRoles, roles, expectedRoles); } + @Test public final void testBuildDetailsHttpServletRequestNoUserRoles() { String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" }; String[] roles = new String[] {}; @@ -59,6 +65,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend testDetails(mappedRoles, roles, expectedRoles); } + @Test public final void testBuildDetailsHttpServletRequestAllUserRoles() { String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" }; String[] roles = new String[] { "Role1", "Role2", "Role3", "Role4" }; @@ -66,6 +73,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend testDetails(mappedRoles, roles, expectedRoles); } + @Test public final void testBuildDetailsHttpServletRequestUnmappedUserRoles() { String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" }; String[] roles = new String[] { "Role1", "Role2", "Role3", "Role4", "Role5" }; @@ -73,6 +81,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend testDetails(mappedRoles, roles, expectedRoles); } + @Test public final void testBuildDetailsHttpServletRequestPartialUserRoles() { String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" }; String[] roles = new String[] { "Role2", "Role3" }; @@ -80,6 +89,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend testDetails(mappedRoles, roles, expectedRoles); } + @Test public final void testBuildDetailsHttpServletRequestPartialAndUnmappedUserRoles() { String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" }; String[] roles = new String[] { "Role2", "Role3", "Role5" }; @@ -89,13 +99,14 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend private void testDetails(String[] mappedRoles, String[] userRoles, String[] expectedRoles) { - J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource src = getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(mappedRoles); + J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource src = getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource( + mappedRoles); Object o = src.buildDetails(getRequest("testUser", userRoles)); assertThat(o).isNotNull(); - assertTrue( - "Returned object not of type PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails, actual type: " - + o.getClass(), - o instanceof PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails); + assertThat( + o instanceof PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails).withFailMessage( + "Returned object not of type PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails, actual type: " + + o.getClass()).isTrue(); PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = (PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails) o; List gas = details.getGrantedAuthorities(); assertThat(gas).as("Granted authorities should not be null").isNotNull(); @@ -106,17 +117,17 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend for (int i = 0; i < gas.size(); i++) { gasRolesSet.add(gas.get(i).getAuthority()); } - assertTrue( - "Granted Authorities do not match expected roles", - expectedRolesColl.containsAll(gasRolesSet) - && gasRolesSet.containsAll(expectedRolesColl)); + assertThat(expectedRolesColl.containsAll(gasRolesSet) + && gasRolesSet.containsAll(expectedRolesColl)).withFailMessage( + "Granted Authorities do not match expected roles").isTrue(); } private J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource( String[] mappedRoles) { J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource result = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(); result.setMappableRolesRetriever(getMappableRolesRetriever(mappedRoles)); - result.setUserRoles2GrantedAuthoritiesMapper(getJ2eeUserRoles2GrantedAuthoritiesMapper()); + result.setUserRoles2GrantedAuthoritiesMapper( + getJ2eeUserRoles2GrantedAuthoritiesMapper()); try { result.afterPropertiesSet(); @@ -144,6 +155,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend private HttpServletRequest getRequest(final String userName, final String[] aRoles) { MockHttpServletRequest req = new MockHttpServletRequest() { + private Set roles = new HashSet(Arrays.asList(aRoles)); public boolean isUserInRole(String arg0) { diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilterTests.java index ed73479c0b..e9bc1d1f11 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilterTests.java @@ -1,5 +1,8 @@ + package org.springframework.security.web.authentication.preauth.j2ee; +import static org.assertj.core.api.Assertions.assertThat; + import java.security.Principal; import java.util.Arrays; import java.util.HashSet; @@ -7,35 +10,35 @@ import java.util.Set; import javax.servlet.http.HttpServletRequest; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.security.web.authentication.preauth.j2ee.J2eePreAuthenticatedProcessingFilter; /** * * @author TSARDD * @since 18-okt-2007 */ -public class J2eePreAuthenticatedProcessingFilterTests extends TestCase { +public class J2eePreAuthenticatedProcessingFilterTests { + @Test public final void testGetPreAuthenticatedPrincipal() { String user = "testUser"; - assertEquals(user, - new J2eePreAuthenticatedProcessingFilter() - .getPreAuthenticatedPrincipal(getRequest(user, new String[] {}))); + assertThat(user).isEqualTo( + new J2eePreAuthenticatedProcessingFilter().getPreAuthenticatedPrincipal( + getRequest(user, new String[] {}))); } + @Test public final void testGetPreAuthenticatedCredentials() { - assertEquals("N/A", - new J2eePreAuthenticatedProcessingFilter() - .getPreAuthenticatedCredentials(getRequest("testUser", - new String[] {}))); + assertThat("N/A").isEqualTo( + new J2eePreAuthenticatedProcessingFilter().getPreAuthenticatedCredentials( + getRequest("testUser", new String[] {}))); } private final HttpServletRequest getRequest(final String aUserName, final String[] aRoles) { MockHttpServletRequest req = new MockHttpServletRequest() { + private Set roles = new HashSet(Arrays.asList(aRoles)); public boolean isUserInRole(String arg0) { @@ -44,6 +47,7 @@ public class J2eePreAuthenticatedProcessingFilterTests extends TestCase { }; req.setRemoteUser(aUserName); req.setUserPrincipal(new Principal() { + public String getName() { return aUserName; } diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/WebXmlJ2eeDefinedRolesRetrieverTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/WebXmlJ2eeDefinedRolesRetrieverTests.java index 8cfbcbaa11..13602a041a 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/WebXmlJ2eeDefinedRolesRetrieverTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/WebXmlJ2eeDefinedRolesRetrieverTests.java @@ -33,12 +33,10 @@ public class WebXmlJ2eeDefinedRolesRetrieverTests { rolesRetriever.afterPropertiesSet(); Set j2eeRoles = rolesRetriever.getMappableAttributes(); assertThat(j2eeRoles).isNotNull(); - assertThat("J2eeRoles expected size: " + ROLE1TO4_EXPECTED_ROLES.size().isTrue() - + ", actual size: " + j2eeRoles.size(), - j2eeRoles.size() == ROLE1TO4_EXPECTED_ROLES.size()); - assertThat("J2eeRoles expected contents (arbitrary order).isTrue(): " - + ROLE1TO4_EXPECTED_ROLES + ", actual content: " + j2eeRoles, - j2eeRoles.containsAll(ROLE1TO4_EXPECTED_ROLES)); + assertThat(j2eeRoles.size()).withFailMessage("J2eeRoles expected size: " + ROLE1TO4_EXPECTED_ROLES.size() + + ", actual size: " + j2eeRoles.size()).isEqualTo(ROLE1TO4_EXPECTED_ROLES.size()); + assertThat(j2eeRoles).withFailMessage("J2eeRoles expected contents (arbitrary order).isTrue(): " + + ROLE1TO4_EXPECTED_ROLES + ", actual content: " + j2eeRoles).containsAll(ROLE1TO4_EXPECTED_ROLES); } @Test @@ -56,7 +54,6 @@ public class WebXmlJ2eeDefinedRolesRetrieverTests { }); rolesRetriever.afterPropertiesSet(); Set j2eeRoles = rolesRetriever.getMappableAttributes(); - assertThat(actual size: " + j2eeRoles.size().isEqualTo("J2eeRoles expected size: 0), 0, - j2eeRoles.size()); + assertThat(j2eeRoles).withFailMessage("actual size: " + j2eeRoles.size() + "J2eeRoles expected size: 0").isEmpty(); } } diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilterTests.java index da76ee6c37..64b0266285 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilterTests.java @@ -34,10 +34,10 @@ public class WebSpherePreAuthenticatedProcessingFilterTests { when(helper.getCurrentUserName()).thenReturn("jerry"); WebSpherePreAuthenticatedProcessingFilter filter = new WebSpherePreAuthenticatedProcessingFilter( helper); - assertEquals("jerry", - filter.getPreAuthenticatedPrincipal(new MockHttpServletRequest())); - assertEquals("N/A", - filter.getPreAuthenticatedCredentials(new MockHttpServletRequest())); + assertThat(filter.getPreAuthenticatedPrincipal(new MockHttpServletRequest())).isEqualTo( + "jerry"); + assertThat(filter.getPreAuthenticatedCredentials(new MockHttpServletRequest())).isEqualTo( + "N/A"); AuthenticationManager am = mock(AuthenticationManager.class); when(am.authenticate(any(Authentication.class))).thenAnswer( diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/x509/SubjectDnX509PrincipalExtractorTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/x509/SubjectDnX509PrincipalExtractorTests.java index c24ce667fe..4c865b526f 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/x509/SubjectDnX509PrincipalExtractorTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/x509/SubjectDnX509PrincipalExtractorTests.java @@ -1,5 +1,7 @@ package org.springframework.security.web.authentication.preauth.x509; +import static org.assertj.core.api.Assertions.assertThat; + import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.SpringSecurityMessageSource; import org.springframework.security.web.authentication.preauth.x509.SubjectDnX509PrincipalExtractor; @@ -7,8 +9,6 @@ import org.springframework.security.web.authentication.preauth.x509.SubjectDnX50 import org.junit.Test; import org.junit.Before; -import static junit.framework.Assert.*; - /** * @author Luke Taylor */ diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServicesTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServicesTests.java index 55ca14d3e1..aed3c169c0 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServicesTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServicesTests.java @@ -1,14 +1,9 @@ + package org.springframework.security.web.authentication.rememberme; -import static org.assertj.core.api.Assertions.*; -import static org.powermock.api.mockito.PowerMockito.*; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.powermock.api.mockito.PowerMockito.when; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; @@ -17,8 +12,7 @@ import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PrepareForTest; +import org.mockito.Mockito; import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.mock.web.MockHttpServletRequest; @@ -43,6 +37,7 @@ import org.springframework.util.StringUtils; @RunWith(PowerMockRunner.class) @PrepareOnlyThisForTest(ReflectionUtils.class) public class AbstractRememberMeServicesTests { + static User joe = new User("joe", "password", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_A")); @@ -71,7 +66,7 @@ public class AbstractRememberMeServicesTests { services.setTokenValiditySeconds(600); assertThat(services.getTokenValiditySeconds()).isEqualTo(600); assertThat(services.getUserDetailsService()).isSameAs(uds); - AuthenticationDetailsSource ads = mock(AuthenticationDetailsSource.class); + AuthenticationDetailsSource ads = Mockito.mock(AuthenticationDetailsSource.class); services.setAuthenticationDetailsSource(ads); assertThat(services.getAuthenticationDetailsSource()).isSameAs(ads); services.afterPropertiesSet(); @@ -97,7 +92,7 @@ public class AbstractRememberMeServicesTests { @Test public void cookieWithOpenIDidentifierAsNameIsEncodedAndDecoded() throws Exception { String[] cookie = new String[] { "http://id.openid.zz", "cookie", "tokens", - "blah" }; + "blah" }; MockRememberMeServices services = new MockRememberMeServices(uds); String[] decoded = services.decodeCookie(services.encodeCookie(cookie)); @@ -120,16 +115,16 @@ public class AbstractRememberMeServicesTests { assertThat(services.autoLogin(request, response)).isNull(); // shouldn't try to invalidate our cookie - assertNull(response - .getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)); + assertThat(response.getCookie( + AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull(); request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); // set non-login cookie request.setCookies(new Cookie("mycookie", "cookie")); assertThat(services.autoLogin(request, response)).isNull(); - assertNull(response - .getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)); + assertThat(response.getCookie( + AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull(); } @Test @@ -155,7 +150,8 @@ public class AbstractRememberMeServicesTests { MockHttpServletResponse response = new MockHttpServletResponse(); request.setCookies(new Cookie( - AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, "ZZZ")); + AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, + "ZZZ")); Authentication result = services.autoLogin(request, response); assertThat(result).isNull(); assertCookieCancelled(response); @@ -248,7 +244,7 @@ public class AbstractRememberMeServicesTests { request.setCookies(createLoginCookie("cookie:1:2")); MockHttpServletResponse response = new MockHttpServletResponse(); - services.logout(request, response, mock(Authentication.class)); + services.logout(request, response, Mockito.mock(Authentication.class)); // Try again with null Authentication response = new MockHttpServletResponse(); @@ -260,6 +256,7 @@ public class AbstractRememberMeServicesTests { @Test(expected = CookieTheftException.class) public void cookieTheftExceptionShouldBeRethrown() { MockRememberMeServices services = new MockRememberMeServices(uds) { + protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) { throw new CookieTheftException("Pretending cookie was stolen"); @@ -318,6 +315,7 @@ public class AbstractRememberMeServicesTests { MockHttpServletResponse response = new MockHttpServletResponse(); request.setContextPath("contextpath"); MockRememberMeServices services = new MockRememberMeServices(uds) { + protected String encodeCookie(String[] cookieTokens) { return cookieTokens[0]; } @@ -340,28 +338,29 @@ public class AbstractRememberMeServicesTests { request.setContextPath("contextpath"); MockRememberMeServices services = new MockRememberMeServices(uds) { + protected String encodeCookie(String[] cookieTokens) { return cookieTokens[0]; } }; services.setUseSecureCookie(true); services.setCookie(new String[] { "mycookie" }, 1000, request, response); - Cookie cookie = response - .getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + Cookie cookie = response.getCookie( + AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie.getSecure()).isTrue(); } @Test public void setHttpOnlyIgnoredForServlet25() throws Exception { spy(ReflectionUtils.class); - when(ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class)) - .thenReturn(null); + when(ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", + boolean.class)).thenReturn(null); MockRememberMeServices services = new MockRememberMeServices(uds); assertThat(ReflectionTestUtils.getField(services, "setHttpOnlyMethod")).isNull(); - services = new MockRememberMeServices("key", new MockUserDetailsService(joe, - false)); + services = new MockRememberMeServices("key", + new MockUserDetailsService(joe, false)); assertThat(ReflectionTestUtils.getField(services, "setHttpOnlyMethod")).isNull(); } @@ -374,8 +373,8 @@ public class AbstractRememberMeServicesTests { services.setCookie(new String[] { "value" }, 0, request, response); - Cookie cookie = response - .getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + Cookie cookie = response.getCookie( + AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie.getVersion()).isEqualTo(1); } @@ -388,8 +387,8 @@ public class AbstractRememberMeServicesTests { services.setCookie(new String[] { "value" }, -1, request, response); - Cookie cookie = response - .getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + Cookie cookie = response.getCookie( + AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie.getVersion()).isEqualTo(1); } @@ -402,8 +401,8 @@ public class AbstractRememberMeServicesTests { services.setCookie(new String[] { "value" }, 1, request, response); - Cookie cookie = response - .getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + Cookie cookie = response.getCookie( + AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie.getVersion()).isEqualTo(0); } @@ -411,15 +410,15 @@ public class AbstractRememberMeServicesTests { MockRememberMeServices services = new MockRememberMeServices(uds); Cookie cookie = new Cookie( AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, - services.encodeCookie(StringUtils.delimitedListToStringArray(cookieToken, - ":"))); + services.encodeCookie( + StringUtils.delimitedListToStringArray(cookieToken, ":"))); return new Cookie[] { cookie }; } private void assertCookieCancelled(MockHttpServletResponse response) { - Cookie returnedCookie = response - .getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + Cookie returnedCookie = response.getCookie( + AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(returnedCookie).isNotNull(); assertThat(returnedCookie.getMaxAge()).isEqualTo(0); } @@ -428,6 +427,7 @@ public class AbstractRememberMeServicesTests { // ================================================================================================== static class MockRememberMeServices extends AbstractRememberMeServices { + boolean loginSuccessCalled; MockRememberMeServices(String key, UserDetailsService userDetailsService) { @@ -449,7 +449,7 @@ public class AbstractRememberMeServicesTests { protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) - throws RememberMeAuthenticationException { + throws RememberMeAuthenticationException { if (cookieTokens.length != 3) { throw new InvalidCookieException("deliberate exception"); } @@ -461,7 +461,9 @@ public class AbstractRememberMeServicesTests { } public static class MockUserDetailsService implements UserDetailsService { + private UserDetails toReturn; + private boolean throwException; public MockUserDetailsService() { diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImplTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImplTests.java index a10320547f..ff4cdbd72b 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImplTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImplTests.java @@ -13,14 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.security.web.authentication.rememberme; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; import java.sql.Timestamp; +import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; @@ -44,17 +50,20 @@ import org.springframework.test.util.ReflectionTestUtils; */ @RunWith(MockitoJUnitRunner.class) public class JdbcTokenRepositoryImplTests { + @Mock private Log logger; private static SingleConnectionDataSource dataSource; + private JdbcTokenRepositoryImpl repo; + private JdbcTemplate template; @BeforeClass public static void createDataSource() { - dataSource = new SingleConnectionDataSource("jdbc:hsqldb:mem:tokenrepotest", - "sa", "", true); + dataSource = new SingleConnectionDataSource("jdbc:hsqldb:mem:tokenrepotest", "sa", + "", true); dataSource.setDriverClassName("org.hsqldb.jdbc.JDBCDriver"); } @@ -71,8 +80,9 @@ public class JdbcTokenRepositoryImplTests { repo.setDataSource(dataSource); repo.initDao(); template = repo.getJdbcTemplate(); - template.execute("create table persistent_logins (username varchar(100) not null, " - + "series varchar(100) not null, token varchar(500) not null, last_used timestamp not null)"); + template.execute( + "create table persistent_logins (username varchar(100) not null, " + + "series varchar(100) not null, token varchar(500) not null, last_used timestamp not null)"); } @After @@ -82,13 +92,13 @@ public class JdbcTokenRepositoryImplTests { @Test public void createNewTokenInsertsCorrectData() { - Date currentDate = new Date(); + Timestamp currentDate = new Timestamp(Calendar.getInstance().getTimeInMillis()); PersistentRememberMeToken token = new PersistentRememberMeToken("joeuser", "joesseries", "atoken", currentDate); repo.createNewToken(token); - Map results = template - .queryForMap("select * from persistent_logins"); + Map results = template.queryForMap( + "select * from persistent_logins"); assertThat(results.get("last_used")).isEqualTo(currentDate); assertThat(results.get("username")).isEqualTo("joeuser"); @@ -99,25 +109,30 @@ public class JdbcTokenRepositoryImplTests { @Test public void retrievingTokenReturnsCorrectData() { - template.execute("insert into persistent_logins (series, username, token, last_used) values " - + "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')"); + template.execute( + "insert into persistent_logins (series, username, token, last_used) values " + + "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')"); PersistentRememberMeToken token = repo.getTokenForSeries("joesseries"); assertThat(token.getUsername()).isEqualTo("joeuser"); assertThat(token.getSeries()).isEqualTo("joesseries"); assertThat(token.getTokenValue()).isEqualTo("atoken"); - assertThat(token.getDate()).isEqualTo(Timestamp.valueOf("2007-10-09 18:19:25.000000000")); + assertThat(token.getDate()).isEqualTo( + Timestamp.valueOf("2007-10-09 18:19:25.000000000")); } @Test public void retrievingTokenWithDuplicateSeriesReturnsNull() { - template.execute("insert into persistent_logins (series, username, token, last_used) values " - + "('joesseries', 'joeuser', 'atoken2', '2007-10-19 18:19:25.000000000')"); - template.execute("insert into persistent_logins (series, username, token, last_used) values " - + "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')"); + template.execute( + "insert into persistent_logins (series, username, token, last_used) values " + + "('joesseries', 'joeuser', 'atoken2', '2007-10-19 18:19:25.000000000')"); + template.execute( + "insert into persistent_logins (series, username, token, last_used) values " + + "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')"); // List results = - // template.queryForList("select * from persistent_logins where series = 'joesseries'"); + // template.queryForList("select * from persistent_logins where series = + // 'joesseries'"); assertThat(repo.getTokenForSeries("joesseries")).isNull(); } @@ -138,18 +153,21 @@ public class JdbcTokenRepositoryImplTests { @Test public void removingUserTokensDeletesData() { - template.execute("insert into persistent_logins (series, username, token, last_used) values " - + "('joesseries2', 'joeuser', 'atoken2', '2007-10-19 18:19:25.000000000')"); - template.execute("insert into persistent_logins (series, username, token, last_used) values " - + "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')"); + template.execute( + "insert into persistent_logins (series, username, token, last_used) values " + + "('joesseries2', 'joeuser', 'atoken2', '2007-10-19 18:19:25.000000000')"); + template.execute( + "insert into persistent_logins (series, username, token, last_used) values " + + "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')"); // List results = - // template.queryForList("select * from persistent_logins where series = 'joesseries'"); + // template.queryForList("select * from persistent_logins where series = + // 'joesseries'"); repo.removeUserTokens("joeuser"); - List> results = template - .queryForList("select * from persistent_logins where username = 'joeuser'"); + List> results = template.queryForList( + "select * from persistent_logins where username = 'joeuser'"); assertThat(results).isEmpty(); } @@ -157,12 +175,13 @@ public class JdbcTokenRepositoryImplTests { @Test public void updatingTokenModifiesTokenValueAndLastUsed() { Timestamp ts = new Timestamp(System.currentTimeMillis() - 1); - template.execute("insert into persistent_logins (series, username, token, last_used) values " - + "('joesseries', 'joeuser', 'atoken', '" + ts.toString() + "')"); + template.execute( + "insert into persistent_logins (series, username, token, last_used) values " + + "('joesseries', 'joeuser', 'atoken', '" + ts.toString() + "')"); repo.updateToken("joesseries", "newtoken", new Date()); - Map results = template - .queryForMap("select * from persistent_logins where series = 'joesseries'"); + Map results = template.queryForMap( + "select * from persistent_logins where series = 'joesseries'"); assertThat(results.get("username")).isEqualTo("joeuser"); assertThat(results.get("series")).isEqualTo("joesseries"); @@ -179,7 +198,8 @@ public class JdbcTokenRepositoryImplTests { repo.setCreateTableOnStartup(true); repo.initDao(); - template.queryForList("select username,series,token,last_used from persistent_logins"); + template.queryForList( + "select username,series,token,last_used from persistent_logins"); } // SEC-2879 diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/NullRememberMeServicesTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/NullRememberMeServicesTests.java index 0ad25b96ec..5d06c16f36 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/NullRememberMeServicesTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/NullRememberMeServicesTests.java @@ -15,19 +15,20 @@ package org.springframework.security.web.authentication.rememberme; -import org.springframework.security.web.authentication.NullRememberMeServices; +import static org.assertj.core.api.Assertions.assertThat; -import junit.framework.TestCase; +import org.junit.Test; +import org.springframework.security.web.authentication.NullRememberMeServices; /** * Tests {@link org.springframework.security.web.authentication.NullRememberMeServices}. * * @author Ben Alex */ -public class NullRememberMeServicesTests extends TestCase { +public class NullRememberMeServicesTests { // ~ Methods // ======================================================================================================== - + @Test public void testAlwaysReturnsNull() { NullRememberMeServices services = new NullRememberMeServices(); assertThat(services.autoLogin(null, null)).isNull(); diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java index 3b5ffeaaaa..0d82094f5b 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java @@ -307,8 +307,8 @@ public class TokenBasedRememberMeServicesTests { assertThat(cookie).isNotNull(); assertThat(cookie.getMaxAge()).isEqualTo(services.getTokenValiditySeconds()); assertThat(Base64.isArrayByteBase64(cookie.getValue().getBytes())).isTrue(); - assertThat(new Date().isTrue().before(new Date( - determineExpiryTimeFromBased64EncodedToken(cookie.getValue())))); + assertThat(new Date().before(new Date( + determineExpiryTimeFromBased64EncodedToken(cookie.getValue())))).isTrue(); } @Test @@ -324,8 +324,8 @@ public class TokenBasedRememberMeServicesTests { assertThat(cookie).isNotNull(); assertThat(cookie.getMaxAge()).isEqualTo(services.getTokenValiditySeconds()); assertThat(Base64.isArrayByteBase64(cookie.getValue().getBytes())).isTrue(); - assertThat(new Date().isTrue().before(new Date( - determineExpiryTimeFromBased64EncodedToken(cookie.getValue())))); + assertThat(new Date().before(new Date( + determineExpiryTimeFromBased64EncodedToken(cookie.getValue())))).isTrue(); } // SEC-933 @@ -351,8 +351,8 @@ public class TokenBasedRememberMeServicesTests { Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie).isNotNull(); // Check the expiry time is within 50ms of two weeks from current time - assertThat(determineExpiryTimeFromBased64EncodedToken(cookie.getValue()).isTrue() - - System.currentTimeMillis() > TWO_WEEKS_S - 50); + assertThat(determineExpiryTimeFromBased64EncodedToken(cookie.getValue()) + - System.currentTimeMillis() > TWO_WEEKS_S - 50).isTrue(); assertThat(cookie.getMaxAge()).isEqualTo(-1); assertThat(Base64.isArrayByteBase64(cookie.getValue().getBytes())).isTrue(); } diff --git a/web/src/test/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategyTests.java b/web/src/test/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategyTests.java index 0767e184f1..55ce1a990c 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategyTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategyTests.java @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.security.web.authentication.session; -import static junit.framework.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -38,14 +39,19 @@ import org.springframework.security.core.Authentication; */ @RunWith(MockitoJUnitRunner.class) public class CompositeSessionAuthenticationStrategyTests { + @Mock private SessionAuthenticationStrategy strategy1; + @Mock private SessionAuthenticationStrategy strategy2; + @Mock private Authentication authentication; + @Mock private HttpServletRequest request; + @Mock private HttpServletResponse response; @@ -78,8 +84,8 @@ public class CompositeSessionAuthenticationStrategyTests { @Test public void delegateShortCircuits() { - doThrow(new SessionAuthenticationException("oops")).when(strategy1) - .onAuthentication(authentication, request, response); + doThrow(new SessionAuthenticationException("oops")).when( + strategy1).onAuthentication(authentication, request, response); CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy( Arrays.asList(strategy1, strategy2)); diff --git a/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilterTests.java index 0cf25ddf88..a63e24331b 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilterTests.java @@ -193,8 +193,7 @@ public class SwitchUserFilterTests { verify(chain, never()).doFilter(request, response); assertThat(response.getRedirectedUrl()).isEqualTo("/mywebapp/switchfailed"); - assertThat("/switchfailed").isEqualTo( - FieldUtils.getFieldValue(filter, "switchFailureUrl")); + assertThat(FieldUtils.getFieldValue(filter, "switchFailureUrl")).isEqualTo("/switchfailed"); } @Test(expected = IllegalArgumentException.class) @@ -403,8 +402,8 @@ public class SwitchUserFilterTests { Authentication result = filter.attemptSwitchUser(request); assertThat(result != null).isTrue(); assertThat(result.getAuthorities()).hasSize(2); - assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities()).contains( - "ROLE_NEW")); + assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities())).contains( + "ROLE_NEW"); } // SEC-1763 diff --git a/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationEntryPointTests.java b/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationEntryPointTests.java index d5a176b40f..e35b0125f8 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationEntryPointTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationEntryPointTests.java @@ -15,10 +15,12 @@ package org.springframework.security.web.authentication.www; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.*; import org.springframework.security.authentication.DisabledException; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; +import org.junit.Before; +import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; @@ -27,29 +29,9 @@ import org.springframework.mock.web.MockHttpServletResponse; * * @author Ben Alex */ -public class BasicAuthenticationEntryPointTests extends TestCase { - // ~ Constructors - // =================================================================================================== - - public BasicAuthenticationEntryPointTests() { - super(); - } - - public BasicAuthenticationEntryPointTests(String arg0) { - super(arg0); - } - - // ~ Methods - // ======================================================================================================== - - public static void main(String[] args) { - junit.textui.TestRunner.run(BasicAuthenticationEntryPointTests.class); - } - - public final void setUp() throws Exception { - super.setUp(); - } +public class BasicAuthenticationEntryPointTests { + @Test public void testDetectsMissingRealmName() throws Exception { BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint(); @@ -61,13 +43,15 @@ public class BasicAuthenticationEntryPointTests extends TestCase { assertThat(expected.getMessage()).isEqualTo("realmName must be specified"); } } - + + @Test public void testGettersSetters() { BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint(); ep.setRealmName("realm"); assertThat(ep.getRealmName()).isEqualTo("realm"); } - + + @Test public void testNormalOperation() throws Exception { BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint(); diff --git a/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthUtilsTests.java b/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthUtilsTests.java index 61f027ca99..078c363be4 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthUtilsTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthUtilsTests.java @@ -15,82 +15,90 @@ package org.springframework.security.web.authentication.www; -import junit.framework.TestCase; - -import org.springframework.util.StringUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.Map; +import org.junit.Test; +import org.springframework.util.StringUtils; + /** * Tests {@link org.springframework.security.util.StringSplitUtils}. * * @author Ben Alex */ -public class DigestAuthUtilsTests extends TestCase { +public class DigestAuthUtilsTests { // ~ Constructors // =================================================================================================== // ~ Methods // ======================================================================================================== - + @Test public void testSplitEachArrayElementAndCreateMapNormalOperation() { // note it ignores malformed entries (ie those without an equals sign) String unsplit = "username=\"rod\", invalidEntryThatHasNoEqualsSign, realm=\"Contacts Realm\", nonce=\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\", uri=\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\", response=\"38644211cf9ac3da63ab639807e2baff\", qop=auth, nc=00000004, cnonce=\"2b8d329a8571b99a\""; String[] headerEntries = StringUtils.commaDelimitedListToStringArray(unsplit); - Map headerMap = DigestAuthUtils - .splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); + Map headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap( + headerEntries, "=", "\""); assertThat(headerMap.get("username")).isEqualTo("rod"); assertThat(headerMap.get("realm")).isEqualTo("Contacts Realm"); - assertEquals("MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==", - headerMap.get("nonce")); - assertEquals( - "/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4", - headerMap.get("uri")); - assertThat(headerMap.get("response")).isEqualTo("38644211cf9ac3da63ab639807e2baff"); + assertThat(headerMap.get("nonce")).isEqualTo( + "MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ=="); + assertThat(headerMap.get("uri")).isEqualTo( + "/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4"); + assertThat(headerMap.get("response")).isEqualTo( + "38644211cf9ac3da63ab639807e2baff"); assertThat(headerMap.get("qop")).isEqualTo("auth"); assertThat(headerMap.get("nc")).isEqualTo("00000004"); assertThat(headerMap.get("cnonce")).isEqualTo("2b8d329a8571b99a"); assertThat(headerMap).hasSize(8); } + @Test public void testSplitEachArrayElementAndCreateMapRespectsInstructionNotToRemoveCharacters() { String unsplit = "username=\"rod\", realm=\"Contacts Realm\", nonce=\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\", uri=\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\", response=\"38644211cf9ac3da63ab639807e2baff\", qop=auth, nc=00000004, cnonce=\"2b8d329a8571b99a\""; String[] headerEntries = StringUtils.commaDelimitedListToStringArray(unsplit); - Map headerMap = DigestAuthUtils - .splitEachArrayElementAndCreateMap(headerEntries, "=", null); + Map headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap( + headerEntries, "=", null); assertThat(headerMap.get("username")).isEqualTo("\"rod\""); assertThat(headerMap.get("realm")).isEqualTo("\"Contacts Realm\""); - assertEquals( - "\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\"", - headerMap.get("nonce")); - assertEquals( - "\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\"", - headerMap.get("uri")); - assertThat(headerMap.get("response")).isEqualTo("\"38644211cf9ac3da63ab639807e2baff\""); + assertThat(headerMap.get("nonce")).isEqualTo( + "\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\""); + assertThat(headerMap.get("uri")).isEqualTo( + "\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\""); + assertThat(headerMap.get("response")).isEqualTo( + "\"38644211cf9ac3da63ab639807e2baff\""); assertThat(headerMap.get("qop")).isEqualTo("auth"); assertThat(headerMap.get("nc")).isEqualTo("00000004"); assertThat(headerMap.get("cnonce")).isEqualTo("\"2b8d329a8571b99a\""); assertThat(headerMap).hasSize(8); } + @Test public void testSplitEachArrayElementAndCreateMapReturnsNullIfArrayEmptyOrNull() { - assertThat(DigestAuthUtils.splitEachArrayElementAndCreateMap(null, "=", "\"")).isNull(); - assertNull(DigestAuthUtils.splitEachArrayElementAndCreateMap(new String[] {}, - "=", "\"")); + assertThat(DigestAuthUtils.splitEachArrayElementAndCreateMap(null, "=", + "\"")).isNull(); + assertThat(DigestAuthUtils.splitEachArrayElementAndCreateMap(new String[] {}, "=", + "\"")).isNull(); } + @Test public void testSplitNormalOperation() { String unsplit = "username=\"rod==\""; - assertThat("=")[0]).as("username").isEqualTo(DigestAuthUtils.split(unsplit); - assertThat("=")[1]).as("\"rod==\"").isEqualTo(DigestAuthUtils.split(unsplit); // should not - // remove - // quotes or - // extra - // equals + assertThat(DigestAuthUtils.split(unsplit, "=")[0]).isEqualTo("username"); + assertThat(DigestAuthUtils.split(unsplit, "=")[1]).isEqualTo("\"rod==\"");// should + // not + // remove + // quotes + // or + // extra + // equals } + @Test public void testSplitRejectsNullsAndIncorrectLengthStrings() { try { DigestAuthUtils.split(null, "="); // null @@ -133,12 +141,13 @@ public class DigestAuthUtilsTests extends TestCase { } } + @Test public void testSplitWorksWithDifferentDelimiters() { - assertThat("/").length).isEqualTo(2, DigestAuthUtils.split("18/rod"); + assertThat(DigestAuthUtils.split("18/rod", "/").length).isEqualTo(2); assertThat(DigestAuthUtils.split("18/rod", "!")).isNull(); // only guarantees to split at FIRST delimiter, not EACH delimiter - assertThat("|").length).isEqualTo(2, DigestAuthUtils.split("18|rod|foo|bar"); + assertThat(DigestAuthUtils.split("18|rod|foo|bar", "|").length).isEqualTo(2); } public void testAuthorizationHeaderWithCommasIsSplitCorrectly() { diff --git a/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationEntryPointTests.java b/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationEntryPointTests.java index df3c74e36d..7fe8bbb750 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationEntryPointTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationEntryPointTests.java @@ -15,12 +15,13 @@ package org.springframework.security.web.authentication.www; -import java.util.Map; +import static org.assertj.core.api.Assertions.*; -import junit.framework.TestCase; +import java.util.Map; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; +import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.DisabledException; @@ -31,7 +32,7 @@ import org.springframework.util.StringUtils; * * @author Ben Alex */ -public class DigestAuthenticationEntryPointTests extends TestCase { +public class DigestAuthenticationEntryPointTests { // ~ Methods // ======================================================================================================== @@ -49,6 +50,7 @@ public class DigestAuthenticationEntryPointTests extends TestCase { assertThat(nonceTokens[1]).isEqualTo(expectedNonceSignature); } + @Test public void testDetectsMissingKey() throws Exception { DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint(); ep.setRealmName("realm"); @@ -61,7 +63,8 @@ public class DigestAuthenticationEntryPointTests extends TestCase { assertThat(expected.getMessage()).isEqualTo("key must be specified"); } } - + + @Test public void testDetectsMissingRealmName() throws Exception { DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint(); ep.setKey("dcdc"); @@ -75,7 +78,8 @@ public class DigestAuthenticationEntryPointTests extends TestCase { assertThat(expected.getMessage()).isEqualTo("realmName must be specified"); } } - + + @Test public void testGettersSetters() { DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint(); assertThat(ep.getNonceValiditySeconds()).isEqualTo(300); // 5 mins default @@ -86,7 +90,8 @@ public class DigestAuthenticationEntryPointTests extends TestCase { ep.setNonceValiditySeconds(12); assertThat(ep.getNonceValiditySeconds()).isEqualTo(12); } - + + @Test public void testNormalOperation() throws Exception { DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint(); ep.setRealmName("hello"); @@ -103,8 +108,7 @@ public class DigestAuthenticationEntryPointTests extends TestCase { // Check response is properly formed assertThat(response.getStatus()).isEqualTo(401); - assertEquals(true, - response.getHeader("WWW-Authenticate").toString().startsWith("Digest ")); + assertThat(response.getHeader("WWW-Authenticate").toString()).startsWith("Digest "); // Break up response header String header = response.getHeader("WWW-Authenticate").toString().substring(7); @@ -118,7 +122,8 @@ public class DigestAuthenticationEntryPointTests extends TestCase { checkNonceValid((String) headerMap.get("nonce")); } - + + @Test public void testOperationIfDueToStaleNonce() throws Exception { DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint(); ep.setRealmName("hello"); @@ -135,8 +140,8 @@ public class DigestAuthenticationEntryPointTests extends TestCase { // Check response is properly formed assertThat(response.getStatus()).isEqualTo(401); - assertThat(response.getHeader("WWW-Authenticate").toString().isTrue() - .startsWith("Digest ")); + assertThat(response.getHeader("WWW-Authenticate").toString()) + .startsWith("Digest "); // Break up response header String header = response.getHeader("WWW-Authenticate").toString().substring(7); diff --git a/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilterTests.java index 46512113ce..f994c3c230 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilterTests.java @@ -15,13 +15,7 @@ package org.springframework.security.web.authentication.www; -import static org.assertj.core.api.Assertions.*; - import static org.assertj.core.api.Assertions.assertThat; -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.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -63,12 +57,19 @@ public class DigestAuthenticationFilterTests { // ===================================================================================== private static final String NC = "00000002"; + private static final String CNONCE = "c822c727a648aba7"; + private static final String REALM = "The Actual, Correct Realm Name"; + private static final String KEY = "springsecurity"; + private static final String QOP = "auth"; + private static final String USERNAME = "rod,ok"; + private static final String PASSWORD = "koala"; + private static final String REQUEST_URI = "/some_file.html"; /** @@ -81,6 +82,7 @@ public class DigestAuthenticationFilterTests { // private ApplicationContext ctx; private DigestAuthenticationFilter filter; + private MockHttpServletRequest request; // ~ Methods @@ -95,7 +97,7 @@ public class DigestAuthenticationFilterTests { private MockHttpServletResponse executeFilterInContainerSimulator(Filter filter, final ServletRequest request, final boolean expectChainToProceed) - throws ServletException, IOException { + throws ServletException, IOException { final MockHttpServletResponse response = new MockHttpServletResponse(); final FilterChain chain = mock(FilterChain.class); @@ -125,10 +127,11 @@ public class DigestAuthenticationFilterTests { // Create User Details Service UserDetailsService uds = new UserDetailsService() { + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - return new User("rod,ok", "koala", AuthorityUtils.createAuthorityList( - "ROLE_ONE", "ROLE_TWO")); + return new User("rod,ok", "koala", + AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); } }; @@ -150,10 +153,8 @@ public class DigestAuthenticationFilterTests { String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE); - request.addHeader( - "Authorization", - createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, - responseDigest, QOP, NC, CNONCE)); + request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, + nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); Thread.sleep(1000); // ensures token expired @@ -165,8 +166,8 @@ public class DigestAuthenticationFilterTests { String header = response.getHeader("WWW-Authenticate").toString().substring(7); String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header); - Map headerMap = DigestAuthUtils - .splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); + Map headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap( + headerEntries, "=", "\""); assertThat(headerMap.get("stale")).isEqualTo("true"); } @@ -225,10 +226,8 @@ public class DigestAuthenticationFilterTests { String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE); - request.addHeader( - "Authorization", - createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, - responseDigest, QOP, NC, CNONCE)); + request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, + nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false); @@ -240,15 +239,13 @@ public class DigestAuthenticationFilterTests { @Test public void testNonceWithIncorrectSignatureForNumericFieldReturnsForbidden() throws Exception { - String nonce = new String(Base64.encodeBase64("123456:incorrectStringPassword" - .getBytes())); + String nonce = new String( + Base64.encodeBase64("123456:incorrectStringPassword".getBytes())); String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE); - request.addHeader( - "Authorization", - createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, - responseDigest, QOP, NC, CNONCE)); + request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, + nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false); @@ -259,15 +256,13 @@ public class DigestAuthenticationFilterTests { @Test public void testNonceWithNonNumericFirstElementReturnsForbidden() throws Exception { - String nonce = new String(Base64.encodeBase64("hello:ignoredSecondElement" - .getBytes())); + String nonce = new String( + Base64.encodeBase64("hello:ignoredSecondElement".getBytes())); String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE); - request.addHeader( - "Authorization", - createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, - responseDigest, QOP, NC, CNONCE)); + request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, + nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false); @@ -279,15 +274,13 @@ public class DigestAuthenticationFilterTests { @Test public void testNonceWithoutTwoColonSeparatedElementsReturnsForbidden() throws Exception { - String nonce = new String(Base64.encodeBase64("a base 64 string without a colon" - .getBytes())); + String nonce = new String( + Base64.encodeBase64("a base 64 string without a colon".getBytes())); String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE); - request.addHeader( - "Authorization", - createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, - responseDigest, QOP, NC, CNONCE)); + request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, + nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false); @@ -298,21 +291,20 @@ public class DigestAuthenticationFilterTests { @Test public void testNormalOperationWhenPasswordIsAlreadyEncoded() throws Exception { - String encodedPassword = DigestAuthUtils.encodePasswordInA1Format(USERNAME, - REALM, PASSWORD); + String encodedPassword = DigestAuthUtils.encodePasswordInA1Format(USERNAME, REALM, + PASSWORD); String responseDigest = DigestAuthUtils.generateDigest(true, USERNAME, REALM, encodedPassword, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); - request.addHeader( - "Authorization", - createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, - responseDigest, QOP, NC, CNONCE)); + request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, + NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); executeFilterInContainerSimulator(filter, request, true); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); - assertThat(((UserDetails) SecurityContextHolder.getContext().isEqualTo(USERNAME) - .getAuthentication().getPrincipal()).getUsername()); + assertThat( + ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()).isEqualTo( + USERNAME); } @Test @@ -320,18 +312,17 @@ public class DigestAuthenticationFilterTests { String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); - request.addHeader( - "Authorization", - createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, - responseDigest, QOP, NC, CNONCE)); + request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, + NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); executeFilterInContainerSimulator(filter, request, true); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); - assertThat(((UserDetails) SecurityContextHolder.getContext().isEqualTo(USERNAME) - .getAuthentication().getPrincipal()).getUsername()); - assertThat(SecurityContextHolder.getContext().getAuthentication().isFalse() - .isAuthenticated()); + assertThat( + ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()).isEqualTo( + USERNAME); + assertThat( + SecurityContextHolder.getContext().getAuthentication().isAuthenticated()).isFalse(); } @Test @@ -340,21 +331,21 @@ public class DigestAuthenticationFilterTests { String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); - request.addHeader( - "Authorization", - createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, - responseDigest, QOP, NC, CNONCE)); + request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, + NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); filter.setCreateAuthenticatedToken(true); executeFilterInContainerSimulator(filter, request, true); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); - assertThat(((UserDetails) SecurityContextHolder.getContext().isEqualTo(USERNAME) - .getAuthentication().getPrincipal()).getUsername()); - assertThat(SecurityContextHolder.getContext().getAuthentication().isTrue() - .isAuthenticated()); - assertThat("ROLE_TWO").isEqualTo(AuthorityUtils.createAuthorityList("ROLE_ONE"), - SecurityContextHolder.getContext().getAuthentication().getAuthorities()); + assertThat( + ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()).isEqualTo( + USERNAME); + assertThat( + SecurityContextHolder.getContext().getAuthentication().isAuthenticated()).isTrue(); + assertThat( + SecurityContextHolder.getContext().getAuthentication().getAuthorities()).isEqualTo( + AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); } @Test @@ -386,10 +377,8 @@ public class DigestAuthenticationFilterTests { String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); - request.addHeader( - "Authorization", - createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, - responseDigest, QOP, NC, CNONCE)); + request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, + NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); executeFilterInContainerSimulator(filter, request, true); @@ -400,10 +389,8 @@ public class DigestAuthenticationFilterTests { "WRONG_PASSWORD", "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); request = new MockHttpServletRequest(); - request.addHeader( - "Authorization", - createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, - responseDigest, QOP, NC, CNONCE)); + request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, + NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false); @@ -420,10 +407,8 @@ public class DigestAuthenticationFilterTests { String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, "DIFFERENT_CNONCE"); - request.addHeader( - "Authorization", - createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, - responseDigest, QOP, NC, cnonce)); + request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, + NONCE, REQUEST_URI, responseDigest, QOP, NC, cnonce)); MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false); @@ -438,10 +423,8 @@ public class DigestAuthenticationFilterTests { String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, password, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); - request.addHeader( - "Authorization", - createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, - responseDigest, QOP, NC, CNONCE)); + request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, + NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false); @@ -456,10 +439,8 @@ public class DigestAuthenticationFilterTests { String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, realm, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); - request.addHeader( - "Authorization", - createAuthorizationHeader(USERNAME, realm, NONCE, REQUEST_URI, - responseDigest, QOP, NC, CNONCE)); + request.addHeader("Authorization", createAuthorizationHeader(USERNAME, realm, + NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false); @@ -473,10 +454,8 @@ public class DigestAuthenticationFilterTests { String responseDigest = DigestAuthUtils.generateDigest(false, "NOT_A_KNOWN_USER", REALM, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); - request.addHeader( - "Authorization", - createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, - responseDigest, QOP, NC, CNONCE)); + request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, + NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false); @@ -489,7 +468,8 @@ public class DigestAuthenticationFilterTests { @Test public void authenticationCreatesEmptyContext() throws Exception { SecurityContext existingContext = SecurityContextHolder.createEmptyContext(); - TestingAuthenticationToken existingAuthentication = new TestingAuthenticationToken("existingauthenitcated", "pass", "ROLE_USER"); + TestingAuthenticationToken existingAuthentication = new TestingAuthenticationToken( + "existingauthenitcated", "pass", "ROLE_USER"); existingContext.setAuthentication(existingAuthentication); SecurityContextHolder.setContext(existingContext); @@ -497,10 +477,8 @@ public class DigestAuthenticationFilterTests { String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE); - request.addHeader( - "Authorization", - createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, - responseDigest, QOP, NC, CNONCE)); + request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM, + NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE)); filter.setCreateAuthenticatedToken(true); executeFilterInContainerSimulator(filter, request, true); diff --git a/web/src/test/java/org/springframework/security/web/concurrent/ConcurrentSessionFilterTests.java b/web/src/test/java/org/springframework/security/web/concurrent/ConcurrentSessionFilterTests.java index f7f542595a..0d5bcd1d84 100644 --- a/web/src/test/java/org/springframework/security/web/concurrent/ConcurrentSessionFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/concurrent/ConcurrentSessionFilterTests.java @@ -87,9 +87,8 @@ public class ConcurrentSessionFilterTests { filter.doFilter(request, response, fc); verifyZeroInteractions(fc); - assertEquals( - "This session has been expired (possibly due to multiple concurrent logins being " - + "attempted as the same user).", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("This session has been expired (possibly due to multiple concurrent logins being " + + "attempted as the same user)."); } @Test(expected = IllegalArgumentException.class) @@ -126,7 +125,6 @@ public class ConcurrentSessionFilterTests { filter.doFilter(request, response, fc); verify(fc).doFilter(request, response); - assertThat(registry.getSessionInformation(session.getId()).getLastRequest().isTrue() - .after(lastRequest)); + assertThat(registry.getSessionInformation(session.getId()).getLastRequest().after(lastRequest)).isTrue(); } } diff --git a/web/src/test/java/org/springframework/security/web/context/HttpSessionSecurityContextRepositoryTests.java b/web/src/test/java/org/springframework/security/web/context/HttpSessionSecurityContextRepositoryTests.java index 68733d7b40..1e67016001 100644 --- a/web/src/test/java/org/springframework/security/web/context/HttpSessionSecurityContextRepositoryTests.java +++ b/web/src/test/java/org/springframework/security/web/context/HttpSessionSecurityContextRepositoryTests.java @@ -10,14 +10,10 @@ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ + package org.springframework.security.web.context; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; @@ -29,7 +25,11 @@ import static org.springframework.security.web.context.HttpSessionSecurityContex import javax.servlet.ServletOutputStream; import javax.servlet.ServletRequest; -import javax.servlet.http.*; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpServletResponseWrapper; +import javax.servlet.http.HttpSession; import org.junit.After; import org.junit.Test; @@ -53,6 +53,7 @@ import org.springframework.util.ClassUtils; @RunWith(PowerMockRunner.class) @PrepareForTest({ ClassUtils.class }) public class HttpSessionSecurityContextRepositoryTests { + private final TestingAuthenticationToken testToken = new TestingAuthenticationToken( "someone", "passwd", "ROLE_A"); @@ -214,8 +215,9 @@ public class HttpSessionSecurityContextRepositoryTests { context.setAuthentication(testToken); repo.saveContext(context, holder.getRequest(), holder.getResponse()); assertThat(request.getSession(false)).isNotNull(); - assertEquals(context, - request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)); + assertThat( + request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isEqualTo( + context); } @Test @@ -229,15 +231,15 @@ public class HttpSessionSecurityContextRepositoryTests { SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(testToken); holder.getResponse().sendRedirect("/doesntmatter"); - assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext()) - .getAttribute("imTheContext")); - assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isTrue() - .isContextSaved()); + assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo( + SecurityContextHolder.getContext()); + assertThat( + ((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue(); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); // Check it's still the same - assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext()) - .getAttribute("imTheContext")); + assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo( + SecurityContextHolder.getContext()); } @Test @@ -251,15 +253,16 @@ public class HttpSessionSecurityContextRepositoryTests { SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(testToken); holder.getResponse().sendError(404); - assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext()) - .getAttribute("imTheContext")); - assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isTrue() - .isContextSaved()); + assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo( + SecurityContextHolder.getContext()); + + assertThat( + ((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue(); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); // Check it's still the same - assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext()) - .getAttribute("imTheContext")); + assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo( + SecurityContextHolder.getContext()); } // SEC-2005 @@ -274,15 +277,15 @@ public class HttpSessionSecurityContextRepositoryTests { SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(testToken); holder.getResponse().flushBuffer(); - assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext()) - .getAttribute("imTheContext")); - assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isTrue() - .isContextSaved()); + assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo( + SecurityContextHolder.getContext()); + assertThat( + ((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue(); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); // Check it's still the same - assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext()) - .getAttribute("imTheContext")); + assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo( + SecurityContextHolder.getContext()); } // SEC-2005 @@ -297,15 +300,15 @@ public class HttpSessionSecurityContextRepositoryTests { SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(testToken); holder.getResponse().getWriter().flush(); - assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext()) - .getAttribute("imTheContext")); - assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isTrue() - .isContextSaved()); + assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo( + SecurityContextHolder.getContext()); + assertThat( + ((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue(); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); // Check it's still the same - assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext()) - .getAttribute("imTheContext")); + assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo( + SecurityContextHolder.getContext()); } // SEC-2005 @@ -320,15 +323,15 @@ public class HttpSessionSecurityContextRepositoryTests { SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(testToken); holder.getResponse().getWriter().close(); - assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext()) - .getAttribute("imTheContext")); - assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isTrue() - .isContextSaved()); + assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo( + SecurityContextHolder.getContext()); + assertThat( + ((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue(); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); // Check it's still the same - assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext()) - .getAttribute("imTheContext")); + assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo( + SecurityContextHolder.getContext()); } // SEC-2005 @@ -343,15 +346,15 @@ public class HttpSessionSecurityContextRepositoryTests { SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(testToken); holder.getResponse().getOutputStream().flush(); - assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext()) - .getAttribute("imTheContext")); - assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isTrue() - .isContextSaved()); + assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo( + SecurityContextHolder.getContext()); + assertThat( + ((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue(); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); // Check it's still the same - assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext()) - .getAttribute("imTheContext")); + assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo( + SecurityContextHolder.getContext()); } // SEC-2005 @@ -366,15 +369,15 @@ public class HttpSessionSecurityContextRepositoryTests { SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(testToken); holder.getResponse().getOutputStream().close(); - assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext()) - .getAttribute("imTheContext")); - assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isTrue() - .isContextSaved()); + assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo( + SecurityContextHolder.getContext()); + assertThat( + ((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue(); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); // Check it's still the same - assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext()) - .getAttribute("imTheContext")); + assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo( + SecurityContextHolder.getContext()); } // SEC-SEC-2055 @@ -438,8 +441,8 @@ public class HttpSessionSecurityContextRepositoryTests { response); SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication( - new AnonymousAuthenticationToken("key", "anon", AuthorityUtils - .createAuthorityList("ANON"))); + new AnonymousAuthenticationToken("key", "anon", + AuthorityUtils.createAuthorityList("ANON"))); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); assertThat(request.getSession(false)).isNull(); @@ -447,7 +450,8 @@ public class HttpSessionSecurityContextRepositoryTests { // SEC-1587 @Test - public void contextIsRemovedFromSessionIfCurrentContextIsAnonymous() throws Exception { + public void contextIsRemovedFromSessionIfCurrentContextIsAnonymous() + throws Exception { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext(); @@ -460,7 +464,8 @@ public class HttpSessionSecurityContextRepositoryTests { new AnonymousAuthenticationToken("x", "x", testToken.getAuthorities())); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); - assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull(); + assertThat( + request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull(); } @Test @@ -493,11 +498,11 @@ public class HttpSessionSecurityContextRepositoryTests { ctxInSession.setAuthentication(testToken); request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctxInSession); SecurityContextHolder.getContext().setAuthentication( - new AnonymousAuthenticationToken("x", "x", AuthorityUtils - .createAuthorityList("ROLE_ANONYMOUS"))); + new AnonymousAuthenticationToken("x", "x", + AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"))); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); - assertSame(ctxInSession, + assertThat(ctxInSession).isSameAs( request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)); } @@ -510,13 +515,15 @@ public class HttpSessionSecurityContextRepositoryTests { ctxInSession.setAuthentication(testToken); request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctxInSession); - HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse()); + HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, + new MockHttpServletResponse()); repo.loadContext(holder); ctxInSession.setAuthentication(null); repo.saveContext(ctxInSession, holder.getRequest(), holder.getResponse()); - assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull(); + assertThat( + request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull(); } @Test @@ -527,6 +534,7 @@ public class HttpSessionSecurityContextRepositoryTests { MockHttpServletRequest request = new MockHttpServletRequest(); final String sessionId = ";jsessionid=id"; MockHttpServletResponse response = new MockHttpServletResponse() { + @Override public String encodeRedirectUrl(String url) { return url + sessionId; @@ -551,8 +559,10 @@ public class HttpSessionSecurityContextRepositoryTests { response); repo.loadContext(holder); String url = "/aUrl"; - assertThat(holder.getResponse().encodeRedirectUrl(url)).isEqualTo(url + sessionId); - assertThat(holder.getResponse().encodeRedirectURL(url)).isEqualTo(url + sessionId); + assertThat(holder.getResponse().encodeRedirectUrl(url)).isEqualTo( + url + sessionId); + assertThat(holder.getResponse().encodeRedirectURL(url)).isEqualTo( + url + sessionId); assertThat(holder.getResponse().encodeUrl(url)).isEqualTo(url + sessionId); assertThat(holder.getResponse().encodeURL(url)).isEqualTo(url + sessionId); repo.setDisableUrlRewriting(true); @@ -573,7 +583,8 @@ public class HttpSessionSecurityContextRepositoryTests { HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse()); repo.loadContext(holder); - AuthenticationTrustResolver trustResolver = mock(AuthenticationTrustResolver.class); + AuthenticationTrustResolver trustResolver = mock( + AuthenticationTrustResolver.class); repo.setTrustResolver(trustResolver); repo.saveContext(contextToSave, holder.getRequest(), holder.getResponse()); @@ -604,8 +615,9 @@ public class HttpSessionSecurityContextRepositoryTests { new HttpServletResponseWrapper(holder.getResponse())); assertThat(request.getSession(false)).isNotNull(); - assertEquals(context, - request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)); + assertThat( + request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isEqualTo( + context); } @Test(expected = IllegalStateException.class) diff --git a/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java b/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java index 5571f4cb12..1b2dc49c39 100644 --- a/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java @@ -52,7 +52,7 @@ public class SecurityContextPersistenceFilterTests { any(ServletResponse.class)); try { filter.doFilter(request, response, chain); - fail(); + fail("IOException should have been thrown"); } catch (IOException expected) { } @@ -80,8 +80,7 @@ public class SecurityContextPersistenceFilterTests { final FilterChain chain = new FilterChain() { public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { - assertThat(SecurityContextHolder.getContext().isEqualTo(beforeAuth) - .getAuthentication()); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo(beforeAuth); // Change the context here SecurityContextHolder.setContext(scExpectedAfter); } diff --git a/web/src/test/java/org/springframework/security/web/firewall/FirewalledResponseTests.java b/web/src/test/java/org/springframework/security/web/firewall/FirewalledResponseTests.java index c7d0219dcc..15fa6e2034 100644 --- a/web/src/test/java/org/springframework/security/web/firewall/FirewalledResponseTests.java +++ b/web/src/test/java/org/springframework/security/web/firewall/FirewalledResponseTests.java @@ -21,20 +21,20 @@ public class FirewalledResponseTests { try { fwResponse.sendRedirect("/theURL\r\nsomething"); - fail(); + fail("IllegalArgumentException should have thrown"); } catch (IllegalArgumentException expected) { } try { fwResponse.sendRedirect("/theURL\rsomething"); - fail(); + fail("IllegalArgumentException should have thrown"); } catch (IllegalArgumentException expected) { } try { fwResponse.sendRedirect("/theURL\nsomething"); - fail(); + fail("IllegalArgumentException should have thrown"); } catch (IllegalArgumentException expected) { } diff --git a/web/src/test/java/org/springframework/security/web/header/writers/frameoptions/RegExpAllowFromStrategyTests.java b/web/src/test/java/org/springframework/security/web/header/writers/frameoptions/RegExpAllowFromStrategyTests.java index 4c031dcb6d..5a326d97de 100644 --- a/web/src/test/java/org/springframework/security/web/header/writers/frameoptions/RegExpAllowFromStrategyTests.java +++ b/web/src/test/java/org/springframework/security/web/header/writers/frameoptions/RegExpAllowFromStrategyTests.java @@ -1,13 +1,12 @@ + package org.springframework.security.web.header.writers.frameoptions; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.regex.PatternSyntaxException; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.security.web.header.writers.frameoptions.RegExpAllowFromStrategy; /** * @@ -34,15 +33,15 @@ public class RegExpAllowFromStrategyTests { request.setParameter("from", "http://abc.test.com"); String result1 = strategy.getAllowFromValue(request); - assertThat(result1, is("http://abc.test.com")); + assertThat(result1).isEqualTo("http://abc.test.com"); request.setParameter("from", "http://foo.test.com"); String result2 = strategy.getAllowFromValue(request); - assertThat(result2, is("http://foo.test.com")); + assertThat(result2).isEqualTo("http://foo.test.com"); request.setParameter("from", "http://test.foobar.com"); String result3 = strategy.getAllowFromValue(request); - assertThat(result3, is("DENY")); + assertThat(result3).isEqualTo("DENY"); } @Test @@ -51,6 +50,6 @@ public class RegExpAllowFromStrategyTests { "^http://([a-z0-9]*?\\.)test\\.com"); MockHttpServletRequest request = new MockHttpServletRequest(); String result1 = strategy.getAllowFromValue(request); - assertThat(result1, is("DENY")); + assertThat(result1).isEqualTo("DENY"); } } diff --git a/web/src/test/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilterTests.java b/web/src/test/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilterTests.java index 4d6acd0f96..b563b6a5ae 100644 --- a/web/src/test/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilterTests.java @@ -13,11 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.security.web.jaasapi; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import java.io.IOException; import java.security.AccessController; @@ -51,7 +50,6 @@ import org.springframework.security.authentication.jaas.TestLoginModule; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.web.jaasapi.JaasApiIntegrationFilter; /** * Tests the JaasApiIntegrationFilter. @@ -59,14 +57,21 @@ import org.springframework.security.web.jaasapi.JaasApiIntegrationFilter; * @author Rob Winch */ public class JaasApiIntegrationFilterTests { + // ~ Instance fields // ================================================================================================ private JaasApiIntegrationFilter filter; + private MockHttpServletRequest request; + private MockHttpServletResponse response; + private Authentication token; + private Subject authenticatedSubject; + private Configuration testConfiguration; + private CallbackHandler callbackHandler; // ~ Methods @@ -80,6 +85,7 @@ public class JaasApiIntegrationFilterTests { authenticatedSubject = new Subject(); authenticatedSubject.getPrincipals().add(new Principal() { + public String getName() { return "principal"; } @@ -87,15 +93,16 @@ public class JaasApiIntegrationFilterTests { authenticatedSubject.getPrivateCredentials().add("password"); authenticatedSubject.getPublicCredentials().add("username"); callbackHandler = new CallbackHandler() { - public void handle(Callback[] callbacks) throws IOException, - UnsupportedCallbackException { + + public void handle(Callback[] callbacks) + throws IOException, UnsupportedCallbackException { for (Callback callback : callbacks) { if (callback instanceof NameCallback) { ((NameCallback) callback).setName("user"); } else if (callback instanceof PasswordCallback) { - ((PasswordCallback) callback).setPassword("password" - .toCharArray()); + ((PasswordCallback) callback).setPassword( + "password".toCharArray()); } else if (callback instanceof TextInputCallback) { // ignore @@ -108,6 +115,7 @@ public class JaasApiIntegrationFilterTests { } }; testConfiguration = new Configuration() { + public void refresh() { } @@ -117,8 +125,8 @@ public class JaasApiIntegrationFilterTests { new HashMap()) }; } }; - LoginContext ctx = new LoginContext("SubjectDoAsFilterTest", - authenticatedSubject, callbackHandler, testConfiguration); + LoginContext ctx = new LoginContext("SubjectDoAsFilterTest", authenticatedSubject, + callbackHandler, testConfiguration); ctx.login(); token = new JaasAuthenticationToken("username", "password", AuthorityUtils.createAuthorityList("ROLE_ADMIN"), ctx); @@ -206,11 +214,12 @@ public class JaasApiIntegrationFilterTests { private void assertJaasSubjectEquals(final Subject expectedValue) throws Exception { MockFilterChain chain = new MockFilterChain() { + public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { // See if the subject was updated - Subject currentSubject = Subject - .getSubject(AccessController.getContext()); + Subject currentSubject = Subject.getSubject( + AccessController.getContext()); assertThat(currentSubject).isEqualTo(expectedValue); // run so we know the chain was executed @@ -223,6 +232,7 @@ public class JaasApiIntegrationFilterTests { } private void assertNullSubject(Subject subject) { - assertThat("Subject is expected to be null, but is not. Got " + subject, subject).isNull(); + assertThat(subject).withFailMessage( + "Subject is expected to be null, but is not. Got " + subject).isNull(); } } diff --git a/web/src/test/java/org/springframework/security/web/savedrequest/HttpSessionRequestCacheTests.java b/web/src/test/java/org/springframework/security/web/savedrequest/HttpSessionRequestCacheTests.java index d36747fbfa..60b3b45d68 100644 --- a/web/src/test/java/org/springframework/security/web/savedrequest/HttpSessionRequestCacheTests.java +++ b/web/src/test/java/org/springframework/security/web/savedrequest/HttpSessionRequestCacheTests.java @@ -1,8 +1,7 @@ + package org.springframework.security.web.savedrequest; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import java.util.Collection; import java.util.List; @@ -30,11 +29,12 @@ public class HttpSessionRequestCacheTests { public void originalGetRequestDoesntMatchIncomingPost() { HttpSessionRequestCache cache = new HttpSessionRequestCache(); - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/destination"); + MockHttpServletRequest request = new MockHttpServletRequest("GET", + "/destination"); MockHttpServletResponse response = new MockHttpServletResponse(); cache.saveRequest(request, response); - assertThat(request.getSession().isNotNull().getAttribute( - HttpSessionRequestCache.SAVED_REQUEST)); + assertThat(request.getSession().getAttribute( + HttpSessionRequestCache.SAVED_REQUEST)).isNotNull(); assertThat(cache.getRequest(request, response)).isNotNull(); MockHttpServletRequest newRequest = new MockHttpServletRequest("POST", @@ -48,6 +48,7 @@ public class HttpSessionRequestCacheTests { public void requestMatcherDefinesCorrectSubsetOfCachedRequests() throws Exception { HttpSessionRequestCache cache = new HttpSessionRequestCache(); cache.setRequestMatcher(new RequestMatcher() { + public boolean matches(HttpServletRequest request) { return request.getMethod().equals("GET"); } @@ -58,8 +59,8 @@ public class HttpSessionRequestCacheTests { MockHttpServletResponse response = new MockHttpServletResponse(); cache.saveRequest(request, response); assertThat(cache.getRequest(request, response)).isNull(); - assertThat(cache.getRequest(new MockHttpServletRequest().isNull(), - new MockHttpServletResponse())); + assertThat(cache.getRequest(new MockHttpServletRequest(), + new MockHttpServletResponse())).isNull(); assertThat(cache.getMatchingRequest(request, response)).isNull(); } @@ -74,10 +75,8 @@ public class HttpSessionRequestCacheTests { @Override public void saveRequest(HttpServletRequest request, HttpServletResponse response) { - request.getSession().setAttribute( - SAVED_REQUEST, - new CustomSavedRequest(new DefaultSavedRequest(request, - new PortResolverImpl()))); + request.getSession().setAttribute(SAVED_REQUEST, new CustomSavedRequest( + new DefaultSavedRequest(request, new PortResolverImpl()))); } }; @@ -89,6 +88,7 @@ public class HttpSessionRequestCacheTests { } private static final class CustomSavedRequest implements SavedRequest { + private final SavedRequest delegate; private CustomSavedRequest(SavedRequest delegate) { diff --git a/web/src/test/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilterTests.java b/web/src/test/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilterTests.java index 8923e5ebbf..c079692ad1 100644 --- a/web/src/test/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilterTests.java @@ -18,11 +18,11 @@ public class RequestCacheAwareFilterTests { "/destination"); MockHttpServletResponse response = new MockHttpServletResponse(); cache.saveRequest(request, response); - assertThat(request.getSession().isNotNull().getAttribute( - HttpSessionRequestCache.SAVED_REQUEST)); + assertThat(request.getSession().getAttribute( + HttpSessionRequestCache.SAVED_REQUEST)).isNotNull(); filter.doFilter(request, response, new MockFilterChain()); - assertThat(request.getSession().isNull().getAttribute( - HttpSessionRequestCache.SAVED_REQUEST)); + assertThat(request.getSession().getAttribute( + HttpSessionRequestCache.SAVED_REQUEST)).isNull(); } } diff --git a/web/src/test/java/org/springframework/security/web/savedrequest/SavedCookieTests.java b/web/src/test/java/org/springframework/security/web/savedrequest/SavedCookieTests.java index 0ebc356d9a..d832ba837e 100644 --- a/web/src/test/java/org/springframework/security/web/savedrequest/SavedCookieTests.java +++ b/web/src/test/java/org/springframework/security/web/savedrequest/SavedCookieTests.java @@ -1,19 +1,22 @@ package org.springframework.security.web.savedrequest; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.*; import javax.servlet.http.Cookie; +import org.junit.Before; +import org.junit.Test; import org.springframework.security.web.savedrequest.SavedCookie; import java.io.Serializable; -public class SavedCookieTests extends TestCase { +public class SavedCookieTests { Cookie cookie; SavedCookie savedCookie; - protected void setUp() throws Exception { + @Before + public void setUp() throws Exception { cookie = new Cookie("name", "value"); cookie.setComment("comment"); cookie.setDomain("domain"); @@ -24,34 +27,42 @@ public class SavedCookieTests extends TestCase { savedCookie = new SavedCookie(cookie); } + @Test public void testGetName() throws Exception { assertThat(savedCookie.getName()).isEqualTo(cookie.getName()); } + @Test public void testGetValue() throws Exception { assertThat(savedCookie.getValue()).isEqualTo(cookie.getValue()); } + @Test public void testGetComment() throws Exception { assertThat(savedCookie.getComment()).isEqualTo(cookie.getComment()); } + @Test public void testGetDomain() throws Exception { assertThat(savedCookie.getDomain()).isEqualTo(cookie.getDomain()); } + @Test public void testGetMaxAge() throws Exception { assertThat(savedCookie.getMaxAge()).isEqualTo(cookie.getMaxAge()); } + @Test public void testGetPath() throws Exception { assertThat(savedCookie.getPath()).isEqualTo(cookie.getPath()); } + @Test public void testGetVersion() throws Exception { assertThat(savedCookie.getVersion()).isEqualTo(cookie.getVersion()); } + @Test public void testGetCookie() throws Exception { Cookie other = savedCookie.getCookie(); assertThat(other.getComment()).isEqualTo(cookie.getComment()); @@ -64,6 +75,7 @@ public class SavedCookieTests extends TestCase { assertThat(other.getVersion()).isEqualTo(cookie.getVersion()); } + @Test public void testSerializable() throws Exception { assertThat(savedCookie instanceof Serializable).isTrue(); } diff --git a/web/src/test/java/org/springframework/security/web/savedrequest/SavedRequestAwareWrapperTests.java b/web/src/test/java/org/springframework/security/web/savedrequest/SavedRequestAwareWrapperTests.java index 34f5c28384..8b95ba58a8 100644 --- a/web/src/test/java/org/springframework/security/web/savedrequest/SavedRequestAwareWrapperTests.java +++ b/web/src/test/java/org/springframework/security/web/savedrequest/SavedRequestAwareWrapperTests.java @@ -117,8 +117,7 @@ public class SavedRequestAwareWrapperTests { assertThat(wrapper.getParameterValues("action")).isEqualTo(new Object[] { "foo" }); wrappedRequest.setParameter("action", "bar"); - assertArrayEquals(new Object[] { "bar", "foo" }, - wrapper.getParameterValues("action")); + assertThat(wrapper.getParameterValues("action")).isEqualTo(new Object[] { "bar", "foo" }); // Check map is consistent String[] valuesFromMap = (String[]) wrapper.getParameterMap().get("action"); assertThat(valuesFromMap.length).isEqualTo(2); diff --git a/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java b/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java index 13b30784f6..bee50b9f80 100644 --- a/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java @@ -16,8 +16,8 @@ package org.springframework.security.web.servletapi; -import static junit.framework.Assert.fail; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; @@ -37,8 +37,6 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import junit.framework.Assert; - import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -72,18 +70,25 @@ import org.springframework.util.ClassUtils; @RunWith(PowerMockRunner.class) @PrepareForTest(ClassUtils.class) public class SecurityContextHolderAwareRequestFilterTests { + @Captor private ArgumentCaptor requestCaptor; + @Mock private AuthenticationManager authenticationManager; + @Mock private AuthenticationEntryPoint authenticationEntryPoint; + @Mock private LogoutHandler logoutHandler; + @Mock private FilterChain filterChain; + @Mock private HttpServletRequest request; + @Mock private HttpServletResponse response; @@ -174,10 +179,8 @@ public class SecurityContextHolderAwareRequestFilterTests { public void login() throws Exception { TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER"); - when( - authenticationManager - .authenticate(any(UsernamePasswordAuthenticationToken.class))) - .thenReturn(expectedAuth); + when(authenticationManager.authenticate( + any(UsernamePasswordAuthenticationToken.class))).thenReturn(expectedAuth); wrappedRequest().login(expectedAuth.getName(), String.valueOf(expectedAuth.getCredentials())); @@ -193,10 +196,8 @@ public class SecurityContextHolderAwareRequestFilterTests { public void loginWithExstingUser() throws Exception { TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER"); - when( - authenticationManager - .authenticate(any(UsernamePasswordAuthenticationToken.class))) - .thenReturn( + when(authenticationManager.authenticate( + any(UsernamePasswordAuthenticationToken.class))).thenReturn( new TestingAuthenticationToken("newuser", "not be found", "ROLE_USER")); SecurityContextHolder.getContext().setAuthentication(expectedAuth); @@ -217,14 +218,12 @@ public class SecurityContextHolderAwareRequestFilterTests { @Test public void loginFail() throws Exception { AuthenticationException authException = new BadCredentialsException("Invalid"); - when( - authenticationManager - .authenticate(any(UsernamePasswordAuthenticationToken.class))) - .thenThrow(authException); + when(authenticationManager.authenticate( + any(UsernamePasswordAuthenticationToken.class))).thenThrow(authException); try { wrappedRequest().login("invalid", "credentials"); - Assert.fail("Expected Exception"); + fail("Expected Exception"); } catch (ServletException success) { assertThat(success.getCause()).isEqualTo(authException); @@ -262,7 +261,7 @@ public class SecurityContextHolderAwareRequestFilterTests { try { wrappedRequest().login(username, password); - Assert.fail("Expected Exception"); + fail("Expected Exception"); } catch (ServletException success) { assertThat(success).isEqualTo(authException); @@ -309,6 +308,7 @@ public class SecurityContextHolderAwareRequestFilterTests { AsyncContext asyncContext = mock(AsyncContext.class); when(request.getAsyncContext()).thenReturn(asyncContext); Runnable runnable = new Runnable() { + public void run() { } }; @@ -317,12 +317,11 @@ public class SecurityContextHolderAwareRequestFilterTests { verifyZeroInteractions(authenticationManager, logoutHandler); verify(asyncContext).start(runnableCaptor.capture()); - DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor - .getValue(); - assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegateSecurityContext")) - .isEqualTo(context); - assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegate")) - .isEqualTo(runnable); + DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor.getValue(); + assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, + "delegateSecurityContext")).isEqualTo(context); + assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegate")).isEqualTo( + runnable); } @Test @@ -336,6 +335,7 @@ public class SecurityContextHolderAwareRequestFilterTests { AsyncContext asyncContext = mock(AsyncContext.class); when(request.startAsync()).thenReturn(asyncContext); Runnable runnable = new Runnable() { + public void run() { } }; @@ -344,12 +344,11 @@ public class SecurityContextHolderAwareRequestFilterTests { verifyZeroInteractions(authenticationManager, logoutHandler); verify(asyncContext).start(runnableCaptor.capture()); - DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor - .getValue(); - assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegateSecurityContext")) - .isEqualTo(context); - assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegate")) - .isEqualTo(runnable); + DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor.getValue(); + assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, + "delegateSecurityContext")).isEqualTo(context); + assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegate")).isEqualTo( + runnable); } @Test @@ -363,6 +362,7 @@ public class SecurityContextHolderAwareRequestFilterTests { AsyncContext asyncContext = mock(AsyncContext.class); when(request.startAsync(request, response)).thenReturn(asyncContext); Runnable runnable = new Runnable() { + public void run() { } }; @@ -371,22 +371,22 @@ public class SecurityContextHolderAwareRequestFilterTests { verifyZeroInteractions(authenticationManager, logoutHandler); verify(asyncContext).start(runnableCaptor.capture()); - DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor - .getValue(); - assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegateSecurityContext")) - .isEqualTo(context); - assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegate")) - .isEqualTo(runnable); + DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor.getValue(); + assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, + "delegateSecurityContext")).isEqualTo(context); + assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegate")).isEqualTo( + runnable); } // SEC-3047 @Test public void updateRequestFactory() throws Exception { - SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("user", - "password", "PREFIX_USER")); + SecurityContextHolder.getContext().setAuthentication( + new TestingAuthenticationToken("user", "password", "PREFIX_USER")); filter.setRolePrefix("PREFIX_"); - assertThat(wrappedRequest().isUserInRole("PREFIX_USER")).isTrue();; + assertThat(wrappedRequest().isUserInRole("PREFIX_USER")).isTrue(); + ; } private HttpServletRequest wrappedRequest() throws Exception { diff --git a/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestWrapperTests.java b/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestWrapperTests.java index d2f0a77c0c..7293e1839c 100644 --- a/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestWrapperTests.java +++ b/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestWrapperTests.java @@ -15,8 +15,10 @@ package org.springframework.security.web.servletapi; -import junit.framework.TestCase; +import static org.assertj.core.api.Assertions.*; +import org.junit.Before; +import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; @@ -30,12 +32,14 @@ import org.springframework.security.web.servletapi.SecurityContextHolderAwareReq * * @author Ben Alex */ -public class SecurityContextHolderAwareRequestWrapperTests extends TestCase { - - protected void tearDown() throws Exception { +public class SecurityContextHolderAwareRequestWrapperTests { + + @Before + public void tearDown() throws Exception { SecurityContextHolder.clearContext(); } + @Test public void testCorrectOperationWithStringBasedPrincipal() throws Exception { Authentication auth = new TestingAuthenticationToken("rod", "koala", "ROLE_FOO"); SecurityContextHolder.getContext().setAuthentication(auth); @@ -52,6 +56,7 @@ public class SecurityContextHolderAwareRequestWrapperTests extends TestCase { assertThat(wrapper.getUserPrincipal()).isEqualTo(auth); } + @Test public void testUseOfRolePrefixMeansItIsntNeededWhenCallngIsUserInRole() { Authentication auth = new TestingAuthenticationToken("rod", "koala", "ROLE_FOO"); SecurityContextHolder.getContext().setAuthentication(auth); @@ -65,6 +70,7 @@ public class SecurityContextHolderAwareRequestWrapperTests extends TestCase { assertThat(wrapper.isUserInRole("FOO")).isTrue(); } + @Test public void testCorrectOperationWithUserDetailsBasedPrincipal() throws Exception { Authentication auth = new TestingAuthenticationToken(new User("rodAsUserDetails", "koala", true, true, true, true, AuthorityUtils.NO_AUTHORITIES), "koala", @@ -85,6 +91,7 @@ public class SecurityContextHolderAwareRequestWrapperTests extends TestCase { assertThat(wrapper.getUserPrincipal()).isEqualTo(auth); } + @Test public void testRoleIsntHeldIfAuthenticationIsNull() throws Exception { SecurityContextHolder.getContext().setAuthentication(null); @@ -98,6 +105,7 @@ public class SecurityContextHolderAwareRequestWrapperTests extends TestCase { assertThat(wrapper.getUserPrincipal()).isNull(); } + @Test public void testRolesArentHeldIfAuthenticationPrincipalIsNull() throws Exception { Authentication auth = new TestingAuthenticationToken(null, "koala", "ROLE_HELLO", "ROLE_FOOBAR"); @@ -115,6 +123,7 @@ public class SecurityContextHolderAwareRequestWrapperTests extends TestCase { assertThat(wrapper.getUserPrincipal()).isNull(); } + @Test public void testRolePrefix() { Authentication auth = new TestingAuthenticationToken("user", "koala", "ROLE_HELLO", "ROLE_FOOBAR"); @@ -130,6 +139,7 @@ public class SecurityContextHolderAwareRequestWrapperTests extends TestCase { } // SEC-3020 + @Test public void testRolePrefixNotAppliedIfRoleStartsWith() { Authentication auth = new TestingAuthenticationToken("user", "koala", "ROLE_HELLO", "ROLE_FOOBAR"); diff --git a/web/src/test/java/org/springframework/security/web/session/DefaultSessionAuthenticationStrategyTests.java b/web/src/test/java/org/springframework/security/web/session/DefaultSessionAuthenticationStrategyTests.java index 5ca80160c5..d4576d8b89 100644 --- a/web/src/test/java/org/springframework/security/web/session/DefaultSessionAuthenticationStrategyTests.java +++ b/web/src/test/java/org/springframework/security/web/session/DefaultSessionAuthenticationStrategyTests.java @@ -87,8 +87,8 @@ public class DefaultSessionAuthenticationStrategyTests { assertThat(oldSessionId.equals(request.getSession().getId())).isFalse(); assertThat(request.getSession().getAttribute("blah")).isNotNull(); - assertThat(request.getSession().isNotNull().getAttribute( - "SPRING_SECURITY_SAVED_REQUEST_KEY")); + assertThat(request.getSession().getAttribute( + "SPRING_SECURITY_SAVED_REQUEST_KEY")).isNotNull(); assertThat(eventArgumentCaptor.getValue()).isNotNull(); assertThat(eventArgumentCaptor.getValue() instanceof SessionFixationProtectionEvent).isTrue(); @@ -114,8 +114,8 @@ public class DefaultSessionAuthenticationStrategyTests { new MockHttpServletResponse()); assertThat(request.getSession().getAttribute("blah")).isNull(); - assertThat(request.getSession().isNotNull().getAttribute( - "SPRING_SECURITY_SAVED_REQUEST_KEY")); + assertThat(request.getSession().getAttribute( + "SPRING_SECURITY_SAVED_REQUEST_KEY")).isNotNull(); } // SEC-2002 @@ -143,8 +143,8 @@ public class DefaultSessionAuthenticationStrategyTests { verify(eventPublisher).publishEvent(eventArgumentCaptor.capture()); assertThat(request.getSession().getAttribute("blah")).isNull(); - assertThat(request.getSession().isNotNull().getAttribute( - "SPRING_SECURITY_SAVED_REQUEST_KEY")); + assertThat(request.getSession().getAttribute( + "SPRING_SECURITY_SAVED_REQUEST_KEY")).isNotNull(); assertThat(eventArgumentCaptor.getValue()).isNotNull(); assertThat(eventArgumentCaptor.getValue() instanceof SessionFixationProtectionEvent).isTrue(); diff --git a/web/src/test/java/org/springframework/security/web/session/HttpSessionDestroyedEventTests.java b/web/src/test/java/org/springframework/security/web/session/HttpSessionDestroyedEventTests.java index 2ba15998ca..d1828532af 100644 --- a/web/src/test/java/org/springframework/security/web/session/HttpSessionDestroyedEventTests.java +++ b/web/src/test/java/org/springframework/security/web/session/HttpSessionDestroyedEventTests.java @@ -1,7 +1,7 @@ + package org.springframework.security.web.session; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import java.util.List; @@ -18,7 +18,9 @@ import org.springframework.security.core.context.SecurityContextImpl; * */ public class HttpSessionDestroyedEventTests { + private MockHttpSession session; + private HttpSessionDestroyedEvent destroyedEvent; @Before diff --git a/web/src/test/java/org/springframework/security/web/util/TextEscapeUtilsTests.java b/web/src/test/java/org/springframework/security/web/util/TextEscapeUtilsTests.java index 8433c9f157..0e7e11f398 100644 --- a/web/src/test/java/org/springframework/security/web/util/TextEscapeUtilsTests.java +++ b/web/src/test/java/org/springframework/security/web/util/TextEscapeUtilsTests.java @@ -12,8 +12,8 @@ public class TextEscapeUtilsTests { */ @Test public void charactersAreEscapedCorrectly() { - assertEquals("& a<script>"'", - TextEscapeUtils.escapeEntities("& a