1
0
mirror of synced 2026-08-06 02:08:01 +00:00

Convert to assertj

Fixes gh-3175
This commit is contained in:
Billy Korando
2015-12-19 09:29:21 -06:00
committed by Rob Winch
parent bb600a473e
commit 71d4ce96ad
153 changed files with 2472 additions and 2202 deletions
@@ -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
@@ -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<ConfigAttribute> accessAttributes = mds.findAttributes(a.getClass()
.getMethod("noRoleMethod"), null);
Collection<ConfigAttribute> accessAttributes = mds.findAttributes(
a.getClass().getMethod("noRoleMethod"), null);
assertThat(accessAttributes).isNull();
}
@Test
public void classRoleIsAppliedToNoRoleMethod() throws Exception {
Collection<ConfigAttribute> accessAttributes = mds.findAttributes(userAllowed
.getClass().getMethod("noRoleMethod"), null);
Collection<ConfigAttribute> accessAttributes = mds.findAttributes(
userAllowed.getClass().getMethod("noRoleMethod"), null);
assertThat(accessAttributes).isNull();
}
@Test
public void methodRoleOverridesClassRole() throws Exception {
Collection<ConfigAttribute> accessAttributes = mds.findAttributes(userAllowed
.getClass().getMethod("adminMethod"), null);
Collection<ConfigAttribute> 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() {
}
@@ -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<ConfigAttribute> attrs = this.mds
.findAttributes(BusinessService.class);
Collection<ConfigAttribute> 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<ConfigAttribute> attrs = mds
.findAttributes(CustomAnnotatedService.class);
Collection<ConfigAttribute> 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<Department> implements
DepartmentService {
class DepartmentServiceImpl extends BusinessServiceImpl<Department>
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<CustomSecurityAnnotation> {
class CustomSecurityAnnotationMetadataExtractor
implements AnnotationMetadataExtractor<CustomSecurityAnnotation> {
public Collection<? extends ConfigAttribute> 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) {
}
@@ -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<GrantedAuthority> authorities0 = null;
List<GrantedAuthority> authorities1 = new ArrayList<GrantedAuthority>();
@@ -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<GrantedAuthority> authorities0 = AuthorityUtils
.createAuthorityList("ROLE_0");
List<GrantedAuthority> authorities1 = AuthorityUtils
.createAuthorityList("ROLE_A");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_B");
List<GrantedAuthority> authorities0 = AuthorityUtils.createAuthorityList(
"ROLE_0");
List<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList(
"ROLE_A");
List<GrantedAuthority> 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<GrantedAuthority> authorities1 = AuthorityUtils
.createAuthorityList("ROLE_A");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_B", "ROLE_C");
List<GrantedAuthority> authorities3 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_B", "ROLE_C", "ROLE_D");
List<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList(
"ROLE_A");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE_A",
"ROLE_B", "ROLE_C");
List<GrantedAuthority> 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<GrantedAuthority> authoritiesInput1 = AuthorityUtils
.createAuthorityList("ROLE_A");
List<GrantedAuthority> authoritiesInput1 = AuthorityUtils.createAuthorityList(
"ROLE_A");
List<GrantedAuthority> authoritiesOutput1 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_B", "ROLE_C", "ROLE_D");
List<GrantedAuthority> authoritiesInput2 = AuthorityUtils
.createAuthorityList("ROLE_B");
List<GrantedAuthority> authoritiesInput2 = AuthorityUtils.createAuthorityList(
"ROLE_B");
List<GrantedAuthority> authoritiesOutput2 = AuthorityUtils.createAuthorityList(
"ROLE_B", "ROLE_D");
List<GrantedAuthority> authoritiesInput3 = AuthorityUtils
.createAuthorityList("ROLE_C");
List<GrantedAuthority> authoritiesInput3 = AuthorityUtils.createAuthorityList(
"ROLE_C");
List<GrantedAuthority> authoritiesOutput3 = AuthorityUtils.createAuthorityList(
"ROLE_C", "ROLE_D");
List<GrantedAuthority> authoritiesInput4 = AuthorityUtils
.createAuthorityList("ROLE_D");
List<GrantedAuthority> authoritiesOutput4 = AuthorityUtils
.createAuthorityList("ROLE_D");
List<GrantedAuthority> authoritiesInput4 = AuthorityUtils.createAuthorityList(
"ROLE_D");
List<GrantedAuthority> 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<GrantedAuthority> authorities0 = HierarchicalRolesTestHelper
.createAuthorityList("ROLE_0");
List<GrantedAuthority> authorities1 = HierarchicalRolesTestHelper
.createAuthorityList("ROLE_A");
List<GrantedAuthority> authorities2 = HierarchicalRolesTestHelper
.createAuthorityList("ROLE_A", "ROLE_B");
List<GrantedAuthority> authorities0 = HierarchicalRolesTestHelper.createAuthorityList(
"ROLE_0");
List<GrantedAuthority> authorities1 = HierarchicalRolesTestHelper.createAuthorityList(
"ROLE_A");
List<GrantedAuthority> 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();
}
}
@@ -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<ConfigAttribute> attr1 = SecurityConfig
.createList(new String[] { "GIVE_ME_SWAP1" });
List<ConfigAttribute> attr2 = SecurityConfig
.createList(new String[] { "GIVE_ME_SWAP2" });
List<ConfigAttribute> attr3 = SecurityConfig
.createList(new String[] { "GIVE_ME_SWAP3" });
List<ConfigAttribute> attr2and3 = SecurityConfig.createList(new String[] {
"GIVE_ME_SWAP2", "GIVE_ME_SWAP3" });
List<ConfigAttribute> attr4 = SecurityConfig
.createList(new String[] { "NEVER_CAUSES_SWAP" });
List<ConfigAttribute> attr1 = SecurityConfig.createList(
new String[] { "GIVE_ME_SWAP1" });
List<ConfigAttribute> attr2 = SecurityConfig.createList(
new String[] { "GIVE_ME_SWAP2" });
List<ConfigAttribute> attr3 = SecurityConfig.createList(
new String[] { "GIVE_ME_SWAP3" });
List<ConfigAttribute> attr2and3 = SecurityConfig.createList(
new String[] { "GIVE_ME_SWAP2", "GIVE_ME_SWAP3" });
List<ConfigAttribute> 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<ConfigAttribute> config, Object returnedObject)
throws AccessDeniedException {
throws AccessDeniedException {
if (config.contains(configAttribute)) {
return forceReturnObject;
}
@@ -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();
@@ -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<String> authorities = AuthorityUtils.authorityListToSet(result
.getAuthorities());
Set<String> 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<String> authorities = AuthorityUtils.authorityListToSet(result
.getAuthorities());
Set<String> 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();
@@ -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<RunAsUserToken> 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();
}
}
@@ -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<TargetObject> 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<TargetObject> 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();
}
}
@@ -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<AccessDecisionVoter<? extends Object>> decisionVoters) {
super(decisionVoters);
@@ -141,6 +146,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
}
private class MockStringOnlyVoter implements AccessDecisionVoter<Object> {
public boolean supports(Class<?> clazz) {
return String.class.isAssignableFrom(clazz);
}
@@ -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<ConfigAttribute> def = SecurityConfig
.createList(AuthenticatedVoter.IS_AUTHENTICATED_ANONYMOUSLY);
assertEquals(AccessDecisionVoter.ACCESS_GRANTED,
List<ConfigAttribute> 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<ConfigAttribute> def = SecurityConfig
.createList(AuthenticatedVoter.IS_AUTHENTICATED_FULLY);
assertEquals(AccessDecisionVoter.ACCESS_DENIED,
List<ConfigAttribute> 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<ConfigAttribute> def = SecurityConfig
.createList(AuthenticatedVoter.IS_AUTHENTICATED_REMEMBERED);
assertEquals(AccessDecisionVoter.ACCESS_DENIED,
List<ConfigAttribute> 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();
}
}
@@ -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<ConfigAttribute> config = SecurityConfig.createList(new String[] { "ROLE_1",
"DENY_FOR_SURE" });
List<ConfigAttribute> 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<ConfigAttribute> config = SecurityConfig.createList(new String[] {
"FOOBAR_1", "FOOBAR_2" });
List<ConfigAttribute> 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<ConfigAttribute> config = SecurityConfig.createList(new String[] { "ROLE_1",
"ROLE_2" });
List<ConfigAttribute> config = SecurityConfig.createList(
new String[] { "ROLE_1", "ROLE_2" });
mgr.decide(auth, new Object(), config);
}
@@ -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);
}
}
@@ -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();
@@ -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(
@@ -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<GrantedAuthority> ROLES_12 = AuthorityUtils
.createAuthorityList("ROLE_ONE", "ROLE_TWO");
private final static List<GrantedAuthority> 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<GrantedAuthority>) null);
new AnonymousAuthenticationToken("key", "Test",
(List<GrantedAuthority>) 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);
@@ -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<GrantedAuthority> ROLES_12 = AuthorityUtils
.createAuthorityList("ROLE_ONE", "ROLE_TWO");
public class DaoAuthenticationProviderTests {
private static final List<GrantedAuthority> 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<Long> 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);
@@ -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;
@@ -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();
@@ -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;
/**
* <p>
@@ -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 {
}
}
}
@@ -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();
}
}
@@ -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");
}
}
@@ -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;
/**
* <p>
@@ -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();
@@ -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;
/**
* <p>
@@ -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);
@@ -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);
@@ -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"));
@@ -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
@@ -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<? extends GrantedAuthority> list = auth.getAuthorities();
Set<String> 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
@@ -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
@@ -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<Principal>(),
new HashSet<Object>(), new HashSet<Object>());
private UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
"principal", "credentials");
private Subject subject = new Subject(false, new HashSet<Principal>(), new HashSet<Object>(),
new HashSet<Object>());
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();
}
@@ -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.<String, AppConfigurationEntry[]> emptyMap())
.getAppConfigurationEntry("name"));
.getAppConfigurationEntry("name")).isNull();
}
@Test
public void constructorEmptyMapNullDefault() {
assertNull(new InMemoryConfiguration(
assertThat(new InMemoryConfiguration(
Collections.<String, AppConfigurationEntry[]> 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
@@ -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();
@@ -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");
@@ -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<GrantedAuthority> 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);
@@ -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);
@@ -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;
@@ -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();
}
}
@@ -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<String> roles = StringUtils.commaDelimitedListToSet("Role1,Role2");
SimpleMappableAttributesRetriever r = new SimpleMappableAttributesRetriever();
r.setMappableAttributes(roles);
Set<String> 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();
}
}
@@ -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<String> 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() {
@@ -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);
@@ -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");
@@ -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";
@@ -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);
@@ -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);
}
}
@@ -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)
@@ -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);
}
}
@@ -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,
@@ -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<UserDetails> users = new HashSet<UserDetails>();
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();
}
@@ -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());
@@ -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());
@@ -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());
@@ -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();
@@ -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);
@@ -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