Start AssertJ Migration

Issue gh-3175
This commit is contained in:
Rob Winch 2015-12-16 10:38:31 -06:00
parent 6cbb439701
commit bb600a473e
355 changed files with 3036 additions and 3133 deletions

View File

@ -1,9 +1,10 @@
package org.springframework.security.acls;
import static org.assertj.core.api.Assertions.*;
import org.springframework.security.acls.domain.AclFormattingUtils;
import org.springframework.security.acls.model.Permission;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
@ -19,126 +20,116 @@ public class AclFormattingUtilsTests extends TestCase {
public final void testDemergePatternsParametersConstraints() throws Exception {
try {
AclFormattingUtils.demergePatterns(null, "SOME STRING");
Assert.fail("It should have thrown IllegalArgumentException");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", null);
Assert.fail("It should have thrown IllegalArgumentException");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING");
Assert.fail("It should have thrown IllegalArgumentException");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH");
Assert.assertTrue(true);
}
catch (IllegalArgumentException notExpected) {
Assert.fail("It shouldn't have thrown IllegalArgumentException");
fail("It shouldn't have thrown IllegalArgumentException");
}
}
public final void testDemergePatterns() throws Exception {
String original = "...........................A...R";
String removeBits = "...............................R";
Assert.assertEquals("...........................A....",
AclFormattingUtils.demergePatterns(original, removeBits));
assertThat(AclFormattingUtils.demergePatterns(original, removeBits)).isEqualTo("...........................A....");
Assert.assertEquals("ABCDEF",
AclFormattingUtils.demergePatterns("ABCDEF", "......"));
Assert.assertEquals("......",
AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL"));
assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "......")).isEqualTo("ABCDEF");
assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL")).isEqualTo("......");
}
public final void testMergePatternsParametersConstraints() throws Exception {
try {
AclFormattingUtils.mergePatterns(null, "SOME STRING");
Assert.fail("It should have thrown IllegalArgumentException");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", null);
Assert.fail("It should have thrown IllegalArgumentException");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING");
Assert.fail("It should have thrown IllegalArgumentException");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH");
Assert.assertTrue(true);
}
catch (IllegalArgumentException notExpected) {
Assert.fail("It shouldn't have thrown IllegalArgumentException");
}
}
public final void testMergePatterns() throws Exception {
String original = "...............................R";
String extraBits = "...........................A....";
Assert.assertEquals("...........................A...R",
AclFormattingUtils.mergePatterns(original, extraBits));
assertThat(
AclFormattingUtils.mergePatterns(original, extraBits)).isEqualTo("...........................A...R");
Assert.assertEquals("ABCDEF",
AclFormattingUtils.mergePatterns("ABCDEF", "......"));
Assert.assertEquals("GHIJKL",
AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL"));
assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "......"))
.isEqualTo("ABCDEF");
assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL"))
.isEqualTo("GHIJKL");
}
public final void testBinaryPrints() throws Exception {
Assert.assertEquals("............................****",
AclFormattingUtils.printBinary(15));
assertThat(
AclFormattingUtils.printBinary(15))
.isEqualTo("............................****");
try {
AclFormattingUtils.printBinary(15, Permission.RESERVED_ON);
Assert.fail("It should have thrown IllegalArgumentException");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException notExpected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF);
Assert.fail("It should have thrown IllegalArgumentException");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException notExpected) {
Assert.assertTrue(true);
}
Assert.assertEquals("............................xxxx",
AclFormattingUtils.printBinary(15, 'x'));
assertThat(
AclFormattingUtils.printBinary(15, 'x'))
.isEqualTo("............................xxxx");
}
public void testPrintBinaryNegative() {
Assert.assertEquals("*...............................",
AclFormattingUtils.printBinary(0x80000000));
assertThat(
AclFormattingUtils.printBinary(0x80000000))
.isEqualTo("*...............................");
}
public void testPrintBinaryMinusOne() {
Assert.assertEquals("********************************",
AclFormattingUtils.printBinary(0xffffffff));
assertThat(
AclFormattingUtils.printBinary(0xffffffff))
.isEqualTo("********************************");
}
}

View File

@ -1,6 +1,7 @@
package org.springframework.security.acls;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
@ -36,7 +37,7 @@ public class AclPermissionEvaluatorTests {
when(service.readAclById(any(ObjectIdentity.class), anyList())).thenReturn(acl);
when(acl.isGranted(anyList(), anyList(), eq(false))).thenReturn(true);
assertTrue(pe.hasPermission(mock(Authentication.class), new Object(), "READ"));
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "READ")).isTrue();
}
@Test
@ -56,7 +57,7 @@ public class AclPermissionEvaluatorTests {
when(service.readAclById(any(ObjectIdentity.class), anyList())).thenReturn(acl);
when(acl.isGranted(anyList(), anyList(), eq(false))).thenReturn(true);
assertTrue(pe.hasPermission(mock(Authentication.class), new Object(), "write"));
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "write")).isTrue();
Locale.setDefault(systemLocale);
}

View File

@ -1,8 +1,8 @@
package org.springframework.security.acls.afterinvocation;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Mockito.*;
@ -42,13 +42,13 @@ public class AclEntryAfterInvocationCollectionFilteringProviderTests {
Object returned = provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), new ArrayList(
Arrays.asList(new Object(), new Object())));
assertTrue(returned instanceof List);
assertTrue(((List) returned).isEmpty());
assertThat(returned).isInstanceOf(List.class);
assertThat(((List) returned)).isEmpty();
returned = provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("UNSUPPORTED", "AFTER_ACL_COLLECTION_READ"),
new Object[] { new Object(), new Object() });
assertTrue(returned instanceof Object[]);
assertTrue(((Object[]) returned).length == 0);
assertThat(returned instanceof Object[]).isTrue();
assertThat(((Object[]) returned).length == 0).isTrue();
}
@Test
@ -57,8 +57,8 @@ public class AclEntryAfterInvocationCollectionFilteringProviderTests {
mock(AclService.class), Arrays.asList(mock(Permission.class)));
Object returned = new Object();
assertSame(
returned,
assertThat(returned)
.isSameAs(
provider.decide(mock(Authentication.class), new Object(),
Collections.<ConfigAttribute> emptyList(), returned));
}
@ -69,8 +69,9 @@ public class AclEntryAfterInvocationCollectionFilteringProviderTests {
AclEntryAfterInvocationCollectionFilteringProvider provider = new AclEntryAfterInvocationCollectionFilteringProvider(
service, Arrays.asList(mock(Permission.class)));
assertNull(provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), null));
assertThat(provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), null))
.isNull();;
verify(service, never()).readAclById(any(ObjectIdentity.class), any(List.class));
}

View File

@ -1,6 +1,6 @@
package org.springframework.security.acls.afterinvocation;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
@ -50,8 +50,9 @@ public class AclEntryAfterInvocationProviderTests {
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Object returned = new Object();
assertSame(
returned,
assertThat(
returned)
.isSameAs(
provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("AFTER_ACL_READ"), returned));
}
@ -62,8 +63,9 @@ public class AclEntryAfterInvocationProviderTests {
mock(AclService.class), Arrays.asList(mock(Permission.class)));
Object returned = new Object();
assertSame(
returned,
assertThat(
returned)
.isSameAs(
provider.decide(mock(Authentication.class), new Object(),
Collections.<ConfigAttribute> emptyList(), returned));
}
@ -76,8 +78,9 @@ public class AclEntryAfterInvocationProviderTests {
// Not a String
Object returned = new Object();
assertSame(
returned,
assertThat(
returned)
.isSameAs(
provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("AFTER_ACL_READ"), returned));
}
@ -104,7 +107,7 @@ public class AclEntryAfterInvocationProviderTests {
provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"),
new Object());
fail();
fail("Expected Exception");
}
catch (AccessDeniedException expected) {
}
@ -119,8 +122,9 @@ public class AclEntryAfterInvocationProviderTests {
AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(
service, Arrays.asList(mock(Permission.class)));
assertNull(provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), null));
assertThat(provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), null))
.isNull();;
verify(service, never()).readAclById(any(ObjectIdentity.class), any(List.class));
}
}

View File

@ -1,6 +1,6 @@
package org.springframework.security.acls.domain;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
@ -60,13 +60,13 @@ public class AccessControlImplEntryTests {
sid, BasePermission.ADMINISTRATION, true, true, true);
// and check every get() method
assertEquals(new Long(1), ace.getId());
assertEquals(mockAcl, ace.getAcl());
assertEquals(sid, ace.getSid());
assertTrue(ace.isGranting());
assertEquals(BasePermission.ADMINISTRATION, ace.getPermission());
assertTrue(((AuditableAccessControlEntry) ace).isAuditFailure());
assertTrue(((AuditableAccessControlEntry) ace).isAuditSuccess());
assertThat(ace.getId()).isEqualTo(new Long(1));
assertThat(ace.getAcl()).isEqualTo(mockAcl);
assertThat(ace.getSid()).isEqualTo(sid);
assertThat(ace.isGranting()).isTrue();
assertThat(ace.getPermission()).isEqualTo(BasePermission.ADMINISTRATION);
assertThat(((AuditableAccessControlEntry) ace).isAuditFailure()).isTrue();
assertThat(((AuditableAccessControlEntry) ace).isAuditSuccess()).isTrue();
}
@Test
@ -80,23 +80,23 @@ public class AccessControlImplEntryTests {
AccessControlEntry ace = new AccessControlEntryImpl(Long.valueOf(1), mockAcl,
sid, BasePermission.ADMINISTRATION, true, true, true);
assertFalse(ace.equals(null));
assertFalse(ace.equals(Long.valueOf(100)));
assertTrue(ace.equals(ace));
assertTrue(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
BasePermission.ADMINISTRATION, true, true, true)));
assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(2), mockAcl, sid,
BasePermission.ADMINISTRATION, true, true, true)));
assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl,
assertThat(ace).isNotNull();
assertThat(ace).isNotEqualTo(Long.valueOf(100));
assertThat(ace).isEqualTo(ace);
assertThat(ace).isEqualTo(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
BasePermission.ADMINISTRATION, true, true, true));
assertThat(ace).isNotEqualTo(new AccessControlEntryImpl(Long.valueOf(2), mockAcl, sid,
BasePermission.ADMINISTRATION, true, true, true));
assertThat(ace).isNotEqualTo(new AccessControlEntryImpl(Long.valueOf(1), mockAcl,
new PrincipalSid("scott"), BasePermission.ADMINISTRATION, true, true,
true)));
assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
BasePermission.WRITE, true, true, true)));
assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
BasePermission.ADMINISTRATION, false, true, true)));
assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
BasePermission.ADMINISTRATION, true, false, true)));
assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
BasePermission.ADMINISTRATION, true, true, false)));
true));
assertThat(ace).isNotEqualTo(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
BasePermission.WRITE, true, true, true));
assertThat(ace).isNotEqualTo(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
BasePermission.ADMINISTRATION, false, true, true));
assertThat(ace).isNotEqualTo(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
BasePermission.ADMINISTRATION, true, false, true));
assertThat(ace).isNotEqualTo(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
BasePermission.ADMINISTRATION, true, true, false));
}
}

View File

@ -1,6 +1,6 @@
package org.springframework.security.acls.domain;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.*;
@ -117,36 +117,36 @@ public class AclImplTests {
acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST1"), true);
service.updateAcl(acl);
// Check it was successfully added
assertEquals(1, acl.getEntries().size());
assertEquals(acl.getEntries().get(0).getAcl(), acl);
assertEquals(acl.getEntries().get(0).getPermission(), BasePermission.READ);
assertEquals(acl.getEntries().get(0).getSid(), new GrantedAuthoritySid(
assertThat(acl.getEntries()).hasSize(1);
assertThat(acl).isEqualTo(acl.getEntries().get(0).getAcl());
assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(0).getPermission());
assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid(
"ROLE_TEST1"));
// Add a second permission
acl.insertAce(1, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true);
service.updateAcl(acl);
// Check it was added on the last position
assertEquals(2, acl.getEntries().size());
assertEquals(acl.getEntries().get(1).getAcl(), acl);
assertEquals(acl.getEntries().get(1).getPermission(), BasePermission.READ);
assertEquals(acl.getEntries().get(1).getSid(), new GrantedAuthoritySid(
assertThat(acl.getEntries()).hasSize(2);
assertThat(acl).isEqualTo(acl.getEntries().get(1).getAcl());
assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(1).getPermission());
assertThat(acl.getEntries().get(1).getSid()).isEqualTo(new GrantedAuthoritySid(
"ROLE_TEST2"));
// Add a third permission, after the first one
acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_TEST3"),
false);
service.updateAcl(acl);
assertEquals(3, acl.getEntries().size());
assertThat(acl.getEntries()).hasSize(3);
// Check the third entry was added between the two existent ones
assertEquals(acl.getEntries().get(0).getPermission(), BasePermission.READ);
assertEquals(acl.getEntries().get(0).getSid(), new GrantedAuthoritySid(
assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(0).getPermission());
assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid(
"ROLE_TEST1"));
assertEquals(acl.getEntries().get(1).getPermission(), BasePermission.WRITE);
assertEquals(acl.getEntries().get(1).getSid(), new GrantedAuthoritySid(
assertThat(BasePermission.WRITE).isEqualTo(acl.getEntries().get(1).getPermission());
assertThat(acl.getEntries().get(1).getSid()).isEqualTo( new GrantedAuthoritySid(
"ROLE_TEST3"));
assertEquals(acl.getEntries().get(2).getPermission(), BasePermission.READ);
assertEquals(acl.getEntries().get(2).getSid(), new GrantedAuthoritySid(
assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(2).getPermission());
assertThat(acl.getEntries().get(2).getSid()).isEqualTo(new GrantedAuthoritySid(
"ROLE_TEST2"));
}
@ -179,26 +179,26 @@ public class AclImplTests {
// Delete first permission and check the order of the remaining permissions is
// kept
acl.deleteAce(0);
assertEquals(2, acl.getEntries().size());
assertEquals(acl.getEntries().get(0).getSid(), new GrantedAuthoritySid(
assertThat(acl.getEntries()).hasSize(2);
assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid(
"ROLE_TEST2"));
assertEquals(acl.getEntries().get(1).getSid(), new GrantedAuthoritySid(
assertThat(acl.getEntries().get(1).getSid()).isEqualTo(new GrantedAuthoritySid(
"ROLE_TEST3"));
// Add one more permission and remove the permission in the middle
acl.insertAce(2, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST4"), true);
service.updateAcl(acl);
acl.deleteAce(1);
assertEquals(2, acl.getEntries().size());
assertEquals(acl.getEntries().get(0).getSid(), new GrantedAuthoritySid(
assertThat(acl.getEntries()).hasSize(2);
assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid(
"ROLE_TEST2"));
assertEquals(acl.getEntries().get(1).getSid(), new GrantedAuthoritySid(
assertThat(acl.getEntries().get(1).getSid()).isEqualTo(new GrantedAuthoritySid(
"ROLE_TEST4"));
// Remove remaining permissions
acl.deleteAce(1);
acl.deleteAce(0);
assertEquals(0, acl.getEntries().size());
assertThat(acl.getEntries()).isEmpty();
}
@Test
@ -259,18 +259,18 @@ public class AclImplTests {
BasePermission.CREATE);
List<Sid> sids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid(
"ROLE_GUEST"));
assertFalse(rootAcl.isGranted(permissions, sids, false));
assertThat(rootAcl.isGranted(permissions, sids, false)).isFalse();
try {
rootAcl.isGranted(permissions, SCOTT, false);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
assertTrue(rootAcl.isGranted(WRITE, SCOTT, false));
assertFalse(rootAcl.isGranted(WRITE, Arrays.asList(new PrincipalSid("rod"),
new GrantedAuthoritySid("WRITE_ACCESS_ROLE")), false));
assertTrue(rootAcl.isGranted(WRITE, Arrays.asList(new GrantedAuthoritySid(
"WRITE_ACCESS_ROLE"), new PrincipalSid("rod")), false));
assertThat(rootAcl.isGranted(WRITE, SCOTT, false)).isTrue();
assertThat(rootAcl.isGranted(WRITE, Arrays.asList(new PrincipalSid("rod"),
new GrantedAuthoritySid("WRITE_ACCESS_ROLE")), false)).isFalse();
assertThat(rootAcl.isGranted(WRITE, Arrays.asList(new GrantedAuthoritySid(
"WRITE_ACCESS_ROLE"), new PrincipalSid("rod")), false)).isTrue();
try {
// Change the type of the Sid and check the granting process
rootAcl.isGranted(WRITE, Arrays.asList(new GrantedAuthoritySid("rod"),
@ -326,40 +326,40 @@ public class AclImplTests {
childAcl1.insertAce(0, BasePermission.CREATE, new PrincipalSid("scott"), true);
// Check granting process for parent1
assertTrue(parentAcl1.isGranted(READ, SCOTT, false));
assertTrue(parentAcl1.isGranted(READ,
Arrays.asList((Sid) new GrantedAuthoritySid("ROLE_USER_READ")), false));
assertTrue(parentAcl1.isGranted(WRITE, BEN, false));
assertFalse(parentAcl1.isGranted(DELETE, BEN, false));
assertFalse(parentAcl1.isGranted(DELETE, SCOTT, false));
assertThat(parentAcl1.isGranted(READ, SCOTT, false)).isTrue();
assertThat(parentAcl1.isGranted(READ,
Arrays.asList((Sid) new GrantedAuthoritySid("ROLE_USER_READ")), false))
.isTrue();
assertThat(parentAcl1.isGranted(WRITE, BEN, false)).isTrue();
assertThat(parentAcl1.isGranted(DELETE, BEN, false)).isFalse();
assertThat(parentAcl1.isGranted(DELETE, SCOTT, false)).isFalse();
// Check granting process for parent2
assertTrue(parentAcl2.isGranted(CREATE, BEN, false));
assertTrue(parentAcl2.isGranted(WRITE, BEN, false));
assertFalse(parentAcl2.isGranted(DELETE, BEN, false));
assertThat(parentAcl2.isGranted(CREATE, BEN, false)).isTrue();
assertThat(parentAcl2.isGranted(WRITE, BEN, false)).isTrue();
assertThat(parentAcl2.isGranted(DELETE, BEN, false)).isFalse();
// Check granting process for child1
assertTrue(childAcl1.isGranted(CREATE, SCOTT, false));
assertTrue(childAcl1.isGranted(READ,
Arrays.asList((Sid) new GrantedAuthoritySid("ROLE_USER_READ")), false));
assertFalse(childAcl1.isGranted(DELETE, BEN, false));
assertThat(childAcl1.isGranted(CREATE, SCOTT, false)).isTrue();
assertThat(childAcl1.isGranted(READ,
Arrays.asList((Sid) new GrantedAuthoritySid("ROLE_USER_READ")), false))
.isTrue();
assertThat(childAcl1.isGranted(DELETE, BEN, false)).isFalse();
// Check granting process for child2 (doesn't inherit the permissions from its
// parent)
try {
assertTrue(childAcl2.isGranted(CREATE, SCOTT, false));
assertThat(childAcl2.isGranted(CREATE, SCOTT, false)).isTrue();
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
assertTrue(true);
}
try {
assertTrue(childAcl2.isGranted(CREATE,
Arrays.asList((Sid) new PrincipalSid("joe")), false));
childAcl2.isGranted(CREATE,
Arrays.asList((Sid) new PrincipalSid("joe")), false);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
assertTrue(true);
}
}
@ -380,9 +380,9 @@ public class AclImplTests {
acl.insertAce(2, BasePermission.CREATE, new PrincipalSid("ben"), true);
service.updateAcl(acl);
assertEquals(acl.getEntries().get(0).getPermission(), BasePermission.READ);
assertEquals(acl.getEntries().get(1).getPermission(), BasePermission.WRITE);
assertEquals(acl.getEntries().get(2).getPermission(), BasePermission.CREATE);
assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(0).getPermission());
assertThat(BasePermission.WRITE).isEqualTo(acl.getEntries().get(1).getPermission());
assertThat(BasePermission.CREATE).isEqualTo(acl.getEntries().get(2).getPermission());
// Change each permission
acl.updateAce(0, BasePermission.CREATE);
@ -390,9 +390,9 @@ public class AclImplTests {
acl.updateAce(2, BasePermission.READ);
// Check the change was successfully made
assertEquals(acl.getEntries().get(0).getPermission(), BasePermission.CREATE);
assertEquals(acl.getEntries().get(1).getPermission(), BasePermission.DELETE);
assertEquals(acl.getEntries().get(2).getPermission(), BasePermission.READ);
assertThat(BasePermission.CREATE).isEqualTo(acl.getEntries().get(0).getPermission());
assertThat(BasePermission.DELETE).isEqualTo(acl.getEntries().get(1).getPermission());
assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(2).getPermission());
}
@Test
@ -411,28 +411,26 @@ public class AclImplTests {
true);
service.updateAcl(acl);
assertFalse(((AuditableAccessControlEntry) acl.getEntries().get(0))
.isAuditFailure());
assertFalse(((AuditableAccessControlEntry) acl.getEntries().get(1))
.isAuditFailure());
assertFalse(((AuditableAccessControlEntry) acl.getEntries().get(0))
.isAuditSuccess());
assertFalse(((AuditableAccessControlEntry) acl.getEntries().get(1))
.isAuditSuccess());
assertThat(((AuditableAccessControlEntry) acl.getEntries().get(0))
.isAuditFailure())
.isFalse();
assertThat(((AuditableAccessControlEntry) acl.getEntries().get(1))
.isAuditFailure())
.isFalse();
assertThat(((AuditableAccessControlEntry) acl.getEntries().get(0))
.isAuditSuccess())
.isFalse();
assertThat(((AuditableAccessControlEntry) acl.getEntries().get(1))
.isAuditSuccess())
.isFalse();
// Change each permission
((AuditableAcl) acl).updateAuditing(0, true, true);
((AuditableAcl) acl).updateAuditing(1, true, true);
// Check the change was successfuly made
assertTrue(((AuditableAccessControlEntry) acl.getEntries().get(0))
.isAuditFailure());
assertTrue(((AuditableAccessControlEntry) acl.getEntries().get(1))
.isAuditFailure());
assertTrue(((AuditableAccessControlEntry) acl.getEntries().get(0))
.isAuditSuccess());
assertTrue(((AuditableAccessControlEntry) acl.getEntries().get(1))
.isAuditSuccess());
assertThat(acl.getEntries()).extracting("auditSuccess").containsOnly(true, true);
assertThat(acl.getEntries()).extracting("auditFailure").containsOnly(true, true);
}
@Test
@ -454,21 +452,21 @@ public class AclImplTests {
true);
service.updateAcl(acl);
assertEquals(acl.getId(), 1);
assertEquals(acl.getObjectIdentity(), identity);
assertEquals(acl.getOwner(), new PrincipalSid("joe"));
assertNull(acl.getParentAcl());
assertTrue(acl.isEntriesInheriting());
assertEquals(2, acl.getEntries().size());
assertThat(1).isEqualTo(acl.getId());
assertThat(identity).isEqualTo(acl.getObjectIdentity());
assertThat(new PrincipalSid("joe")).isEqualTo(acl.getOwner());
assertThat(acl.getParentAcl()).isNull();
assertThat(acl.isEntriesInheriting()).isTrue();
assertThat(acl.getEntries()).hasSize(2);
acl.setParent(parentAcl);
assertEquals(acl.getParentAcl(), parentAcl);
assertThat(parentAcl).isEqualTo(acl.getParentAcl());
acl.setEntriesInheriting(false);
assertFalse(acl.isEntriesInheriting());
assertThat(acl.isEntriesInheriting()).isFalse();
acl.setOwner(new PrincipalSid("ben"));
assertEquals(acl.getOwner(), new PrincipalSid("ben"));
assertThat(new PrincipalSid("ben")).isEqualTo(acl.getOwner());
}
@Test
@ -478,20 +476,25 @@ public class AclImplTests {
MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null,
loadedSids, true, new PrincipalSid("joe"));
assertTrue(acl.isSidLoaded(loadedSids));
assertTrue(acl.isSidLoaded(Arrays.asList(new GrantedAuthoritySid("ROLE_IGNORED"),
new PrincipalSid("ben"))));
assertTrue(acl.isSidLoaded(Arrays.asList((Sid) new GrantedAuthoritySid(
"ROLE_IGNORED"))));
assertTrue(acl.isSidLoaded(BEN));
assertTrue(acl.isSidLoaded(null));
assertTrue(acl.isSidLoaded(new ArrayList<Sid>(0)));
assertTrue(acl.isSidLoaded(Arrays.asList((Sid) new GrantedAuthoritySid(
"ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_IGNORED"))));
assertFalse(acl.isSidLoaded(Arrays.asList((Sid) new GrantedAuthoritySid(
"ROLE_GENERAL"), new GrantedAuthoritySid("ROLE_IGNORED"))));
assertFalse(acl.isSidLoaded(Arrays.asList((Sid) new GrantedAuthoritySid(
"ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_GENERAL"))));
assertThat(acl.isSidLoaded(loadedSids)).isTrue();
assertThat(acl.isSidLoaded(Arrays.asList(new GrantedAuthoritySid("ROLE_IGNORED"),
new PrincipalSid("ben"))))
.isTrue();
assertThat(acl.isSidLoaded(Arrays.asList((Sid)new GrantedAuthoritySid(
"ROLE_IGNORED"))))
.isTrue();
assertThat(acl.isSidLoaded(BEN)).isTrue();
assertThat(acl.isSidLoaded(null)).isTrue();
assertThat(acl.isSidLoaded(new ArrayList<Sid>(0))).isTrue();
assertThat(acl.isSidLoaded(Arrays.asList((Sid) new GrantedAuthoritySid(
"ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_IGNORED"))))
.isTrue();
assertThat(acl.isSidLoaded(Arrays.asList((Sid) new GrantedAuthoritySid(
"ROLE_GENERAL"), new GrantedAuthoritySid("ROLE_IGNORED"))))
.isFalse();
assertThat(acl.isSidLoaded(Arrays.asList((Sid)new GrantedAuthoritySid(
"ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_GENERAL"))))
.isFalse();
}
@Test(expected = NotFoundException.class)
@ -558,7 +561,7 @@ public class AclImplTests {
/*
* Mock implementation that populates the aces list with fully initialized
* AccessControlEntries
*
*
* @see
* org.springframework.security.acls.MutableAclService#updateAcl(org.springframework
* .security.acls.MutableAcl)

View File

@ -1,6 +1,6 @@
package org.springframework.security.acls.domain;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.*;
import org.springframework.security.access.AccessDeniedException;
@ -162,7 +162,7 @@ public class AclImplementationSecurityCheckTests {
try {
aclAuthorizationStrategy.securityCheck(aclFirstAllow,
AclAuthorizationStrategy.CHANGE_AUDITING);
assertTrue(true);
}
catch (AccessDeniedException notExpected) {
fail("It shouldn't have thrown AccessDeniedException");
@ -177,13 +177,13 @@ public class AclImplementationSecurityCheckTests {
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
assertTrue(true);
}
// and still grant access for CHANGE_GENERAL
try {
aclAuthorizationStrategy.securityCheck(aclNoACE,
AclAuthorizationStrategy.CHANGE_GENERAL);
assertTrue(true);
}
catch (NotFoundException expected) {
fail("It shouldn't have thrown NotFoundException");
@ -221,7 +221,7 @@ public class AclImplementationSecurityCheckTests {
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
assertTrue(true);
}
// Link the child with its parent and test again against the
@ -231,7 +231,7 @@ public class AclImplementationSecurityCheckTests {
try {
aclAuthorizationStrategy.securityCheck(childAcl,
AclAuthorizationStrategy.CHANGE_OWNERSHIP);
assertTrue(true);
}
catch (NotFoundException expected) {
fail("It shouldn't have thrown NotFoundException");
@ -250,7 +250,7 @@ public class AclImplementationSecurityCheckTests {
try {
aclAuthorizationStrategy.securityCheck(childAcl,
AclAuthorizationStrategy.CHANGE_OWNERSHIP);
assertTrue(true);
}
catch (NotFoundException expected) {
fail("It shouldn't have thrown NotFoundException");

View File

@ -1,6 +1,6 @@
package org.springframework.security.acls.domain;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.io.ByteArrayOutputStream;
@ -46,14 +46,14 @@ public class AuditLoggerTests {
public void nonAuditableAceIsIgnored() {
AccessControlEntry ace = mock(AccessControlEntry.class);
logger.logIfNeeded(true, ace);
assertEquals(0, bytes.size());
assertThat(bytes.size()).isEqualTo(0);
}
@Test
public void successIsNotLoggedIfAceDoesntRequireSuccessAudit() throws Exception {
when(ace.isAuditSuccess()).thenReturn(false);
logger.logIfNeeded(true, ace);
assertEquals(0, bytes.size());
assertThat(bytes.size()).isEqualTo(0);
}
@Test
@ -61,20 +61,20 @@ public class AuditLoggerTests {
when(ace.isAuditSuccess()).thenReturn(true);
logger.logIfNeeded(true, ace);
assertTrue(bytes.toString().startsWith("GRANTED due to ACE"));
assertThat(bytes.toString().startsWith("GRANTED due to ACE")).isTrue();
}
@Test
public void failureIsntLoggedIfAceDoesntRequireFailureAudit() throws Exception {
when(ace.isAuditFailure()).thenReturn(false);
logger.logIfNeeded(false, ace);
assertEquals(0, bytes.size());
assertThat(bytes.size()).isEqualTo(0);
}
@Test
public void failureIsLoggedIfAceRequiresFailureAudit() throws Exception {
when(ace.isAuditFailure()).thenReturn(true);
logger.logIfNeeded(false, ace);
assertTrue(bytes.toString().startsWith("DENIED due to ACE"));
assertThat(bytes.toString().startsWith("DENIED due to ACE")).isTrue();
}
}

View File

@ -1,6 +1,6 @@
package org.springframework.security.acls.domain;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.security.acls.domain.IdentityUnavailableException;
@ -66,8 +66,8 @@ public class ObjectIdentityImplTests {
@Test
public void gettersReturnExpectedValues() throws Exception {
ObjectIdentity obj = new ObjectIdentityImpl(DOMAIN_CLASS, Long.valueOf(1));
assertEquals(Long.valueOf(1), obj.getIdentifier());
assertEquals(MockIdDomainObject.class.getName(), obj.getType());
assertThat(obj.getIdentifier()).isEqualTo(Long.valueOf(1));
assertThat(obj.getType()).isEqualTo(MockIdDomainObject.class.getName());
}
@Test
@ -121,23 +121,22 @@ public class ObjectIdentityImplTests {
mockObj.setId(Long.valueOf(1));
String string = "SOME_STRING";
assertNotSame(obj, string);
assertFalse(obj.equals(null));
assertFalse(obj.equals("DIFFERENT_OBJECT_TYPE"));
assertFalse(obj.equals(new ObjectIdentityImpl(DOMAIN_CLASS, Long.valueOf(2))));
assertFalse(obj
.equals(new ObjectIdentityImpl(
assertThat(string).isNotSameAs(obj);
assertThat(obj.equals(null)).isFalse();
assertThat(obj.equals("DIFFERENT_OBJECT_TYPE")).isFalse();
assertThat(obj.equals(new ObjectIdentityImpl(DOMAIN_CLASS, Long.valueOf(2)))).isFalse();
assertThat(obj).isNotEqualTo(new ObjectIdentityImpl(
"org.springframework.security.acls.domain.ObjectIdentityImplTests$MockOtherIdDomainObject",
Long.valueOf(1))));
assertEquals(new ObjectIdentityImpl(DOMAIN_CLASS, Long.valueOf(1)), obj);
assertEquals(obj, new ObjectIdentityImpl(mockObj));
Long.valueOf(1)));
assertThat(new ObjectIdentityImpl(DOMAIN_CLASS, 1L)).isEqualTo(obj);
assertThat(new ObjectIdentityImpl(mockObj)).isEqualTo(obj);
}
@Test
public void hashcodeIsDifferentForDifferentJavaTypes() throws Exception {
ObjectIdentity obj = new ObjectIdentityImpl(Object.class, Long.valueOf(1));
ObjectIdentity obj2 = new ObjectIdentityImpl(String.class, Long.valueOf(1));
assertFalse(obj.hashCode() == obj2.hashCode());
assertThat(obj.hashCode() == obj2.hashCode()).isFalse();
}
@Test
@ -145,23 +144,23 @@ public class ObjectIdentityImplTests {
ObjectIdentity obj = new ObjectIdentityImpl(Object.class, new Long(5));
ObjectIdentity obj2 = new ObjectIdentityImpl(Object.class, Integer.valueOf(5));
assertEquals(obj, obj2);
assertEquals(obj.hashCode(), obj2.hashCode());
assertThat(obj2).isEqualTo(obj);
assertThat(obj2.hashCode()).isEqualTo(obj.hashCode());
}
@Test
public void equalStringIdsAreEqualAndHaveSameHashcode() throws Exception {
ObjectIdentity obj = new ObjectIdentityImpl(Object.class, "1000");
ObjectIdentity obj2 = new ObjectIdentityImpl(Object.class, "1000");
assertEquals(obj, obj2);
assertEquals(obj.hashCode(), obj2.hashCode());
assertThat(obj2).isEqualTo(obj);
assertThat(obj2.hashCode()).isEqualTo(obj.hashCode());
}
@Test
public void stringAndNumericIdsAreNotEqual() throws Exception {
ObjectIdentity obj = new ObjectIdentityImpl(Object.class, "1000");
ObjectIdentity obj2 = new ObjectIdentityImpl(Object.class, Long.valueOf(1000));
assertFalse(obj.equals(obj2));
assertThat(obj.equals(obj2)).isFalse();
}
// ~ Inner Classes

View File

@ -1,5 +1,8 @@
package org.springframework.security.acls.domain;
import static org.assertj.core.api.Assertions.*;
import org.springframework.security.acls.domain.ObjectIdentityImpl;
import org.springframework.security.acls.domain.ObjectIdentityRetrievalStrategyImpl;
import org.springframework.security.acls.model.ObjectIdentity;
@ -23,8 +26,8 @@ public class ObjectIdentityRetrievalStrategyImplTests extends TestCase {
ObjectIdentityRetrievalStrategy retStrategy = new ObjectIdentityRetrievalStrategyImpl();
ObjectIdentity identity = retStrategy.getObjectIdentity(domain);
assertNotNull(identity);
assertEquals(identity, new ObjectIdentityImpl(domain));
assertThat(identity).isNotNull();
assertThat(new ObjectIdentityImpl(domain)).isEqualTo(identity);
}
// ~ Inner Classes

View File

@ -14,7 +14,7 @@
*/
package org.springframework.security.acls.domain;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Before;
import org.junit.Test;
@ -37,82 +37,60 @@ public class PermissionTests {
@Test
public void basePermissionTest() {
Permission p = permissionFactory.buildFromName("WRITE");
assertNotNull(p);
assertThat(p).isNotNull();
}
@Test
public void expectedIntegerValues() {
assertEquals(1, BasePermission.READ.getMask());
assertEquals(16, BasePermission.ADMINISTRATION.getMask());
assertEquals(
7,
assertThat(BasePermission.READ.getMask()).isEqualTo(1);
assertThat(BasePermission.ADMINISTRATION.getMask()).isEqualTo(16);
assertThat(
new CumulativePermission().set(BasePermission.READ)
.set(BasePermission.WRITE).set(BasePermission.CREATE).getMask());
assertEquals(
17,
.set(BasePermission.WRITE).set(BasePermission.CREATE).getMask())
.isEqualTo(7);
assertThat(
new CumulativePermission().set(BasePermission.READ)
.set(BasePermission.ADMINISTRATION).getMask());
.set(BasePermission.ADMINISTRATION).getMask())
.isEqualTo(17);
}
@Test
public void fromInteger() {
Permission permission = permissionFactory.buildFromMask(7);
System.out.println("7 = " + permission.toString());
permission = permissionFactory.buildFromMask(4);
System.out.println("4 = " + permission.toString());
}
@Test
public void stringConversion() {
permissionFactory.registerPublicPermissions(SpecialPermission.class);
System.out.println("R = " + BasePermission.READ.toString());
assertEquals("BasePermission[...............................R=1]",
BasePermission.READ.toString());
assertThat(BasePermission.READ.toString())
.isEqualTo("BasePermission[...............................R=1]");
System.out.println("A = " + BasePermission.ADMINISTRATION.toString());
assertEquals("BasePermission[...........................A....=16]",
BasePermission.ADMINISTRATION.toString());
assertThat(
BasePermission.ADMINISTRATION.toString())
.isEqualTo("BasePermission[...........................A....=16]");
System.out.println("R = "
+ new CumulativePermission().set(BasePermission.READ).toString());
assertEquals("CumulativePermission[...............................R=1]",
new CumulativePermission().set(BasePermission.READ).toString());
assertThat(
new CumulativePermission().set(BasePermission.READ).toString())
.isEqualTo("CumulativePermission[...............................R=1]");
System.out.println("A = "
+ new CumulativePermission().set(SpecialPermission.ENTER)
.set(BasePermission.ADMINISTRATION).toString());
assertEquals(
"CumulativePermission[..........................EA....=48]",
new CumulativePermission().set(SpecialPermission.ENTER)
.set(BasePermission.ADMINISTRATION).toString());
assertThat(new CumulativePermission().set(SpecialPermission.ENTER)
.set(BasePermission.ADMINISTRATION).toString())
.isEqualTo("CumulativePermission[..........................EA....=48]");
System.out.println("RA = "
+ new CumulativePermission().set(BasePermission.ADMINISTRATION)
.set(BasePermission.READ).toString());
assertEquals(
"CumulativePermission[...........................A...R=17]",
new CumulativePermission().set(BasePermission.ADMINISTRATION)
.set(BasePermission.READ).toString());
assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION)
.set(BasePermission.READ).toString())
.isEqualTo("CumulativePermission[...........................A...R=17]");
System.out.println("R = "
+ new CumulativePermission().set(BasePermission.ADMINISTRATION)
assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION)
.set(BasePermission.READ).clear(BasePermission.ADMINISTRATION)
.toString());
assertEquals(
"CumulativePermission[...............................R=1]",
new CumulativePermission().set(BasePermission.ADMINISTRATION)
.set(BasePermission.READ).clear(BasePermission.ADMINISTRATION)
.toString());
.toString())
.isEqualTo("CumulativePermission[...............................R=1]");
System.out.println("0 = "
+ new CumulativePermission().set(BasePermission.ADMINISTRATION)
assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION)
.set(BasePermission.READ).clear(BasePermission.ADMINISTRATION)
.clear(BasePermission.READ).toString());
assertEquals(
"CumulativePermission[................................=0]",
new CumulativePermission().set(BasePermission.ADMINISTRATION)
.set(BasePermission.READ).clear(BasePermission.ADMINISTRATION)
.clear(BasePermission.READ).toString());
.clear(BasePermission.READ).toString())
.isEqualTo("CumulativePermission[................................=0]");
}
}

View File

@ -1,6 +1,7 @@
package org.springframework.security.acls.jdbc;
import junit.framework.Assert;
import static org.assertj.core.api.Assertions.*;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
@ -45,14 +46,12 @@ public class BasicLookupStrategyTests {
@BeforeClass
public static void initCacheManaer() {
cacheManager = CacheManager.create();
cacheManager
.addCache(new Cache("basiclookuptestcache", 500, false, false, 30, 30));
cacheManager.addCache(new Cache("basiclookuptestcache", 500, false, false, 30, 30));
}
@BeforeClass
public static void createDatabase() throws Exception {
dataSource = new SingleConnectionDataSource("jdbc:hsqldb:mem:lookupstrategytest",
"sa", "", true);
dataSource = new SingleConnectionDataSource("jdbc:hsqldb:mem:lookupstrategytest", "sa", "", true);
dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
jdbcTemplate = new JdbcTemplate(dataSource);
@ -75,9 +74,7 @@ public class BasicLookupStrategyTests {
@Before
public void populateDatabase() {
String query = "INSERT INTO acl_sid(ID,PRINCIPAL,SID) VALUES (1,1,'ben');"
+ "INSERT INTO acl_class(ID,CLASS) VALUES (2,'"
+ TARGET_CLASS
+ "');"
+ "INSERT INTO acl_class(ID,CLASS) VALUES (2,'" + TARGET_CLASS + "');"
+ "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (1,2,100,null,1,1);"
+ "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (2,2,101,1,1,1);"
+ "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (3,2,102,2,1,1);"
@ -102,14 +99,10 @@ public class BasicLookupStrategyTests {
@After
public void emptyDatabase() {
String query = "DELETE FROM acl_entry;"
+ "DELETE FROM acl_object_identity WHERE ID = 7;"
+ "DELETE FROM acl_object_identity WHERE ID = 6;"
+ "DELETE FROM acl_object_identity WHERE ID = 5;"
+ "DELETE FROM acl_object_identity WHERE ID = 4;"
+ "DELETE FROM acl_object_identity WHERE ID = 3;"
+ "DELETE FROM acl_object_identity WHERE ID = 2;"
+ "DELETE FROM acl_object_identity WHERE ID = 1;"
String query = "DELETE FROM acl_entry;" + "DELETE FROM acl_object_identity WHERE ID = 7;"
+ "DELETE FROM acl_object_identity WHERE ID = 6;" + "DELETE FROM acl_object_identity WHERE ID = 5;"
+ "DELETE FROM acl_object_identity WHERE ID = 4;" + "DELETE FROM acl_object_identity WHERE ID = 3;"
+ "DELETE FROM acl_object_identity WHERE ID = 2;" + "DELETE FROM acl_object_identity WHERE ID = 1;"
+ "DELETE FROM acl_class;" + "DELETE FROM acl_sid;";
jdbcTemplate.execute(query);
}
@ -123,33 +116,29 @@ public class BasicLookupStrategyTests {
@Test
public void testAclsRetrievalWithDefaultBatchSize() throws Exception {
ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(100));
ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(
101));
// Deliberately use an integer for the child, to reproduce bug report in SEC-819
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS,
Integer.valueOf(102));
ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(101));
// Deliberately use an integer for the child, to reproduce bug report in
// SEC-819
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, Integer.valueOf(102));
Map<ObjectIdentity, Acl> map = this.strategy.readAclsById(
Arrays.asList(topParentOid, middleParentOid, childOid), null);
Map<ObjectIdentity, Acl> map = this.strategy
.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
checkEntries(topParentOid, middleParentOid, childOid, map);
}
@Test
public void testAclsRetrievalFromCacheOnly() throws Exception {
ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS,
Integer.valueOf(100));
ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(
101));
ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, Integer.valueOf(100));
ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(101));
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(102));
// Objects were put in cache
strategy.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid),
null);
strategy.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
// Let's empty the database to force acls retrieval from cache
emptyDatabase();
Map<ObjectIdentity, Acl> map = this.strategy.readAclsById(
Arrays.asList(topParentOid, middleParentOid, childOid), null);
Map<ObjectIdentity, Acl> map = this.strategy
.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
checkEntries(topParentOid, middleParentOid, childOid, map);
}
@ -157,99 +146,83 @@ public class BasicLookupStrategyTests {
@Test
public void testAclsRetrievalWithCustomBatchSize() throws Exception {
ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(100));
ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS,
Integer.valueOf(101));
ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, Integer.valueOf(101));
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(102));
// Set a batch size to allow multiple database queries in order to retrieve all
// Set a batch size to allow multiple database queries in order to
// retrieve all
// acls
this.strategy.setBatchSize(1);
Map<ObjectIdentity, Acl> map = this.strategy.readAclsById(
Arrays.asList(topParentOid, middleParentOid, childOid), null);
Map<ObjectIdentity, Acl> map = this.strategy
.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
checkEntries(topParentOid, middleParentOid, childOid, map);
}
private void checkEntries(ObjectIdentity topParentOid,
ObjectIdentity middleParentOid, ObjectIdentity childOid,
private void checkEntries(ObjectIdentity topParentOid, ObjectIdentity middleParentOid, ObjectIdentity childOid,
Map<ObjectIdentity, Acl> map) throws Exception {
Assert.assertEquals(3, map.size());
assertThat(map).hasSize(3);
MutableAcl topParent = (MutableAcl) map.get(topParentOid);
MutableAcl middleParent = (MutableAcl) map.get(middleParentOid);
MutableAcl child = (MutableAcl) map.get(childOid);
// Check the retrieved versions has IDs
Assert.assertNotNull(topParent.getId());
Assert.assertNotNull(middleParent.getId());
Assert.assertNotNull(child.getId());
assertThat(topParent.getId()).isNotNull();
assertThat(middleParent.getId()).isNotNull();
assertThat(child.getId()).isNotNull();
// Check their parents were correctly retrieved
Assert.assertNull(topParent.getParentAcl());
Assert.assertEquals(topParentOid, middleParent.getParentAcl().getObjectIdentity());
Assert.assertEquals(middleParentOid, child.getParentAcl().getObjectIdentity());
assertThat(topParent.getParentAcl()).isNull();
assertThat(middleParent.getParentAcl().getObjectIdentity()).isEqualTo(topParentOid);
assertThat(child.getParentAcl().getObjectIdentity()).isEqualTo(middleParentOid);
// Check their ACEs were correctly retrieved
Assert.assertEquals(2, topParent.getEntries().size());
Assert.assertEquals(1, middleParent.getEntries().size());
Assert.assertEquals(1, child.getEntries().size());
assertThat(topParent.getEntries()).hasSize(2);
assertThat(middleParent.getEntries()).hasSize(1);
assertThat(child.getEntries()).hasSize(1);
// Check object identities were correctly retrieved
Assert.assertEquals(topParentOid, topParent.getObjectIdentity());
Assert.assertEquals(middleParentOid, middleParent.getObjectIdentity());
Assert.assertEquals(childOid, child.getObjectIdentity());
assertThat(topParent.getObjectIdentity()).isEqualTo(topParentOid);
assertThat(middleParent.getObjectIdentity()).isEqualTo(middleParentOid);
assertThat(child.getObjectIdentity()).isEqualTo(childOid);
// Check each entry
Assert.assertTrue(topParent.isEntriesInheriting());
Assert.assertEquals(topParent.getId(), Long.valueOf(1));
Assert.assertEquals(topParent.getOwner(), new PrincipalSid("ben"));
Assert.assertEquals(topParent.getEntries().get(0).getId(), Long.valueOf(1));
Assert.assertEquals(topParent.getEntries().get(0).getPermission(),
BasePermission.READ);
Assert.assertEquals(topParent.getEntries().get(0).getSid(), new PrincipalSid(
"ben"));
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries().get(0))
.isAuditFailure());
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries().get(0))
.isAuditSuccess());
Assert.assertTrue((topParent.getEntries().get(0)).isGranting());
assertThat(topParent.isEntriesInheriting()).isTrue();
assertThat(Long.valueOf(1)).isEqualTo(topParent.getId());
assertThat(new PrincipalSid("ben")).isEqualTo(topParent.getOwner());
assertThat(Long.valueOf(1)).isEqualTo(topParent.getEntries().get(0).getId());
assertThat(topParent.getEntries().get(0).getPermission()).isEqualTo(BasePermission.READ);
assertThat(topParent.getEntries().get(0).getSid()).isEqualTo(new PrincipalSid("ben"));
assertThat(((AuditableAccessControlEntry) topParent.getEntries().get(0)).isAuditFailure()).isFalse();
assertThat(((AuditableAccessControlEntry) topParent.getEntries().get(0)).isAuditSuccess()).isFalse();
assertThat((topParent.getEntries().get(0)).isGranting()).isTrue();
Assert.assertEquals(topParent.getEntries().get(1).getId(), Long.valueOf(2));
Assert.assertEquals(topParent.getEntries().get(1).getPermission(),
BasePermission.WRITE);
Assert.assertEquals(topParent.getEntries().get(1).getSid(), new PrincipalSid(
"ben"));
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries().get(1))
.isAuditFailure());
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries().get(1))
.isAuditSuccess());
Assert.assertFalse(topParent.getEntries().get(1).isGranting());
assertThat(Long.valueOf(2)).isEqualTo(topParent.getEntries().get(1).getId());
assertThat(topParent.getEntries().get(1).getPermission()).isEqualTo(BasePermission.WRITE);
assertThat(topParent.getEntries().get(1).getSid()).isEqualTo(new PrincipalSid("ben"));
assertThat(((AuditableAccessControlEntry) topParent.getEntries().get(1)).isAuditFailure()).isFalse();
assertThat(((AuditableAccessControlEntry) topParent.getEntries().get(1)).isAuditSuccess()).isFalse();
assertThat(topParent.getEntries().get(1).isGranting()).isFalse();
Assert.assertTrue(middleParent.isEntriesInheriting());
Assert.assertEquals(middleParent.getId(), Long.valueOf(2));
Assert.assertEquals(middleParent.getOwner(), new PrincipalSid("ben"));
Assert.assertEquals(middleParent.getEntries().get(0).getId(), Long.valueOf(3));
Assert.assertEquals(middleParent.getEntries().get(0).getPermission(),
BasePermission.DELETE);
Assert.assertEquals(middleParent.getEntries().get(0).getSid(), new PrincipalSid(
"ben"));
Assert.assertFalse(((AuditableAccessControlEntry) middleParent.getEntries()
.get(0)).isAuditFailure());
Assert.assertFalse(((AuditableAccessControlEntry) middleParent.getEntries()
.get(0)).isAuditSuccess());
Assert.assertTrue(middleParent.getEntries().get(0).isGranting());
assertThat(middleParent.isEntriesInheriting()).isTrue();
assertThat(Long.valueOf(2)).isEqualTo(middleParent.getId());
assertThat(new PrincipalSid("ben")).isEqualTo(middleParent.getOwner());
assertThat(Long.valueOf(3)).isEqualTo(middleParent.getEntries().get(0).getId());
assertThat(middleParent.getEntries().get(0).getPermission()).isEqualTo(BasePermission.DELETE);
assertThat(middleParent.getEntries().get(0).getSid()).isEqualTo(new PrincipalSid("ben"));
assertThat(((AuditableAccessControlEntry) middleParent.getEntries().get(0)).isAuditFailure()).isFalse();
assertThat(((AuditableAccessControlEntry) middleParent.getEntries().get(0)).isAuditSuccess()).isFalse();
assertThat(middleParent.getEntries().get(0).isGranting()).isTrue();
Assert.assertTrue(child.isEntriesInheriting());
Assert.assertEquals(child.getId(), Long.valueOf(3));
Assert.assertEquals(child.getOwner(), new PrincipalSid("ben"));
Assert.assertEquals(child.getEntries().get(0).getId(), Long.valueOf(4));
Assert.assertEquals(child.getEntries().get(0).getPermission(),
BasePermission.DELETE);
Assert.assertEquals(child.getEntries().get(0).getSid(), new PrincipalSid("ben"));
Assert.assertFalse(((AuditableAccessControlEntry) child.getEntries().get(0))
.isAuditFailure());
Assert.assertFalse(((AuditableAccessControlEntry) child.getEntries().get(0))
.isAuditSuccess());
Assert.assertFalse((child.getEntries().get(0)).isGranting());
assertThat(child.isEntriesInheriting()).isTrue();
assertThat(Long.valueOf(3)).isEqualTo(child.getId());
assertThat(new PrincipalSid("ben")).isEqualTo(child.getOwner());
assertThat(Long.valueOf(4)).isEqualTo(child.getEntries().get(0).getId());
assertThat(child.getEntries().get(0).getPermission()).isEqualTo(BasePermission.DELETE);
assertThat(new PrincipalSid("ben")).isEqualTo(child.getEntries().get(0).getSid());
assertThat(((AuditableAccessControlEntry) child.getEntries().get(0)).isAuditFailure()).isFalse();
assertThat(((AuditableAccessControlEntry) child.getEntries().get(0)).isAuditSuccess()).isFalse();
assertThat((child.getEntries().get(0)).isGranting()).isFalse();
}
@Test
@ -257,36 +230,31 @@ public class BasicLookupStrategyTests {
String query = "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (4,2,103,1,1,1);";
jdbcTemplate.execute(query);
ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS,
Long.valueOf(100));
ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS,
Long.valueOf(101));
ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, Long.valueOf(100));
ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, Long.valueOf(101));
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, Long.valueOf(102));
ObjectIdentity middleParent2Oid = new ObjectIdentityImpl(TARGET_CLASS,
Long.valueOf(103));
ObjectIdentity middleParent2Oid = new ObjectIdentityImpl(TARGET_CLASS, Long.valueOf(103));
// Retrieve the child
Map<ObjectIdentity, Acl> map = this.strategy.readAclsById(
Arrays.asList(childOid), null);
Map<ObjectIdentity, Acl> map = this.strategy.readAclsById(Arrays.asList(childOid), null);
// Check that the child and all its parents were retrieved
Assert.assertNotNull(map.get(childOid));
Assert.assertEquals(childOid, map.get(childOid).getObjectIdentity());
Assert.assertNotNull(map.get(middleParentOid));
Assert.assertEquals(middleParentOid, map.get(middleParentOid).getObjectIdentity());
Assert.assertNotNull(map.get(topParentOid));
Assert.assertEquals(topParentOid, map.get(topParentOid).getObjectIdentity());
assertThat(map.get(childOid)).isNotNull();
assertThat(map.get(childOid).getObjectIdentity()).isEqualTo(childOid);
assertThat(map.get(middleParentOid)).isNotNull();
assertThat(map.get(middleParentOid).getObjectIdentity()).isEqualTo(middleParentOid);
assertThat(map.get(topParentOid)).isNotNull();
assertThat(map.get(topParentOid).getObjectIdentity()).isEqualTo(topParentOid);
// The second parent shouldn't have been retrieved
Assert.assertNull(map.get(middleParent2Oid));
assertThat(map.get(middleParent2Oid)).isNull();
}
/**
* Test created from SEC-590.
*/
@Test
public void testReadAllObjectIdentitiesWhenLastElementIsAlreadyCached()
throws Exception {
public void testReadAllObjectIdentitiesWhenLastElementIsAlreadyCached() throws Exception {
String query = "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (4,2,104,null,1,1);"
+ "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (5,2,105,4,1,1);"
+ "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (6,2,106,4,1,1);"
@ -294,15 +262,13 @@ public class BasicLookupStrategyTests {
+ "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (5,4,0,1,1,1,0,0)";
jdbcTemplate.execute(query);
ObjectIdentity grandParentOid = new ObjectIdentityImpl(TARGET_CLASS,
new Long(104));
ObjectIdentity grandParentOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(104));
ObjectIdentity parent1Oid = new ObjectIdentityImpl(TARGET_CLASS, new Long(105));
ObjectIdentity parent2Oid = new ObjectIdentityImpl(TARGET_CLASS,
Integer.valueOf(106));
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS,
Integer.valueOf(107));
ObjectIdentity parent2Oid = new ObjectIdentityImpl(TARGET_CLASS, Integer.valueOf(106));
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, Integer.valueOf(107));
// First lookup only child, thus populating the cache with grandParent, parent1
// First lookup only child, thus populating the cache with grandParent,
// parent1
// and child
List<Permission> checkPermission = Arrays.asList(BasePermission.READ);
List<Sid> sids = Arrays.asList(BEN_SID);
@ -312,25 +278,25 @@ public class BasicLookupStrategyTests {
Map<ObjectIdentity, Acl> foundAcls = strategy.readAclsById(childOids, sids);
Acl foundChildAcl = foundAcls.get(childOid);
Assert.assertNotNull(foundChildAcl);
Assert.assertTrue(foundChildAcl.isGranted(checkPermission, sids, false));
assertThat(foundChildAcl).isNotNull();
assertThat(foundChildAcl.isGranted(checkPermission, sids, false)).isTrue();
// Search for object identities has to be done in the following order: last
// Search for object identities has to be done in the following order:
// last
// element have to be one which
// is already in cache and the element before it must not be stored in cache
List<ObjectIdentity> allOids = Arrays.asList(grandParentOid, parent1Oid,
parent2Oid, childOid);
// is already in cache and the element before it must not be stored in
// cache
List<ObjectIdentity> allOids = Arrays.asList(grandParentOid, parent1Oid, parent2Oid, childOid);
try {
foundAcls = strategy.readAclsById(allOids, sids);
Assert.assertTrue(true);
}
catch (NotFoundException notExpected) {
Assert.fail("It shouldn't have thrown NotFoundException");
} catch (NotFoundException notExpected) {
fail("It shouldn't have thrown NotFoundException");
}
Acl foundParent2Acl = foundAcls.get(parent2Oid);
Assert.assertNotNull(foundParent2Acl);
Assert.assertTrue(foundParent2Acl.isGranted(checkPermission, sids, false));
assertThat(foundParent2Acl).isNotNull();
assertThat(foundParent2Acl.isGranted(checkPermission, sids, false)).isTrue();
}
@Test(expected = IllegalArgumentException.class)
@ -348,16 +314,16 @@ public class BasicLookupStrategyTests {
public void testCreatePrincipalSid() {
Sid result = strategy.createSid(true, "sid");
Assert.assertEquals(PrincipalSid.class, result.getClass());
Assert.assertEquals("sid", ((PrincipalSid) result).getPrincipal());
assertThat(result.getClass()).isEqualTo(PrincipalSid.class);
assertThat(((PrincipalSid) result).getPrincipal()).isEqualTo("sid");
}
@Test
public void testCreateGrantedAuthority() {
Sid result = strategy.createSid(false, "sid");
Assert.assertEquals(GrantedAuthoritySid.class, result.getClass());
Assert.assertEquals("sid", ((GrantedAuthoritySid) result).getGrantedAuthority());
assertThat(result.getClass()).isEqualTo(GrantedAuthoritySid.class);
assertThat(((GrantedAuthoritySid) result).getGrantedAuthority()).isEqualTo("sid");
}
}

View File

@ -2,8 +2,7 @@ package org.springframework.security.acls.jdbc;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
import static org.fest.assertions.Assertions.*;
import static org.assertj.core.api.Assertions.*;
import java.io.File;
import java.io.FileInputStream;
@ -94,7 +93,6 @@ public class EhCacheBasedAclCacheTests {
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
@ -103,7 +101,6 @@ public class EhCacheBasedAclCacheTests {
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
@ -112,7 +109,6 @@ public class EhCacheBasedAclCacheTests {
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
@ -121,7 +117,6 @@ public class EhCacheBasedAclCacheTests {
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
@ -130,7 +125,6 @@ public class EhCacheBasedAclCacheTests {
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
@ -149,15 +143,15 @@ public class EhCacheBasedAclCacheTests {
MutableAcl retrieved = (MutableAcl) ois.readObject();
ois.close();
assertEquals(acl, retrieved);
assertThat(retrieved).isEqualTo(acl);
Object retrieved1 = FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy",
retrieved);
assertEquals(null, retrieved1);
assertThat(retrieved1).isEqualTo(null);
Object retrieved2 = FieldUtils.getProtectedFieldValue(
"permissionGrantingStrategy", retrieved);
assertEquals(null, retrieved2);
assertThat(retrieved2).isEqualTo(null);
}
@Test

View File

@ -14,7 +14,7 @@
*/
package org.springframework.security.acls.jdbc;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.Arrays;
@ -147,7 +147,7 @@ public class JdbcMutableAclServiceTests extends
// Let's check if we can read them back correctly
Map<ObjectIdentity, Acl> map = jdbcMutableAclService.readAclsById(Arrays.asList(
topParentOid, middleParentOid, childOid));
assertEquals(3, map.size());
assertThat(map).hasSize(3);
// Replace our current objects with their retrieved versions
topParent = (MutableAcl) map.get(topParentOid);
@ -155,19 +155,19 @@ public class JdbcMutableAclServiceTests extends
child = (MutableAcl) map.get(childOid);
// Check the retrieved versions has IDs
assertNotNull(topParent.getId());
assertNotNull(middleParent.getId());
assertNotNull(child.getId());
assertThat(topParent.getId()).isNotNull();
assertThat(middleParent.getId()).isNotNull();
assertThat(child.getId()).isNotNull();
// Check their parents were correctly persisted
assertNull(topParent.getParentAcl());
assertEquals(topParentOid, middleParent.getParentAcl().getObjectIdentity());
assertEquals(middleParentOid, child.getParentAcl().getObjectIdentity());
assertThat(topParent.getParentAcl()).isNull();
assertThat(middleParent.getParentAcl().getObjectIdentity()).isEqualTo(topParentOid);
assertThat(child.getParentAcl().getObjectIdentity()).isEqualTo(middleParentOid);
// Check their ACEs were correctly persisted
assertEquals(2, topParent.getEntries().size());
assertEquals(1, middleParent.getEntries().size());
assertEquals(1, child.getEntries().size());
assertThat(topParent.getEntries()).hasSize(2);
assertThat(middleParent.getEntries()).hasSize(1);
assertThat(child.getEntries()).hasSize(1);
// Check the retrieved rights are correct
List<Permission> read = Arrays.asList(BasePermission.READ);
@ -175,39 +175,39 @@ public class JdbcMutableAclServiceTests extends
List<Permission> delete = Arrays.asList(BasePermission.DELETE);
List<Sid> pSid = Arrays.asList((Sid) new PrincipalSid(auth));
assertTrue(topParent.isGranted(read, pSid, false));
assertFalse(topParent.isGranted(write, pSid, false));
assertTrue(middleParent.isGranted(delete, pSid, false));
assertFalse(child.isGranted(delete, pSid, false));
assertThat(topParent.isGranted(read, pSid, false)).isTrue();
assertThat(topParent.isGranted(write, pSid, false)).isFalse();
assertThat(middleParent.isGranted(delete, pSid, false)).isTrue();
assertThat(child.isGranted(delete, pSid, false)).isFalse();
try {
child.isGranted(Arrays.asList(BasePermission.ADMINISTRATION), pSid, false);
fail("Should have thrown NotFoundException");
}
catch (NotFoundException expected) {
assertTrue(true);
}
// Now check the inherited rights (when not explicitly overridden) also look OK
assertTrue(child.isGranted(read, pSid, false));
assertFalse(child.isGranted(write, pSid, false));
assertFalse(child.isGranted(delete, pSid, false));
assertThat(child.isGranted(read, pSid, false)).isTrue();
assertThat(child.isGranted(write, pSid, false)).isFalse();
assertThat(child.isGranted(delete, pSid, false)).isFalse();
// Next change the child so it doesn't inherit permissions from above
child.setEntriesInheriting(false);
jdbcMutableAclService.updateAcl(child);
child = (MutableAcl) jdbcMutableAclService.readAclById(childOid);
assertFalse(child.isEntriesInheriting());
assertThat(child.isEntriesInheriting()).isFalse();
// Check the child permissions no longer inherit
assertFalse(child.isGranted(delete, pSid, true));
assertThat(child.isGranted(delete, pSid, true)).isFalse();
try {
child.isGranted(read, pSid, true);
fail("Should have thrown NotFoundException");
}
catch (NotFoundException expected) {
assertTrue(true);
}
try {
@ -215,7 +215,7 @@ public class JdbcMutableAclServiceTests extends
fail("Should have thrown NotFoundException");
}
catch (NotFoundException expected) {
assertTrue(true);
}
// Let's add an identical permission to the child, but it'll appear AFTER the
@ -228,7 +228,7 @@ public class JdbcMutableAclServiceTests extends
// Save the changed child
jdbcMutableAclService.updateAcl(child);
child = (MutableAcl) jdbcMutableAclService.readAclById(childOid);
assertEquals(3, child.getEntries().size());
assertThat(child.getEntries()).hasSize(3);
// Output permissions
for (int i = 0; i < child.getEntries().size(); i++) {
@ -236,25 +236,25 @@ public class JdbcMutableAclServiceTests extends
}
// Check the permissions are as they should be
assertFalse(child.isGranted(delete, pSid, true)); // as earlier permission
assertThat(child.isGranted(delete, pSid, true)).isFalse(); // as earlier permission
// overrode
assertTrue(child.isGranted(Arrays.asList(BasePermission.CREATE), pSid, true));
assertThat(child.isGranted(Arrays.asList(BasePermission.CREATE), pSid, true)).isTrue();
// Now check the first ACE (index 0) really is DELETE for our Sid and is
// non-granting
AccessControlEntry entry = child.getEntries().get(0);
assertEquals(BasePermission.DELETE.getMask(), entry.getPermission().getMask());
assertEquals(new PrincipalSid(auth), entry.getSid());
assertFalse(entry.isGranting());
assertNotNull(entry.getId());
assertThat(entry.getPermission().getMask()).isEqualTo(BasePermission.DELETE.getMask());
assertThat(entry.getSid()).isEqualTo(new PrincipalSid(auth));
assertThat(entry.isGranting()).isFalse();
assertThat(entry.getId()).isNotNull();
// Now delete that first ACE
child.deleteAce(0);
// Save and check it worked
child = jdbcMutableAclService.updateAcl(child);
assertEquals(2, child.getEntries().size());
assertTrue(child.isGranted(delete, pSid, false));
assertThat(child.getEntries()).hasSize(2);
assertThat(child.isGranted(delete, pSid, false)).isTrue();
SecurityContextHolder.clearContext();
}
@ -276,7 +276,7 @@ public class JdbcMutableAclServiceTests extends
// Check the childOid really is a child of middleParentOid
Acl childAcl = jdbcMutableAclService.readAclById(childOid);
assertEquals(middleParentOid, childAcl.getParentAcl().getObjectIdentity());
assertThat(childAcl.getParentAcl().getObjectIdentity()).isEqualTo(middleParentOid);
// Delete the mid-parent and test if the child was deleted, as well
jdbcMutableAclService.deleteAcl(middleParentOid, true);
@ -286,19 +286,19 @@ public class JdbcMutableAclServiceTests extends
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
assertTrue(true);
}
try {
jdbcMutableAclService.readAclById(childOid);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
assertTrue(true);
}
Acl acl = jdbcMutableAclService.readAclById(topParentOid);
assertNotNull(acl);
assertEquals(((MutableAcl) acl).getObjectIdentity(), topParentOid);
assertThat(acl).isNotNull();
assertThat(topParentOid).isEqualTo(((MutableAcl) acl).getObjectIdentity());
}
@Test
@ -398,17 +398,16 @@ public class JdbcMutableAclServiceTests extends
// Remove the child and check all related database rows were removed accordingly
jdbcMutableAclService.deleteAcl(childOid, false);
assertEquals(
1,
assertThat(
jdbcTemplate.queryForList(SELECT_ALL_CLASSES,
new Object[] { TARGET_CLASS }).size());
assertEquals(0, jdbcTemplate.queryForList("select * from acl_object_identity")
.size());
assertEquals(0, jdbcTemplate.queryForList("select * from acl_entry").size());
new Object[] { TARGET_CLASS })).hasSize(1);
assertThat(jdbcTemplate.queryForList("select * from acl_object_identity")
).isEmpty();
assertThat(jdbcTemplate.queryForList("select * from acl_entry")).isEmpty();
// Check the cache
assertNull(aclCache.getFromCache(childOid));
assertNull(aclCache.getFromCache(Long.valueOf(102)));
assertThat(aclCache.getFromCache(childOid)).isNull();
assertThat(aclCache.getFromCache(Long.valueOf(102))).isNull();
}
/** SEC-1107 */
@ -419,8 +418,8 @@ public class JdbcMutableAclServiceTests extends
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, Integer.valueOf(101));
jdbcMutableAclService.createAcl(oid);
assertNotNull(jdbcMutableAclService.readAclById(new ObjectIdentityImpl(
TARGET_CLASS, Long.valueOf(101))));
assertThat(jdbcMutableAclService.readAclById(new ObjectIdentityImpl(
TARGET_CLASS, Long.valueOf(101)))).isNotNull();
}
/**
@ -454,12 +453,11 @@ public class JdbcMutableAclServiceTests extends
child = (MutableAcl) jdbcMutableAclService.readAclById(childOid);
parent = (MutableAcl) child.getParentAcl();
assertEquals("Fails because child has a stale reference to its parent", 2, parent
.getEntries().size());
assertEquals(1, parent.getEntries().get(0).getPermission().getMask());
assertEquals(new PrincipalSid("ben"), parent.getEntries().get(0).getSid());
assertEquals(1, parent.getEntries().get(1).getPermission().getMask());
assertEquals(new PrincipalSid("scott"), parent.getEntries().get(1).getSid());
assertThat(parent.getEntries()).hasSize(2).withFailMessage("Fails because child has a stale reference to its parent");
assertThat(parent.getEntries().get(0).getPermission().getMask()).isEqualTo(1);
assertThat(parent.getEntries().get(0).getSid()).isEqualTo(new PrincipalSid("ben"));
assertThat(parent.getEntries().get(1).getPermission().getMask()).isEqualTo(1);
assertThat(parent.getEntries().get(1).getSid()).isEqualTo(new PrincipalSid("scott"));
}
/**
@ -492,12 +490,12 @@ public class JdbcMutableAclServiceTests extends
parent = (MutableAcl) child.getParentAcl();
assertEquals(2, parent.getEntries().size());
assertEquals(16, parent.getEntries().get(0).getPermission().getMask());
assertEquals(new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), parent.getEntries()
.get(0).getSid());
assertEquals(8, parent.getEntries().get(1).getPermission().getMask());
assertEquals(new PrincipalSid("terry"), parent.getEntries().get(1).getSid());
assertThat(parent.getEntries()).hasSize(2);
assertThat(parent.getEntries().get(0).getPermission().getMask()).isEqualTo(16);
assertThat(parent.getEntries()
.get(0).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_ADMINISTRATOR"));
assertThat(parent.getEntries().get(1).getPermission().getMask()).isEqualTo(8);
assertThat(parent.getEntries().get(1).getSid()).isEqualTo(new PrincipalSid("terry"));
}
@Test
@ -515,17 +513,17 @@ public class JdbcMutableAclServiceTests extends
// Add an ACE permission entry
Permission cm = new CumulativePermission().set(BasePermission.READ).set(
BasePermission.ADMINISTRATION);
assertEquals(17, cm.getMask());
assertThat(cm.getMask()).isEqualTo(17);
Sid benSid = new PrincipalSid(auth);
topParent.insertAce(0, cm, benSid, true);
assertEquals(1, topParent.getEntries().size());
assertThat(topParent.getEntries()).hasSize(1);
// Explicitly save the changed ACL
topParent = jdbcMutableAclService.updateAcl(topParent);
// Check the mask was retrieved correctly
assertEquals(17, topParent.getEntries().get(0).getPermission().getMask());
assertTrue(topParent.isGranted(Arrays.asList(cm), Arrays.asList(benSid), true));
assertThat(topParent.getEntries().get(0).getPermission().getMask()).isEqualTo(17);
assertThat(topParent.isGranted(Arrays.asList(cm), Arrays.asList(benSid), true)).isTrue();
SecurityContextHolder.clearContext();
}
@ -542,7 +540,7 @@ public class JdbcMutableAclServiceTests extends
Long result = customJdbcMutableAclService.createOrRetrieveSidPrimaryKey(
customSid, false);
assertEquals(result, new Long(1L));
assertThat(new Long(1L)).isEqualTo(result);
}
/**

View File

@ -18,7 +18,7 @@ import org.springframework.security.util.FieldUtils;
import java.util.Map;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
/**
* Tests {@link org.springframework.security.acls.domain.SpringCacheBasedAclCache}
@ -72,12 +72,12 @@ public class SpringCacheBasedAclCacheTests {
MutableAcl acl = new AclImpl(identity, Long.valueOf(1), aclAuthorizationStrategy,
auditLogger);
assertEquals(0, realCache.size());
assertThat(realCache).isEmpty();
myCache.putInCache(acl);
// Check we can get from cache the same objects we put in
assertEquals(myCache.getFromCache(Long.valueOf(1)), acl);
assertEquals(myCache.getFromCache(identity), acl);
assertThat(acl).isEqualTo(myCache.getFromCache(Long.valueOf(1)));
assertThat(acl).isEqualTo(myCache.getFromCache(identity));
// Put another object in cache
ObjectIdentity identity2 = new ObjectIdentityImpl(TARGET_CLASS, Long.valueOf(101));
@ -89,17 +89,17 @@ public class SpringCacheBasedAclCacheTests {
// Try to evict an entry that doesn't exist
myCache.evictFromCache(Long.valueOf(3));
myCache.evictFromCache(new ObjectIdentityImpl(TARGET_CLASS, Long.valueOf(102)));
assertEquals(realCache.size(), 4);
assertThat(4).isEqualTo(realCache.size());
myCache.evictFromCache(Long.valueOf(1));
assertEquals(realCache.size(), 2);
assertThat(2).isEqualTo(realCache.size());
// Check the second object inserted
assertEquals(myCache.getFromCache(Long.valueOf(2)), acl2);
assertEquals(myCache.getFromCache(identity2), acl2);
assertThat(acl2).isEqualTo(myCache.getFromCache(Long.valueOf(2)));
assertThat(acl2).isEqualTo(myCache.getFromCache(identity2));
myCache.evictFromCache(identity2);
assertEquals(realCache.size(), 0);
assertThat(0).isEqualTo(realCache.size());
}
@SuppressWarnings("rawtypes")
@ -133,24 +133,24 @@ public class SpringCacheBasedAclCacheTests {
acl.setParent(parentAcl);
assertEquals(0, realCache.size());
assertThat(realCache).isEmpty();
myCache.putInCache(acl);
assertEquals(realCache.size(), 4);
assertThat(4).isEqualTo(realCache.size());
// Check we can get from cache the same objects we put in
AclImpl aclFromCache = (AclImpl) myCache.getFromCache(Long.valueOf(1));
assertEquals(acl, aclFromCache);
assertThat(aclFromCache).isEqualTo(acl);
// SEC-951 check transient fields are set on parent
assertNotNull(FieldUtils.getFieldValue(aclFromCache.getParentAcl(),
"aclAuthorizationStrategy"));
assertNotNull(FieldUtils.getFieldValue(aclFromCache.getParentAcl(),
"permissionGrantingStrategy"));
assertEquals(acl, myCache.getFromCache(identity));
assertNotNull(FieldUtils.getFieldValue(aclFromCache, "aclAuthorizationStrategy"));
assertThat(FieldUtils.getFieldValue(aclFromCache.getParentAcl(),
"aclAuthorizationStrategy")).isNotNull();
assertThat(FieldUtils.getFieldValue(aclFromCache.getParentAcl(),
"permissionGrantingStrategy")).isNotNull();
assertThat(myCache.getFromCache(identity)).isEqualTo(acl);
assertThat(FieldUtils.getFieldValue(aclFromCache, "aclAuthorizationStrategy")).isNotNull();
AclImpl parentAclFromCache = (AclImpl) myCache.getFromCache(Long.valueOf(2));
assertEquals(parentAcl, parentAclFromCache);
assertNotNull(FieldUtils.getFieldValue(parentAclFromCache,
"aclAuthorizationStrategy"));
assertEquals(parentAcl, myCache.getFromCache(identityParent));
assertThat(parentAclFromCache).isEqualTo(parentAcl);
assertThat(FieldUtils.getFieldValue(parentAclFromCache,
"aclAuthorizationStrategy")).isNotNull();
assertThat(myCache.getFromCache(identityParent)).isEqualTo(parentAcl);
}
}

View File

@ -1,6 +1,6 @@
package org.springframework.security.acls.sid;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
@ -38,19 +38,19 @@ public class SidRetrievalStrategyTests {
SidRetrievalStrategy retrStrategy = new SidRetrievalStrategyImpl();
List<Sid> sids = retrStrategy.getSids(authentication);
assertNotNull(sids);
assertEquals(4, sids.size());
assertNotNull(sids.get(0));
assertTrue(sids.get(0) instanceof PrincipalSid);
assertThat(sids).isNotNull();
assertThat(sids).hasSize(4);
assertThat(sids.get(0)).isNotNull();
assertThat(sids.get(0) instanceof PrincipalSid).isTrue();
for (int i = 1; i < sids.size(); i++) {
assertTrue(sids.get(i) instanceof GrantedAuthoritySid);
assertThat(sids.get(i) instanceof GrantedAuthoritySid).isTrue();
}
assertEquals("scott", ((PrincipalSid) sids.get(0)).getPrincipal());
assertEquals("A", ((GrantedAuthoritySid) sids.get(1)).getGrantedAuthority());
assertEquals("B", ((GrantedAuthoritySid) sids.get(2)).getGrantedAuthority());
assertEquals("C", ((GrantedAuthoritySid) sids.get(3)).getGrantedAuthority());
assertThat(((PrincipalSid) sids.get(0)).getPrincipal()).isEqualTo("scott");
assertThat(((GrantedAuthoritySid) sids.get(1)).getGrantedAuthority()).isEqualTo("A");
assertThat(((GrantedAuthoritySid) sids.get(2)).getGrantedAuthority()).isEqualTo("B");
assertThat(((GrantedAuthoritySid) sids.get(3)).getGrantedAuthority()).isEqualTo("C");
}
@Test
@ -62,9 +62,9 @@ public class SidRetrievalStrategyTests {
SidRetrievalStrategy strat = new SidRetrievalStrategyImpl(rh);
List<Sid> sids = strat.getSids(authentication);
assertEquals(2, sids.size());
assertNotNull(sids.get(0));
assertTrue(sids.get(0) instanceof PrincipalSid);
assertEquals("D", ((GrantedAuthoritySid) sids.get(1)).getGrantedAuthority());
assertThat(sids).hasSize(2);
assertThat(sids.get(0)).isNotNull();
assertThat(sids.get(0) instanceof PrincipalSid).isTrue();
assertThat(((GrantedAuthoritySid) sids.get(1)).getGrantedAuthority()).isEqualTo("D");
}
}

View File

@ -1,6 +1,7 @@
package org.springframework.security.acls.sid;
import junit.framework.Assert;
import static org.assertj.core.api.Assertions.*;
import junit.framework.TestCase;
import org.springframework.security.acls.domain.GrantedAuthoritySid;
import org.springframework.security.acls.domain.PrincipalSid;
@ -20,57 +21,43 @@ public class SidTests extends TestCase {
try {
String string = null;
new PrincipalSid(string);
Assert.fail("It should have thrown IllegalArgumentException");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
new PrincipalSid("");
Assert.fail("It should have thrown IllegalArgumentException");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
new PrincipalSid("johndoe");
Assert.assertTrue(true);
}
catch (IllegalArgumentException notExpected) {
Assert.fail("It shouldn't have thrown IllegalArgumentException");
}
new PrincipalSid("johndoe");
// throws no exception
// Check one Authentication-argument constructor
try {
Authentication authentication = null;
new PrincipalSid(authentication);
Assert.fail("It should have thrown IllegalArgumentException");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
Authentication authentication = new TestingAuthenticationToken(null,
"password");
new PrincipalSid(authentication);
Assert.fail("It should have thrown IllegalArgumentException");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
Authentication authentication = new TestingAuthenticationToken("johndoe",
"password");
new PrincipalSid(authentication);
Assert.assertTrue(true);
}
catch (IllegalArgumentException notExpected) {
Assert.fail("It shouldn't have thrown IllegalArgumentException");
}
Authentication authentication = new TestingAuthenticationToken("johndoe",
"password");
new PrincipalSid(authentication);
// throws no exception
}
public void testGrantedAuthoritySidConstructorsRequiredFields() throws Exception {
@ -78,54 +65,54 @@ public class SidTests extends TestCase {
try {
String string = null;
new GrantedAuthoritySid(string);
Assert.fail("It should have thrown IllegalArgumentException");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
new GrantedAuthoritySid("");
Assert.fail("It should have thrown IllegalArgumentException");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
new GrantedAuthoritySid("ROLE_TEST");
Assert.assertTrue(true);
}
catch (IllegalArgumentException notExpected) {
Assert.fail("It shouldn't have thrown IllegalArgumentException");
fail("It shouldn't have thrown IllegalArgumentException");
}
// Check one GrantedAuthority-argument constructor
try {
GrantedAuthority ga = null;
new GrantedAuthoritySid(ga);
Assert.fail("It should have thrown IllegalArgumentException");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
GrantedAuthority ga = new SimpleGrantedAuthority(null);
new GrantedAuthoritySid(ga);
Assert.fail("It should have thrown IllegalArgumentException");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST");
new GrantedAuthoritySid(ga);
Assert.assertTrue(true);
}
catch (IllegalArgumentException notExpected) {
Assert.fail("It shouldn't have thrown IllegalArgumentException");
fail("It shouldn't have thrown IllegalArgumentException");
}
}
@ -134,32 +121,32 @@ public class SidTests extends TestCase {
"password");
Sid principalSid = new PrincipalSid(authentication);
Assert.assertFalse(principalSid.equals(null));
Assert.assertFalse(principalSid.equals("DIFFERENT_TYPE_OBJECT"));
Assert.assertTrue(principalSid.equals(principalSid));
Assert.assertTrue(principalSid.equals(new PrincipalSid(authentication)));
Assert.assertTrue(principalSid.equals(new PrincipalSid(
assertThat(principalSid.equals(null)).isFalse();
assertThat(principalSid.equals("DIFFERENT_TYPE_OBJECT")).isFalse();
assertThat(principalSid.equals(principalSid)).isTrue();
assertThat(principalSid.equals(new PrincipalSid(authentication))).isTrue();
assertTrue(principalSid.equals(new PrincipalSid(
new TestingAuthenticationToken("johndoe", null))));
Assert.assertFalse(principalSid.equals(new PrincipalSid(
assertFalse(principalSid.equals(new PrincipalSid(
new TestingAuthenticationToken("scott", null))));
Assert.assertTrue(principalSid.equals(new PrincipalSid("johndoe")));
Assert.assertFalse(principalSid.equals(new PrincipalSid("scott")));
assertThat(principalSid.equals(new PrincipalSid("johndoe"))).isTrue();
assertThat(principalSid.equals(new PrincipalSid("scott"))).isFalse();
}
public void testGrantedAuthoritySidEquals() throws Exception {
GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST");
Sid gaSid = new GrantedAuthoritySid(ga);
Assert.assertFalse(gaSid.equals(null));
Assert.assertFalse(gaSid.equals("DIFFERENT_TYPE_OBJECT"));
Assert.assertTrue(gaSid.equals(gaSid));
Assert.assertTrue(gaSid.equals(new GrantedAuthoritySid(ga)));
Assert.assertTrue(gaSid.equals(new GrantedAuthoritySid(
assertThat(gaSid.equals(null)).isFalse();
assertThat(gaSid.equals("DIFFERENT_TYPE_OBJECT")).isFalse();
assertThat(gaSid.equals(gaSid)).isTrue();
assertThat(gaSid.equals(new GrantedAuthoritySid(ga))).isTrue();
assertTrue(gaSid.equals(new GrantedAuthoritySid(
new SimpleGrantedAuthority("ROLE_TEST"))));
Assert.assertFalse(gaSid.equals(new GrantedAuthoritySid(
assertFalse(gaSid.equals(new GrantedAuthoritySid(
new SimpleGrantedAuthority("ROLE_NOT_EQUAL"))));
Assert.assertTrue(gaSid.equals(new GrantedAuthoritySid("ROLE_TEST")));
Assert.assertFalse(gaSid.equals(new GrantedAuthoritySid("ROLE_NOT_EQUAL")));
assertThat(gaSid.equals(new GrantedAuthoritySid("ROLE_TEST"))).isTrue();
assertThat(gaSid.equals(new GrantedAuthoritySid("ROLE_NOT_EQUAL"))).isFalse();
}
public void testPrincipalSidHashCode() throws Exception {
@ -167,11 +154,10 @@ public class SidTests extends TestCase {
"password");
Sid principalSid = new PrincipalSid(authentication);
Assert.assertTrue(principalSid.hashCode() == "johndoe".hashCode());
Assert.assertTrue(principalSid.hashCode() == new PrincipalSid("johndoe")
.hashCode());
Assert.assertTrue(principalSid.hashCode() != new PrincipalSid("scott").hashCode());
Assert.assertTrue(principalSid.hashCode() != new PrincipalSid(
assertThat(principalSid.hashCode()).isSameAs("johndoe".hashCode());
assertThat(principalSid.hashCode()).isSameAs(new PrincipalSid("johndoe").hashCode());
assertThat(principalSid.hashCode()).isNotEqualTo(new PrincipalSid("scott").hashCode());
assertThat(principalSid.hashCode()).isNotEqualTo(new PrincipalSid(
new TestingAuthenticationToken("scott", "password")).hashCode());
}
@ -179,12 +165,12 @@ public class SidTests extends TestCase {
GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST");
Sid gaSid = new GrantedAuthoritySid(ga);
Assert.assertTrue(gaSid.hashCode() == "ROLE_TEST".hashCode());
Assert.assertTrue(gaSid.hashCode() == new GrantedAuthoritySid("ROLE_TEST")
assertThat(gaSid.hashCode()).isEqualTo("ROLE_TEST".hashCode());
assertThat(gaSid.hashCode()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST")
.hashCode());
Assert.assertTrue(gaSid.hashCode() != new GrantedAuthoritySid("ROLE_TEST_2")
assertThat(gaSid.hashCode()).isNotEqualTo(new GrantedAuthoritySid("ROLE_TEST_2")
.hashCode());
Assert.assertTrue(gaSid.hashCode() != new GrantedAuthoritySid(
assertThat(gaSid.hashCode()).isNotEqualTo(new GrantedAuthoritySid(
new SimpleGrantedAuthority("ROLE_TEST_2")).hashCode());
}
@ -195,10 +181,10 @@ public class SidTests extends TestCase {
GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST");
GrantedAuthoritySid gaSid = new GrantedAuthoritySid(ga);
Assert.assertTrue("johndoe".equals(principalSid.getPrincipal()));
Assert.assertFalse("scott".equals(principalSid.getPrincipal()));
assertThat("johndoe".equals(principalSid.getPrincipal())).isTrue();
assertThat("scott".equals(principalSid.getPrincipal())).isFalse();
Assert.assertTrue("ROLE_TEST".equals(gaSid.getGrantedAuthority()));
Assert.assertFalse("ROLE_TEST2".equals(gaSid.getGrantedAuthority()));
assertThat("ROLE_TEST".equals(gaSid.getGrantedAuthority())).isTrue();
assertThat("ROLE_TEST2".equals(gaSid.getGrantedAuthority())).isFalse();
}
}

View File

@ -1,6 +1,6 @@
package org.springframework.security.access.intercept.aspectj.aspect;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.ArrayList;
import java.util.Arrays;
@ -129,9 +129,9 @@ public class AnnotationSecurityAspectTests {
configureForElAnnotations();
SecurityContextHolder.getContext().setAuthentication(anne);
List<String> objects = prePostSecured.postFilterMethod();
assertEquals(2, objects.size());
assertTrue(objects.contains("apple"));
assertTrue(objects.contains("aubergine"));
assertThat(objects).hasSize(2);
assertThat(objects.contains("apple")).isTrue();
assertThat(objects.contains("aubergine")).isTrue();
}
private void configureForElAnnotations() {

View File

@ -16,7 +16,7 @@
package org.springframework.security.cas.authentication;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.AssertionImpl;
@ -90,28 +90,28 @@ public class CasAuthenticationProviderTests {
Authentication result = cap.authenticate(token);
// Confirm ST-123 was NOT added to the cache
assertTrue(cache.getByTicketId("ST-456") == null);
assertThat(cache.getByTicketId("ST-456") == null).isTrue();
if (!(result instanceof CasAuthenticationToken)) {
fail("Should have returned a CasAuthenticationToken");
}
CasAuthenticationToken casResult = (CasAuthenticationToken) result;
assertEquals(makeUserDetailsFromAuthoritiesPopulator(), casResult.getPrincipal());
assertEquals("ST-123", casResult.getCredentials());
assertTrue(casResult.getAuthorities().contains(
new SimpleGrantedAuthority("ROLE_A")));
assertTrue(casResult.getAuthorities().contains(
new SimpleGrantedAuthority("ROLE_B")));
assertEquals(cap.getKey().hashCode(), casResult.getKeyHash());
assertEquals("details", casResult.getDetails());
assertThat(casResult.getPrincipal()).isEqualTo(makeUserDetailsFromAuthoritiesPopulator());
assertThat(casResult.getCredentials()).isEqualTo("ST-123");
assertThat(casResult.getAuthorities()).contains(
new SimpleGrantedAuthority("ROLE_A"));
assertThat(casResult.getAuthorities()).contains(
new SimpleGrantedAuthority("ROLE_B"));
assertThat(casResult.getKeyHash()).isEqualTo(cap.getKey().hashCode());
assertThat(casResult.getDetails()).isEqualTo("details");
// Now confirm the CasAuthenticationToken is automatically re-accepted.
// To ensure TicketValidator not called again, set it to deliver an exception...
cap.setTicketValidator(new MockTicketValidator(false));
Authentication laterResult = cap.authenticate(result);
assertEquals(result, laterResult);
assertThat(laterResult).isEqualTo(result);
}
@Test
@ -133,15 +133,15 @@ public class CasAuthenticationProviderTests {
Authentication result = cap.authenticate(token);
// Confirm ST-456 was added to the cache
assertTrue(cache.getByTicketId("ST-456") != null);
assertThat(cache.getByTicketId("ST-456") != null).isTrue();
if (!(result instanceof CasAuthenticationToken)) {
fail("Should have returned a CasAuthenticationToken");
}
assertEquals(makeUserDetailsFromAuthoritiesPopulator(), result.getPrincipal());
assertEquals("ST-456", result.getCredentials());
assertEquals("details", result.getDetails());
assertThat(result.getPrincipal()).isEqualTo(makeUserDetailsFromAuthoritiesPopulator());
assertThat(result.getCredentials()).isEqualTo("ST-456");
assertThat(result.getDetails()).isEqualTo("details");
// Now try to authenticate again. To ensure TicketValidator not
// called again, set it to deliver an exception...
@ -149,8 +149,8 @@ public class CasAuthenticationProviderTests {
// Previously created UsernamePasswordAuthenticationToken is OK
Authentication newResult = cap.authenticate(token);
assertEquals(makeUserDetailsFromAuthoritiesPopulator(), newResult.getPrincipal());
assertEquals("ST-456", newResult.getCredentials());
assertThat(newResult.getPrincipal()).isEqualTo(makeUserDetailsFromAuthoritiesPopulator());
assertThat(newResult.getCredentials()).isEqualTo("ST-456");
}
@Test
@ -331,10 +331,10 @@ public class CasAuthenticationProviderTests {
cap.afterPropertiesSet();
// TODO disabled because why do we need to expose this?
// assertTrue(cap.getUserDetailsService() != null);
assertEquals("qwerty", cap.getKey());
assertTrue(cap.getStatelessTicketCache() != null);
assertTrue(cap.getTicketValidator() != null);
// assertThat(cap.getUserDetailsService() != null).isTrue();
assertThat(cap.getKey()).isEqualTo("qwerty");
assertThat(cap.getStatelessTicketCache() != null).isTrue();
assertThat(cap.getTicketValidator() != null).isTrue();
}
@Test
@ -349,10 +349,10 @@ public class CasAuthenticationProviderTests {
TestingAuthenticationToken token = new TestingAuthenticationToken("user",
"password", "ROLE_A");
assertFalse(cap.supports(TestingAuthenticationToken.class));
assertThat(cap.supports(TestingAuthenticationToken.class)).isFalse();
// Try it anyway
assertEquals(null, cap.authenticate(token));
assertThat(cap.authenticate(token)).isEqualTo(null);
}
@Test
@ -369,14 +369,14 @@ public class CasAuthenticationProviderTests {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"some_normal_user", "password",
AuthorityUtils.createAuthorityList("ROLE_A"));
assertEquals(null, cap.authenticate(token));
assertThat(cap.authenticate(token)).isEqualTo(null);
}
@Test
public void supportsRequiredTokens() {
CasAuthenticationProvider cap = new CasAuthenticationProvider();
assertTrue(cap.supports(UsernamePasswordAuthenticationToken.class));
assertTrue(cap.supports(CasAuthenticationToken.class));
assertThat(cap.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
assertThat(cap.supports(CasAuthenticationToken.class)).isTrue();
}
// ~ Inner Classes

View File

@ -15,6 +15,8 @@
package org.springframework.security.cas.authentication;
import static org.assertj.core.api.Assertions.*;
import junit.framework.TestCase;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.AssertionImpl;
@ -97,7 +99,6 @@ public class CasAuthenticationTokenTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
@ -110,7 +111,7 @@ public class CasAuthenticationTokenTests extends TestCase {
CasAuthenticationToken token2 = new CasAuthenticationToken("key",
makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion);
assertEquals(token1, token2);
assertThat(token2).isEqualTo(token1);
}
public void testGetters() {
@ -118,16 +119,15 @@ public class CasAuthenticationTokenTests extends TestCase {
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key",
makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion);
assertEquals("key".hashCode(), token.getKeyHash());
assertEquals(makeUserDetails(), token.getPrincipal());
assertEquals("Password", token.getCredentials());
assertTrue(token.getAuthorities()
.contains(new SimpleGrantedAuthority("ROLE_ONE")));
assertTrue(token.getAuthorities()
.contains(new SimpleGrantedAuthority("ROLE_TWO")));
assertEquals(assertion, token.getAssertion());
assertEquals(makeUserDetails().getUsername(), token.getUserDetails()
.getUsername());
assertThat(token.getKeyHash()).isEqualTo("key".hashCode());
assertThat(token.getPrincipal()).isEqualTo(makeUserDetails());
assertThat(token.getCredentials()).isEqualTo("Password");
assertThat(token.getAuthorities())
.contains(new SimpleGrantedAuthority("ROLE_ONE"));
assertThat(token.getAuthorities())
.contains(new SimpleGrantedAuthority("ROLE_TWO"));
assertThat(token.getAssertion()).isEqualTo(assertion);
assertThat(token.getUserDetails().getUsername()).isEqualTo(makeUserDetails().getUsername());
}
public void testNoArgConstructorDoesntExist() {
@ -136,7 +136,7 @@ public class CasAuthenticationTokenTests extends TestCase {
fail("Should have thrown NoSuchMethodException");
}
catch (NoSuchMethodException expected) {
assertTrue(true);
}
}
@ -150,7 +150,7 @@ public class CasAuthenticationTokenTests extends TestCase {
makeUserDetails("OTHER_NAME"), "Password", ROLES, makeUserDetails(),
assertion);
assertTrue(!token1.equals(token2));
assertThat(!token1.equals(token2)).isTrue();
}
public void testNotEqualsDueToDifferentAuthenticationClass() {
@ -161,7 +161,7 @@ public class CasAuthenticationTokenTests extends TestCase {
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken(
"Test", "Password", ROLES);
assertTrue(!token1.equals(token2));
assertThat(!token1.equals(token2)).isTrue();
}
public void testNotEqualsDueToKey() {
@ -173,7 +173,7 @@ public class CasAuthenticationTokenTests extends TestCase {
CasAuthenticationToken token2 = new CasAuthenticationToken("DIFFERENT_KEY",
makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion);
assertTrue(!token1.equals(token2));
assertThat(!token1.equals(token2)).isTrue();
}
public void testNotEqualsDueToAssertion() {
@ -186,16 +186,16 @@ public class CasAuthenticationTokenTests extends TestCase {
CasAuthenticationToken token2 = new CasAuthenticationToken("key",
makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion2);
assertTrue(!token1.equals(token2));
assertThat(!token1.equals(token2)).isTrue();
}
public void testSetAuthenticated() {
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key",
makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion);
assertTrue(token.isAuthenticated());
assertThat(token.isAuthenticated()).isTrue();
token.setAuthenticated(false);
assertTrue(!token.isAuthenticated());
assertThat(!token.isAuthenticated()).isTrue();
}
public void testToString() {
@ -203,6 +203,6 @@ public class CasAuthenticationTokenTests extends TestCase {
CasAuthenticationToken token = new CasAuthenticationToken("key",
makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion);
String result = token.toString();
assertTrue(result.lastIndexOf("Credentials (Service/Proxy Ticket):") != -1);
assertThat(result.lastIndexOf("Credentials (Service/Proxy Ticket):") != -1).isTrue();
}
}

View File

@ -25,7 +25,7 @@ import org.junit.AfterClass;
import org.springframework.security.cas.authentication.CasAuthenticationToken;
import org.springframework.security.cas.authentication.EhCacheBasedTicketCache;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
/**
* Tests {@link EhCacheBasedTicketCache}.
@ -59,15 +59,15 @@ public class EhCacheBasedTicketCacheTests extends AbstractStatelessTicketCacheTe
// Check it gets stored in the cache
cache.putTicketInCache(token);
assertEquals(token, cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ"));
assertThat(cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ")).isEqualTo(token);
// Check it gets removed from the cache
cache.removeTicketFromCache(getToken());
assertNull(cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ"));
assertThat(cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ")).isNull();
// Check it doesn't return values for null or unknown service tickets
assertNull(cache.getByTicketId(null));
assertNull(cache.getByTicketId("UNKNOWN_SERVICE_TICKET"));
assertThat(cache.getByTicketId(null)).isNull();
assertThat(cache.getByTicketId("UNKNOWN_SERVICE_TICKET")).isNull();
}
@Test
@ -79,11 +79,11 @@ public class EhCacheBasedTicketCacheTests extends AbstractStatelessTicketCacheTe
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
Ehcache myCache = cacheManager.getCache("castickets");
cache.setCache(myCache);
assertEquals(myCache, cache.getCache());
assertThat(cache.getCache()).isEqualTo(myCache);
}
}

View File

@ -19,7 +19,7 @@ import org.springframework.security.cas.authentication.CasAuthenticationToken;
import org.springframework.security.cas.authentication.NullStatelessTicketCache;
import org.springframework.security.cas.authentication.StatelessTicketCache;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
/**
* Test cases for the @link {@link NullStatelessTicketCache}
@ -33,14 +33,14 @@ public class NullStatelessTicketCacheTests extends AbstractStatelessTicketCacheT
@Test
public void testGetter() {
assertNull(cache.getByTicketId(null));
assertNull(cache.getByTicketId("test"));
assertThat(cache.getByTicketId(null)).isNull();
assertThat(cache.getByTicketId("test")).isNull();
}
@Test
public void testInsertAndGet() {
final CasAuthenticationToken token = getToken();
cache.putTicketInCache(token);
assertNull(cache.getByTicketId((String) token.getCredentials()));
assertThat(cache.getByTicketId((String) token.getCredentials())).isNull();
}
}

View File

@ -20,7 +20,7 @@ import org.junit.Test;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
/**
* Tests
@ -50,15 +50,15 @@ public class SpringCacheBasedTicketCacheTests extends AbstractStatelessTicketCac
// Check it gets stored in the cache
cache.putTicketInCache(token);
assertEquals(token, cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ"));
assertThat(cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ")).isEqualTo(token);
// Check it gets removed from the cache
cache.removeTicketFromCache(getToken());
assertNull(cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ"));
assertThat(cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ")).isNull();
// Check it doesn't return values for null or unknown service tickets
assertNull(cache.getByTicketId(null));
assertNull(cache.getByTicketId("UNKNOWN_SERVICE_TICKET"));
assertThat(cache.getByTicketId(null)).isNull();
assertThat(cache.getByTicketId("UNKNOWN_SERVICE_TICKET")).isNull();
}
@Test(expected = IllegalArgumentException.class)

View File

@ -1,6 +1,7 @@
package org.springframework.security.cas.userdetails;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@ -41,10 +42,10 @@ public class GrantedAuthorityFromAssertionAttributesUserDetailsServiceTests {
assertion, "ticket");
UserDetails user = uds.loadUserDetails(token);
Set<String> roles = AuthorityUtils.authorityListToSet(user.getAuthorities());
assertTrue(roles.size() == 4);
assertTrue(roles.contains("role_a1"));
assertTrue(roles.contains("role_a2"));
assertTrue(roles.contains("role_b"));
assertTrue(roles.contains("role_c"));
assertThat(roles.size()).isEqualTo(4);
assertThat(roles).contains("role_a1");
assertThat(roles).contains("role_a2");
assertThat(roles).contains("role_b");
assertThat(roles).contains("role_c");
}
}

View File

@ -15,6 +15,8 @@
package org.springframework.security.cas.web;
import static org.assertj.core.api.Assertions.*;
import junit.framework.TestCase;
import org.springframework.mock.web.MockHttpServletRequest;
@ -42,7 +44,7 @@ public class CasAuthenticationEntryPointTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertEquals("loginUrl must be specified", expected.getMessage());
assertThat(expected.getMessage()).isEqualTo("loginUrl must be specified");
}
}
@ -55,17 +57,17 @@ public class CasAuthenticationEntryPointTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertEquals("serviceProperties must be specified", expected.getMessage());
assertThat(expected.getMessage()).isEqualTo("serviceProperties must be specified");
}
}
public void testGettersSetters() {
CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint();
ep.setLoginUrl("https://cas/login");
assertEquals("https://cas/login", ep.getLoginUrl());
assertThat(ep.getLoginUrl()).isEqualTo("https://cas/login");
ep.setServiceProperties(new ServiceProperties());
assertTrue(ep.getServiceProperties() != null);
assertThat(ep.getServiceProperties() != null).isTrue();
}
public void testNormalOperationWithRenewFalse() throws Exception {

View File

@ -15,7 +15,7 @@
package org.springframework.security.cas.web;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
@ -81,11 +81,11 @@ public class CasAuthenticationFilterTests {
}
});
assertTrue(filter.requiresAuthentication(request, new MockHttpServletResponse()));
assertThat(filter.requiresAuthentication(request, new MockHttpServletResponse())).isTrue();
Authentication result = filter.attemptAuthentication(request,
new MockHttpServletResponse());
assertTrue(result != null);
assertThat(result != null).isTrue();
}
@Test(expected = AuthenticationException.class)
@ -110,7 +110,7 @@ public class CasAuthenticationFilterTests {
MockHttpServletResponse response = new MockHttpServletResponse();
request.setServletPath(url);
assertTrue(filter.requiresAuthentication(request, response));
assertThat(filter.requiresAuthentication(request, response)).isTrue();
}
@Test
@ -120,13 +120,13 @@ public class CasAuthenticationFilterTests {
MockHttpServletResponse response = new MockHttpServletResponse();
request.setServletPath("/pgtCallback");
assertFalse(filter.requiresAuthentication(request, response));
assertThat(filter.requiresAuthentication(request, response)).isFalse();
filter.setProxyReceptorUrl(request.getServletPath());
assertFalse(filter.requiresAuthentication(request, response));
assertThat(filter.requiresAuthentication(request, response)).isFalse();
filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class));
assertTrue(filter.requiresAuthentication(request, response));
assertThat(filter.requiresAuthentication(request, response)).isTrue();
request.setServletPath("/other");
assertFalse(filter.requiresAuthentication(request, response));
assertThat(filter.requiresAuthentication(request, response)).isFalse();
}
@Test
@ -142,23 +142,23 @@ public class CasAuthenticationFilterTests {
MockHttpServletResponse response = new MockHttpServletResponse();
request.setServletPath(url);
assertTrue(filter.requiresAuthentication(request, response));
assertThat(filter.requiresAuthentication(request, response)).isTrue();
request.setServletPath("/other");
assertFalse(filter.requiresAuthentication(request, response));
assertThat(filter.requiresAuthentication(request, response)).isFalse();
request.setParameter(properties.getArtifactParameter(), "value");
assertTrue(filter.requiresAuthentication(request, response));
assertThat(filter.requiresAuthentication(request, response)).isTrue();
SecurityContextHolder.getContext().setAuthentication(
new AnonymousAuthenticationToken("key", "principal", AuthorityUtils
.createAuthorityList("ROLE_ANONYMOUS")));
assertTrue(filter.requiresAuthentication(request, response));
assertThat(filter.requiresAuthentication(request, response)).isTrue();
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("un", "principal", AuthorityUtils
.createAuthorityList("ROLE_ANONYMOUS")));
assertTrue(filter.requiresAuthentication(request, response));
assertThat(filter.requiresAuthentication(request, response)).isTrue();
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("un", "principal", "ROLE_ANONYMOUS"));
assertFalse(filter.requiresAuthentication(request, response));
assertThat(filter.requiresAuthentication(request, response)).isFalse();
}
@Test
@ -170,7 +170,7 @@ public class CasAuthenticationFilterTests {
request.setServletPath("/pgtCallback");
filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class));
filter.setProxyReceptorUrl(request.getServletPath());
assertNull(filter.attemptAuthentication(request, response));
assertThat(filter.attemptAuthentication(request, response)).isNull();
}
@Test
@ -196,8 +196,8 @@ public class CasAuthenticationFilterTests {
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
assertFalse("Authentication should not be null", SecurityContextHolder
.getContext().getAuthentication() == null);
assertThat(SecurityContextHolder
.getContext().getAuthentication()).isNotNull().withFailMessage("Authentication should not be null");
verify(chain).doFilter(request, response);
verifyZeroInteractions(successHandler);
@ -224,4 +224,4 @@ public class CasAuthenticationFilterTests {
filter.doFilter(request, response, chain);
verifyZeroInteractions(chain);
}
}
}

View File

@ -15,7 +15,7 @@
package org.springframework.security.cas.web;
import static junit.framework.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.security.cas.SamlServiceProperties;
@ -60,16 +60,16 @@ public class ServicePropertiesTests {
ServiceProperties[] sps = { new ServiceProperties(), new SamlServiceProperties() };
for (ServiceProperties sp : sps) {
sp.setSendRenew(false);
assertFalse(sp.isSendRenew());
assertThat(sp.isSendRenew()).isFalse();
sp.setSendRenew(true);
assertTrue(sp.isSendRenew());
assertThat(sp.isSendRenew()).isTrue();
sp.setArtifactParameter("notticket");
assertEquals("notticket", sp.getArtifactParameter());
assertThat(sp.getArtifactParameter()).isEqualTo("notticket");
sp.setServiceParameter("notservice");
assertEquals("notservice", sp.getServiceParameter());
assertThat(sp.getServiceParameter()).isEqualTo("notservice");
sp.setService("https://mycompany.com/service");
assertEquals("https://mycompany.com/service", sp.getService());
assertThat(sp.getService()).isEqualTo("https://mycompany.com/service");
sp.afterPropertiesSet();
}

View File

@ -15,7 +15,7 @@
*/
package org.springframework.security.cas.web.authentication;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.regex.Pattern;
@ -71,7 +71,7 @@ public class DefaultServiceAuthenticationDetailsTests {
public void getServiceUrlNullQuery() throws Exception {
details = new DefaultServiceAuthenticationDetails(casServiceUrl, request,
artifactPattern);
assertEquals(UrlUtils.buildFullRequestUrl(request), details.getServiceUrl());
assertThat(details.getServiceUrl()).isEqualTo(UrlUtils.buildFullRequestUrl(request));
}
@Test
@ -81,7 +81,7 @@ public class DefaultServiceAuthenticationDetailsTests {
artifactPattern);
String serviceUrl = details.getServiceUrl();
request.setQueryString(null);
assertEquals(UrlUtils.buildFullRequestUrl(request), serviceUrl);
assertThat(serviceUrl).isEqualTo(UrlUtils.buildFullRequestUrl(request));
}
@Test
@ -91,7 +91,7 @@ public class DefaultServiceAuthenticationDetailsTests {
artifactPattern);
String serviceUrl = details.getServiceUrl();
request.setQueryString("other=value");
assertEquals(UrlUtils.buildFullRequestUrl(request), serviceUrl);
assertThat(serviceUrl).isEqualTo(UrlUtils.buildFullRequestUrl(request));
}
@Test
@ -101,7 +101,7 @@ public class DefaultServiceAuthenticationDetailsTests {
artifactPattern);
String serviceUrl = details.getServiceUrl();
request.setQueryString("other=value");
assertEquals(UrlUtils.buildFullRequestUrl(request), serviceUrl);
assertThat(serviceUrl).isEqualTo(UrlUtils.buildFullRequestUrl(request));
}
@Test
@ -111,7 +111,7 @@ public class DefaultServiceAuthenticationDetailsTests {
artifactPattern);
String serviceUrl = details.getServiceUrl();
request.setQueryString("other=value&last=this");
assertEquals(UrlUtils.buildFullRequestUrl(request), serviceUrl);
assertThat(serviceUrl).isEqualTo(UrlUtils.buildFullRequestUrl(request));
}
@Test
@ -120,7 +120,7 @@ public class DefaultServiceAuthenticationDetailsTests {
request.setServerName("evil.com");
details = new DefaultServiceAuthenticationDetails(casServiceUrl, request,
artifactPattern);
assertEquals("https://example.com/cas-sample/secure/", details.getServiceUrl());
assertThat(details.getServiceUrl()).isEqualTo("https://example.com/cas-sample/secure/");
}
@Test
@ -128,7 +128,7 @@ public class DefaultServiceAuthenticationDetailsTests {
casServiceUrl = "https://example.com/j_spring_security_cas";
request.setServerName("evil.com");
ServiceAuthenticationDetails details = loadServiceAuthenticationDetails("defaultserviceauthenticationdetails-explicit.xml");
assertEquals("https://example.com/cas-sample/secure/", details.getServiceUrl());
assertThat(details.getServiceUrl()).isEqualTo("https://example.com/cas-sample/secure/");
}
private ServiceAuthenticationDetails loadServiceAuthenticationDetails(

View File

@ -12,7 +12,7 @@
*/
package org.springframework.security.config.ldap;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.net.ServerSocket;
@ -92,8 +92,7 @@ public class LdapServerBeanDefinitionParserTests {
appCtx = new InMemoryXmlApplicationContext("<ldap-server/>");
ApacheDSContainer dsContainer = appCtx.getBean(ApacheDSContainer.class);
assertEquals("classpath*:*.ldif",
ReflectionTestUtils.getField(dsContainer, "ldifResources"));
assertThat(ReflectionTestUtils.getField(dsContainer, "ldifResources")).isEqualTo("classpath*:*.ldif");
}
private int getDefaultPort() throws IOException {

View File

@ -12,7 +12,7 @@
*/
package org.springframework.security.config.ldap;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.springframework.security.config.ldap.LdapUserServiceBeanDefinitionParser.*;
@ -50,16 +50,12 @@ public class LdapUserServiceBeanDefinitionParserTests {
@Test
public void beanClassNamesAreCorrect() throws Exception {
assertEquals(LDAP_SEARCH_CLASS, FilterBasedLdapUserSearch.class.getName());
assertEquals(PERSON_MAPPER_CLASS, PersonContextMapper.class.getName());
assertEquals(INET_ORG_PERSON_MAPPER_CLASS,
InetOrgPersonContextMapper.class.getName());
assertEquals(LDAP_USER_MAPPER_CLASS, LdapUserDetailsMapper.class.getName());
assertEquals(LDAP_AUTHORITIES_POPULATOR_CLASS,
DefaultLdapAuthoritiesPopulator.class.getName());
assertEquals(LdapUserDetailsService.class.getName(),
new LdapUserServiceBeanDefinitionParser()
.getBeanClassName(mock(Element.class)));
assertThat(FilterBasedLdapUserSearch.class.getName()).isEqualTo(LDAP_SEARCH_CLASS);
assertThat(PersonContextMapper.class.getName()).isEqualTo(PERSON_MAPPER_CLASS);
assertThat(InetOrgPersonContextMapper.class.getName()).isEqualTo(INET_ORG_PERSON_MAPPER_CLASS);
assertThat(LdapUserDetailsMapper.class.getName()).isEqualTo(LDAP_USER_MAPPER_CLASS);
assertThat(DefaultLdapAuthoritiesPopulator.class.getName()).isEqualTo(LDAP_AUTHORITIES_POPULATOR_CLASS);
assertThat(new LdapUserServiceBeanDefinitionParser().getBeanClassName(mock(Element.class))).isEqualTo(LdapUserDetailsService.class.getName());
}
@Test
@ -75,8 +71,8 @@ public class LdapUserServiceBeanDefinitionParserTests {
UserDetails ben = uds.loadUserByUsername("ben");
Set<String> authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities());
assertEquals(3, authorities.size());
assertTrue(authorities.contains("ROLE_DEVELOPERS"));
assertThat(authorities).hasSize(3);
assertThat(authorities.contains("ROLE_DEVELOPERS")).isTrue();
}
@Test
@ -89,7 +85,7 @@ public class LdapUserServiceBeanDefinitionParserTests {
UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS");
UserDetails joe = uds.loadUserByUsername("Joe Smeth");
assertEquals("Joe Smeth", joe.getUsername());
assertThat(joe.getUsername()).isEqualTo("Joe Smeth");
}
@Test
@ -103,12 +99,12 @@ public class LdapUserServiceBeanDefinitionParserTests {
UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS");
UserDetails ben = uds.loadUserByUsername("ben");
assertTrue(AuthorityUtils.authorityListToSet(ben.getAuthorities()).contains(
assertThat(AuthorityUtils.authorityListToSet(ben.getAuthorities()).contains(
"PREFIX_DEVELOPERS"));
uds = (UserDetailsService) appCtx.getBean("ldapUDSNoPrefix");
ben = uds.loadUserByUsername("ben");
assertTrue(AuthorityUtils.authorityListToSet(ben.getAuthorities()).contains(
assertThat(AuthorityUtils.authorityListToSet(ben.getAuthorities()).contains(
"DEVELOPERS"));
}
@ -120,8 +116,8 @@ public class LdapUserServiceBeanDefinitionParserTests {
UserDetails ben = uds.loadUserByUsername("ben");
Set<String> authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities());
assertEquals(3, authorities.size());
assertTrue(authorities.contains("ROLE_DEVELOPER"));
assertThat(authorities).hasSize(3);
assertThat(authorities.contains("ROLE_DEVELOPER")).isTrue();
}
@ -140,7 +136,7 @@ public class LdapUserServiceBeanDefinitionParserTests {
+ "<ldap-user-service id='ldapUDS' user-search-filter='(uid={0})' user-details-class='person'/>");
UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS");
UserDetails ben = uds.loadUserByUsername("ben");
assertTrue(ben instanceof Person);
assertThat(ben instanceof Person).isTrue();
}
@Test
@ -149,7 +145,7 @@ public class LdapUserServiceBeanDefinitionParserTests {
+ "<ldap-user-service id='ldapUDS' user-search-filter='(uid={0})' user-details-class='inetOrgPerson'/>");
UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS");
UserDetails ben = uds.loadUserByUsername("ben");
assertTrue(ben instanceof InetOrgPerson);
assertThat(ben instanceof InetOrgPerson).isTrue();
}
@Test
@ -161,7 +157,7 @@ public class LdapUserServiceBeanDefinitionParserTests {
UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS");
UserDetails ben = uds.loadUserByUsername("ben");
assertTrue(ben instanceof InetOrgPerson);
assertThat(ben instanceof InetOrgPerson).isTrue();
}
private void setContext(String context) {

View File

@ -15,7 +15,7 @@
*/
package org.springframework.security.config.annotation;
import static org.fest.assertions.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.LinkedList;

View File

@ -25,7 +25,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
import javax.sql.DataSource
import static org.fest.assertions.Assertions.assertThat
import static org.assertj.core.api.Assertions.*
import static org.junit.Assert.fail
import org.aopalliance.intercept.MethodInterceptor

View File

@ -15,7 +15,7 @@
*/
package org.springframework.security.config.annotation.method.configuration
import static org.fest.assertions.Assertions.assertThat
import static org.assertj.core.api.Assertions.assertThat
import static org.junit.Assert.fail
import java.io.Serializable;

View File

@ -17,7 +17,7 @@ package org.springframework.security.config.annotation.method.configuration
import org.springframework.security.access.intercept.aspectj.AspectJMethodSecurityInterceptor
import static org.fest.assertions.Assertions.assertThat
import static org.assertj.core.api.Assertions.assertThat
import static org.junit.Assert.fail
import java.lang.reflect.Method

View File

@ -15,7 +15,7 @@
package org.springframework.security.config;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
@ -105,7 +105,7 @@ public class FilterChainProxyConfigTests {
public void pathWithNoMatchHasNoFilters() throws Exception {
FilterChainProxy filterChainProxy = appCtx.getBean(
"newFilterChainProxyNoDefaultPath", FilterChainProxy.class);
assertEquals(null, filterChainProxy.getFilters("/nomatch"));
assertThat(filterChainProxy.getFilters("/nomatch")).isEqualTo(null);
}
// SEC-1235
@ -115,9 +115,9 @@ public class FilterChainProxyConfigTests {
FilterChainProxy.class);
List<SecurityFilterChain> chains = fcp.getFilterChains();
assertEquals("/login*", getPattern(chains.get(0)));
assertEquals("/logout", getPattern(chains.get(1)));
assertTrue(((DefaultSecurityFilterChain) chains.get(2)).getRequestMatcher() instanceof AnyRequestMatcher);
assertThat(getPattern(chains.get(0))).isEqualTo("/login*");
assertThat(getPattern(chains.get(1))).isEqualTo("/logout");
assertThat(((DefaultSecurityFilterChain) chains.get(2)).getRequestMatcher() instanceof AnyRequestMatcher).isTrue();
}
private String getPattern(SecurityFilterChain chain) {
@ -128,24 +128,24 @@ public class FilterChainProxyConfigTests {
private void checkPathAndFilterOrder(FilterChainProxy filterChainProxy)
throws Exception {
List<Filter> filters = filterChainProxy.getFilters("/foo/blah;x=1");
assertEquals(1, filters.size());
assertTrue(filters.get(0) instanceof SecurityContextHolderAwareRequestFilter);
assertThat(filters).hasSize(1);
assertThat(filters.get(0) instanceof SecurityContextHolderAwareRequestFilter).isTrue();
filters = filterChainProxy.getFilters("/some;x=2,y=3/other/path;z=4/blah");
assertNotNull(filters);
assertEquals(3, filters.size());
assertTrue(filters.get(0) instanceof SecurityContextPersistenceFilter);
assertTrue(filters.get(1) instanceof SecurityContextHolderAwareRequestFilter);
assertTrue(filters.get(2) instanceof SecurityContextHolderAwareRequestFilter);
assertThat(filters).isNotNull();
assertThat(filters).hasSize(3);
assertThat(filters.get(0) instanceof SecurityContextPersistenceFilter).isTrue();
assertThat(filters.get(1) instanceof SecurityContextHolderAwareRequestFilter).isTrue();
assertThat(filters.get(2) instanceof SecurityContextHolderAwareRequestFilter).isTrue();
filters = filterChainProxy.getFilters("/do/not/filter;x=7");
assertEquals(0, filters.size());
assertThat(filters).isEmpty();
filters = filterChainProxy.getFilters("/another/nonspecificmatch");
assertEquals(3, filters.size());
assertTrue(filters.get(0) instanceof SecurityContextPersistenceFilter);
assertTrue(filters.get(1) instanceof UsernamePasswordAuthenticationFilter);
assertTrue(filters.get(2) instanceof SecurityContextHolderAwareRequestFilter);
assertThat(filters).hasSize(3);
assertThat(filters.get(0) instanceof SecurityContextPersistenceFilter).isTrue();
assertThat(filters.get(1) instanceof UsernamePasswordAuthenticationFilter).isTrue();
assertThat(filters.get(2) instanceof SecurityContextHolderAwareRequestFilter).isTrue();
}
private void doNormalOperation(FilterChainProxy filterChainProxy) throws Exception {

View File

@ -1,6 +1,6 @@
package org.springframework.security.config;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.After;
import org.junit.Test;
@ -45,10 +45,10 @@ public class InvalidConfigurationTests {
}
catch (BeanCreationException e) {
Throwable cause = ultimateCause(e);
assertTrue(cause instanceof NoSuchBeanDefinitionException);
assertThat(cause instanceof NoSuchBeanDefinitionException).isTrue();
NoSuchBeanDefinitionException nsbe = (NoSuchBeanDefinitionException) cause;
assertEquals(BeanIds.AUTHENTICATION_MANAGER, nsbe.getBeanName());
assertTrue(nsbe.getMessage().endsWith(
assertThat(nsbe.getBeanName()).isEqualTo(BeanIds.AUTHENTICATION_MANAGER);
assertThat(nsbe.getMessage().endsWith(
AuthenticationManagerFactoryBean.MISSING_BEAN_ERROR_MESSAGE));
}
}

View File

@ -1,6 +1,6 @@
package org.springframework.security.config;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Matchers.*;
import static org.powermock.api.mockito.PowerMockito.*;
@ -57,7 +57,7 @@ public class SecurityNamespaceHandlerTests {
fail("Expected BeanDefinitionParsingException");
}
catch (BeanDefinitionParsingException expected) {
assertTrue(expected.getMessage().contains(
assertThat(expected.getMessage().contains(
"You cannot use a spring-security-2.0.xsd"));
}
}

View File

@ -15,7 +15,7 @@
*/
package org.springframework.security.config.annotation.web.configurers;
import static org.fest.assertions.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import javax.servlet.http.HttpServletResponse;

View File

@ -15,7 +15,7 @@
*/
package org.springframework.security.config.annotation.web.configurers;
import static org.fest.assertions.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.junit.After;

View File

@ -15,7 +15,7 @@
*/
package org.springframework.security.config.annotation.web.configurers;
import static org.fest.assertions.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import javax.servlet.http.HttpServletResponse;

View File

@ -15,7 +15,7 @@
*/
package org.springframework.security.config.annotation.web.configurers;
import static org.fest.assertions.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import javax.servlet.http.HttpServletResponse;

View File

@ -31,7 +31,7 @@ import org.springframework.util.AntPathMatcher;
import java.util.Collection;
import static org.fest.assertions.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)

View File

@ -64,8 +64,8 @@ import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import static org.fest.assertions.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests {
AnnotationConfigWebApplicationContext context;
@ -191,4 +191,4 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests {
return new SyncExecutorSubscribableChannelPostProcessor();
}
}
}
}

View File

@ -14,8 +14,8 @@
*/
package org.springframework.security.config.annotation.web.socket;
import static org.fest.assertions.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.HashMap;
import java.util.Map;
@ -688,4 +688,4 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
return new SyncExecutorSubscribableChannelPostProcessor();
}
}
}
}

View File

@ -1,6 +1,6 @@
package org.springframework.security.config.authentication;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.ArrayList;
import java.util.List;
@ -33,7 +33,7 @@ public class AuthenticationManagerBeanDefinitionParserTests {
// SEC-1225
public void providersAreRegisteredAsTopLevelBeans() throws Exception {
setContext(CONTEXT);
assertEquals(1, appContext.getBeansOfType(AuthenticationProvider.class).size());
assertThat(appContext.getBeansOfType(AuthenticationProvider.class)).hasSize(1);
}
@Test
@ -45,11 +45,11 @@ public class AuthenticationManagerBeanDefinitionParserTests {
ProviderManager pm = (ProviderManager) appContext
.getBeansOfType(ProviderManager.class).values().toArray()[0];
Object eventPublisher = FieldUtils.getFieldValue(pm, "eventPublisher");
assertNotNull(eventPublisher);
assertTrue(eventPublisher instanceof DefaultAuthenticationEventPublisher);
assertThat(eventPublisher).isNotNull();
assertThat(eventPublisher instanceof DefaultAuthenticationEventPublisher).isTrue();
pm.authenticate(new UsernamePasswordAuthenticationToken("bob", "bobspassword"));
assertEquals(1, listener.events.size());
assertThat(listener.events).hasSize(1);
}
@Test
@ -57,7 +57,7 @@ public class AuthenticationManagerBeanDefinitionParserTests {
setContext(CONTEXT);
ProviderManager pm = (ProviderManager) appContext
.getBeansOfType(ProviderManager.class).values().toArray()[0];
assertTrue(pm.isEraseCredentialsAfterAuthentication());
assertThat(pm.isEraseCredentialsAfterAuthentication()).isTrue();
}
@Test
@ -65,7 +65,7 @@ public class AuthenticationManagerBeanDefinitionParserTests {
setContext("<authentication-manager erase-credentials='false'/>");
ProviderManager pm = (ProviderManager) appContext
.getBeansOfType(ProviderManager.class).values().toArray()[0];
assertFalse(pm.isEraseCredentialsAfterAuthentication());
assertThat(pm.isEraseCredentialsAfterAuthentication()).isFalse();
}
private void setContext(String context) {

View File

@ -1,6 +1,6 @@
package org.springframework.security.config.authentication;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
@ -118,7 +118,7 @@ public class AuthenticationProviderBeanDefinitionParserTests {
ShaPasswordEncoder encoder = (ShaPasswordEncoder) FieldUtils.getFieldValue(
getProvider(), "passwordEncoder");
assertEquals("SHA-256", encoder.getAlgorithm());
assertThat(encoder.getAlgorithm()).isEqualTo("SHA-256");
}
@Test

View File

@ -1,6 +1,6 @@
package org.springframework.security.config.authentication;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.After;
@ -46,7 +46,7 @@ public class JdbcUserServiceBeanDefinitionParserTests {
@Test
public void beanNameIsCorrect() throws Exception {
assertEquals(JdbcUserDetailsManager.class.getName(),
assertThat(JdbcUserDetailsManager.class.getName()).isEqualTo(
new JdbcUserServiceBeanDefinitionParser()
.getBeanClassName(mock(Element.class)));
}
@ -56,14 +56,14 @@ public class JdbcUserServiceBeanDefinitionParserTests {
setContext("<jdbc-user-service data-source-ref='dataSource'/>" + DATA_SOURCE);
JdbcUserDetailsManager mgr = (JdbcUserDetailsManager) appContext
.getBean(BeanIds.USER_DETAILS_SERVICE);
assertNotNull(mgr.loadUserByUsername("rod"));
assertThat(mgr.loadUserByUsername("rod")).isNotNull();
}
@Test
public void beanIdIsParsedCorrectly() {
setContext("<jdbc-user-service id='myUserService' data-source-ref='dataSource'/>"
+ DATA_SOURCE);
assertTrue(appContext.getBean("myUserService") instanceof JdbcUserDetailsManager);
assertThat(appContext.getBean("myUserService") instanceof JdbcUserDetailsManager).isTrue();
}
@Test
@ -76,10 +76,9 @@ public class JdbcUserServiceBeanDefinitionParserTests {
+ "'/>" + DATA_SOURCE);
JdbcUserDetailsManager mgr = (JdbcUserDetailsManager) appContext
.getBean("myUserService");
assertEquals(userQuery, FieldUtils.getFieldValue(mgr, "usersByUsernameQuery"));
assertEquals(authoritiesQuery,
FieldUtils.getFieldValue(mgr, "authoritiesByUsernameQuery"));
assertTrue(mgr.loadUserByUsername("rod") != null);
assertThat(FieldUtils.getFieldValue(mgr,"usersByUsernameQuery")).isEqualTo(userQuery);
assertThat(FieldUtils.getFieldValue(mgr, "authoritiesByUsernameQuery")).isEqualTo(authoritiesQuery);
assertThat(mgr.loadUserByUsername("rod") != null).isTrue();
}
@Test
@ -89,9 +88,8 @@ public class JdbcUserServiceBeanDefinitionParserTests {
+ "group-authorities-by-username-query='blah blah'/>" + DATA_SOURCE);
JdbcUserDetailsManager mgr = (JdbcUserDetailsManager) appContext
.getBean("myUserService");
assertEquals("blah blah",
FieldUtils.getFieldValue(mgr, "groupAuthoritiesByUsernameQuery"));
assertTrue((Boolean) FieldUtils.getFieldValue(mgr, "enableGroups"));
assertThat(FieldUtils.getFieldValue(mgr, "groupAuthoritiesByUsernameQuery")).isEqualTo("blah blah");
assertThat((Boolean) FieldUtils.getFieldValue(mgr, "enableGroups")).isTrue();
}
@Test
@ -101,9 +99,9 @@ public class JdbcUserServiceBeanDefinitionParserTests {
CachingUserDetailsService cachingUserService = (CachingUserDetailsService) appContext
.getBean("myUserService"
+ AbstractUserDetailsServiceBeanDefinitionParser.CACHING_SUFFIX);
assertSame(cachingUserService.getUserCache(), appContext.getBean("userCache"));
assertNotNull(cachingUserService.loadUserByUsername("rod"));
assertNotNull(cachingUserService.loadUserByUsername("rod"));
assertThat(appContext.getBean("userCache")).isSameAs(cachingUserService.getUserCache());
assertThat(cachingUserService.loadUserByUsername("rod")).isNotNull();
assertThat(cachingUserService.loadUserByUsername("rod")).isNotNull();
}
@Test
@ -128,10 +126,10 @@ public class JdbcUserServiceBeanDefinitionParserTests {
.getBean(BeanIds.AUTHENTICATION_MANAGER);
DaoAuthenticationProvider provider = (DaoAuthenticationProvider) mgr
.getProviders().get(0);
assertSame(provider.getUserCache(), appContext.getBean("userCache"));
assertThat(appContext.getBean("userCache")).isSameAs(provider.getUserCache());
provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "koala"));
assertNotNull("Cache should contain user after authentication", provider
.getUserCache().getUserFromCache("rod"));
assertThat(provider
.getUserCache().getUserFromCache("rod")).isNotNull().withFailMessage("Cache should contain user after authentication");
}
@Test
@ -141,7 +139,7 @@ public class JdbcUserServiceBeanDefinitionParserTests {
JdbcUserDetailsManager mgr = (JdbcUserDetailsManager) appContext
.getBean("myUserService");
UserDetails rod = mgr.loadUserByUsername("rod");
assertTrue(AuthorityUtils.authorityListToSet(rod.getAuthorities()).contains(
assertThat(AuthorityUtils.authorityListToSet(rod.getAuthorities()).contains(
"PREFIX_ROLE_SUPERVISOR"));
}

View File

@ -1,6 +1,6 @@
package org.springframework.security.config.authentication;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.security.core.userdetails.UserDetails;
@ -56,8 +56,8 @@ public class UserServiceBeanDefinitionParserTests {
UserDetailsService userService = (UserDetailsService) appContext
.getBean("service");
UserDetails joe = userService.loadUserByUsername("joe");
assertEquals("joespassword", joe.getPassword());
assertEquals(2, joe.getAuthorities().size());
assertThat(joe.getPassword()).isEqualTo("joespassword");
assertThat(joe.getAuthorities()).hasSize(2);
}
@Test
@ -67,7 +67,7 @@ public class UserServiceBeanDefinitionParserTests {
UserDetailsService userService = (UserDetailsService) appContext
.getBean("service");
UserDetails joe = userService.loadUserByUsername("joe");
assertTrue(joe.getPassword().length() > 0);
assertThat(joe.getPassword().length() > 0).isTrue();
Long.parseLong(joe.getPassword());
}
@ -79,13 +79,14 @@ public class UserServiceBeanDefinitionParserTests {
+ "</user-service>");
UserDetailsService userService = (UserDetailsService) appContext
.getBean("service");
assertEquals("http://joe.myopenid.com/",
userService.loadUserByUsername("http://joe.myopenid.com/").getUsername());
assertEquals(
"https://www.google.com/accounts/o8/id?id=MPtOaenBIk5yzW9n7n9",
assertThat(
userService.loadUserByUsername("http://joe.myopenid.com/").getUsername())
.isEqualTo("http://joe.myopenid.com/");
assertThat(
userService.loadUserByUsername(
"https://www.google.com/accounts/o8/id?id=MPtOaenBIk5yzW9n7n9")
.getUsername());
.getUsername())
.isEqualTo("https://www.google.com/accounts/o8/id?id=MPtOaenBIk5yzW9n7n9");
}
@Test
@ -97,10 +98,10 @@ public class UserServiceBeanDefinitionParserTests {
UserDetailsService userService = (UserDetailsService) appContext
.getBean("service");
UserDetails joe = userService.loadUserByUsername("joe");
assertFalse(joe.isAccountNonLocked());
assertThat(joe.isAccountNonLocked()).isFalse();
// Check case-sensitive lookup SEC-1432
UserDetails bob = userService.loadUserByUsername("Bob");
assertFalse(bob.isEnabled());
assertThat(bob.isEnabled()).isFalse();
}
@Test(expected = FatalBeanException.class)

View File

@ -1,6 +1,6 @@
package org.springframework.security.config.http;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@ -49,8 +49,8 @@ public class FilterSecurityMetadataSourceBeanDefinitionParserTests {
.getBean("fids");
Collection<ConfigAttribute> cad = fids.getAttributes(createFilterInvocation(
"/anything", "GET"));
assertNotNull(cad);
assertTrue(cad.contains(new SecurityConfig("ROLE_A")));
assertThat(cad).isNotNull();
assertThat(cad.contains(new SecurityConfig("ROLE_A"))).isTrue();
}
@Test
@ -64,8 +64,8 @@ public class FilterSecurityMetadataSourceBeanDefinitionParserTests {
ConfigAttribute[] cad = fids.getAttributes(
createFilterInvocation("/anything", "GET")).toArray(
new ConfigAttribute[0]);
assertEquals(1, cad.length);
assertEquals("hasRole('ROLE_A')", cad[0].toString());
assertThat(cad.length).isEqualTo(1);
assertThat(cad[0].toString()).isEqualTo("hasRole('ROLE_A')");
}
// SEC-1201
@ -81,9 +81,9 @@ public class FilterSecurityMetadataSourceBeanDefinitionParserTests {
.getBean("fids");
Collection<ConfigAttribute> cad = fids.getAttributes(createFilterInvocation(
"/secure", "GET"));
assertNotNull(cad);
assertEquals(1, cad.size());
assertTrue(cad.contains(new SecurityConfig("ROLE_A")));
assertThat(cad).isNotNull();
assertThat(cad).hasSize(1);
assertThat(cad.contains(new SecurityConfig("ROLE_A"))).isTrue();
}
@Test

View File

@ -15,7 +15,7 @@
*/
package org.springframework.security.config.http.customconfigurer;
import static org.fest.assertions.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.config.http.customconfigurer.CustomConfigurer.customConfigurer;
import java.util.Properties;

View File

@ -1,6 +1,6 @@
package org.springframework.security.config.method;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.security.config.ConfigTestUtils.AUTH_PROVIDER_XML;
import java.util.ArrayList;
@ -93,8 +93,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
// SEC-1213. Check the order
Advisor[] advisors = ((Advised) target).getAdvisors();
assertEquals(1, advisors.length);
assertEquals(1001, ((MethodSecurityMetadataSourceAdvisor) advisors[0]).getOrder());
assertThat(advisors.length).isEqualTo(1);
assertThat(((MethodSecurityMetadataSourceAdvisor) advisors[0]).getOrder()).isEqualTo(1001);
}
@Test(expected = AccessDeniedException.class)
@ -121,7 +121,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
PostProcessedMockUserDetailsService service = (PostProcessedMockUserDetailsService) appContext
.getBean("myUserService");
assertEquals("Hello from the post processor!", service.getPostProcessorWasHere());
assertThat(service.getPostProcessorWasHere()).isEqualTo("Hello from the post processor!");
}
@Test(expected = AccessDeniedException.class)
@ -237,7 +237,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
.getAdvice()).getAfterInvocationManager();
PostInvocationAdviceProvider aip = (PostInvocationAdviceProvider) pm
.getProviders().get(0);
assertTrue(FieldUtils.getFieldValue(mev, "preAdvice.expressionHandler") == FieldUtils
assertThat(FieldUtils.getFieldValue(mev, "preAdvice.expressionHandler")).isSameAs(FieldUtils
.getFieldValue(aip, "postAdvice.expressionHandler"));
}
@ -280,8 +280,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
// Expression is (filterObject == name or filterObject == 'sam'), so "joe" should
// be gone after pre-filter
// PostFilter should remove sam from the return object
assertEquals(1, result.size());
assertEquals("bob", result.get(0));
assertThat(result).hasSize(1);
assertThat(result.get(0)).isEqualTo("bob");
}
@Test
@ -293,8 +293,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
target = (BusinessService) appContext.getBean("target");
Object[] arg = new String[] { "joe", "bob", "sam" };
Object[] result = target.methodReturningAnArray(arg);
assertEquals(1, result.length);
assertEquals("bob", result[0]);
assertThat(result.length).isEqualTo(1);
assertThat(result[0]).isEqualTo("bob");
}
// SEC-1392
@ -348,7 +348,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
MethodSecurityMetadataSourceAdvisor msi = (MethodSecurityMetadataSourceAdvisor) appContext
.getBeansOfType(MethodSecurityMetadataSourceAdvisor.class).values()
.toArray()[0];
assertSame(ram, FieldUtils.getFieldValue(msi.getAdvice(), "runAsManager"));
assertThat(ram).isSameAs(FieldUtils.getFieldValue(msi.getAdvice(), "runAsManager"));
}
@Test
@ -421,7 +421,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
/*
* (non-Javadoc)
*
*
* @see
* org.springframework.context.ApplicationContextAware#setApplicationContext(org
* .springframework.context.ApplicationContext)

View File

@ -1,6 +1,6 @@
package org.springframework.security.config.method;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.*;
import org.junit.runner.RunWith;
@ -50,12 +50,12 @@ public class InterceptMethodsBeanDefinitionDecoratorTests implements
@Test
public void targetDoesntLoseApplicationListenerInterface() {
assertEquals(1, appContext.getBeansOfType(ApplicationListener.class).size());
assertEquals(1, appContext.getBeanNamesForType(ApplicationListener.class).length);
assertThat(appContext.getBeansOfType(ApplicationListener.class)).hasSize(1);
assertThat(appContext.getBeanNamesForType(ApplicationListener.class).length).isEqualTo(1);
appContext.publishEvent(new AuthenticationSuccessEvent(
new TestingAuthenticationToken("user", "")));
assertTrue(target instanceof ApplicationListener<?>);
assertThat(target instanceof ApplicationListener<?>).isTrue();
}
@Test

View File

@ -1,6 +1,6 @@
package org.springframework.security.intercept.method.aopalliance;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.After;
import org.junit.Before;

View File

@ -15,7 +15,7 @@
package org.springframework.security.access;
import static org.junit.Assert.assertSame;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.springframework.security.access.event.AuthorizationFailureEvent;
@ -61,8 +61,8 @@ public class AuthorizationFailureEventTests {
public void gettersReturnCtorSuppliedData() throws Exception {
AuthorizationFailureEvent event = new AuthorizationFailureEvent(new Object(),
attributes, foo, exception);
assertSame(attributes, event.getConfigAttributes());
assertSame(exception, event.getAccessDeniedException());
assertSame(foo, event.getAuthentication());
assertThat(event.getConfigAttributes()).isSameAs(attributes);
assertThat(event.getAccessDeniedException()).isSameAs(exception);
assertThat(event.getAuthentication()).isSameAs(foo);
}
}

View File

@ -15,7 +15,8 @@
package org.springframework.security.access;
import junit.framework.Assert;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.springframework.security.access.ConfigAttribute;
@ -34,7 +35,7 @@ public class SecurityConfigTests {
@Test
public void testHashCode() {
SecurityConfig config = new SecurityConfig("TEST");
Assert.assertEquals("TEST".hashCode(), config.hashCode());
assertThat(config.hashCode()).isEqualTo("TEST".hashCode());
}
@Test(expected = IllegalArgumentException.class)
@ -56,32 +57,32 @@ public class SecurityConfigTests {
public void testObjectEquals() throws Exception {
SecurityConfig security1 = new SecurityConfig("TEST");
SecurityConfig security2 = new SecurityConfig("TEST");
Assert.assertEquals(security1, security2);
assertThat(security2).isEqualTo(security1);
// SEC-311: Must observe symmetry requirement of Object.equals(Object) contract
String securityString1 = "TEST";
Assert.assertNotSame(security1, securityString1);
assertThat(securityString1).isNotSameAs(security1);
String securityString2 = "NOT_EQUAL";
Assert.assertTrue(!security1.equals(securityString2));
assertThat(!security1.equals(securityString2)).isTrue();
SecurityConfig security3 = new SecurityConfig("NOT_EQUAL");
Assert.assertTrue(!security1.equals(security3));
assertThat(!security1.equals(security3)).isTrue();
MockConfigAttribute mock1 = new MockConfigAttribute("TEST");
Assert.assertEquals(security1, mock1);
assertThat(mock1).isEqualTo(security1);
MockConfigAttribute mock2 = new MockConfigAttribute("NOT_EQUAL");
Assert.assertTrue(!security1.equals(mock2));
assertThat(!security1.equals(mock2)).isTrue();
Integer int1 = Integer.valueOf(987);
Assert.assertTrue(!security1.equals(int1));
assertThat(!security1.equals(int1)).isTrue();
}
@Test
public void testToString() {
SecurityConfig config = new SecurityConfig("TEST");
Assert.assertEquals("TEST", config.toString());
assertThat(config.toString()).isEqualTo("TEST");
}
// ~ Inner Classes

View File

@ -15,8 +15,7 @@
*/
package org.springframework.security.access.annotation;
import static org.fest.assertions.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collection;
@ -53,38 +52,37 @@ public class Jsr250MethodSecurityMetadataSourceTests {
@Test
public void methodWithRolesAllowedHasCorrectAttribute() throws Exception {
ConfigAttribute[] accessAttributes = findAttributes("adminMethod");
assertEquals(1, accessAttributes.length);
assertEquals("ROLE_ADMIN", accessAttributes[0].toString());
assertThat(accessAttributes.length).isEqualTo(1);
assertThat(accessAttributes[0].toString()).isEqualTo("ROLE_ADMIN");
}
@Test
public void permitAllMethodHasPermitAllAttribute() throws Exception {
ConfigAttribute[] accessAttributes = findAttributes("permitAllMethod");
assertEquals(1, accessAttributes.length);
assertEquals("javax.annotation.security.PermitAll",
accessAttributes[0].toString());
assertThat(accessAttributes).hasSize(1);
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);
Assert.assertNull(accessAttributes);
assertThat(accessAttributes).isNull();
}
@Test
public void classRoleIsAppliedToNoRoleMethod() throws Exception {
Collection<ConfigAttribute> accessAttributes = mds.findAttributes(userAllowed
.getClass().getMethod("noRoleMethod"), null);
Assert.assertNull(accessAttributes);
assertThat(accessAttributes).isNull();
}
@Test
public void methodRoleOverridesClassRole() throws Exception {
Collection<ConfigAttribute> accessAttributes = mds.findAttributes(userAllowed
.getClass().getMethod("adminMethod"), null);
assertEquals(1, accessAttributes.size());
assertEquals("ROLE_ADMIN", accessAttributes.toArray()[0].toString());
assertThat(accessAttributes).hasSize(1);
assertThat(accessAttributes.toArray()[0].toString()).isEqualTo("ROLE_ADMIN");
}
@Test
@ -92,8 +90,8 @@ public class Jsr250MethodSecurityMetadataSourceTests {
mds.setDefaultRolePrefix("CUSTOMPREFIX_");
ConfigAttribute[] accessAttributes = findAttributes("adminMethod");
assertEquals(1, accessAttributes.length);
assertEquals("CUSTOMPREFIX_ADMIN", accessAttributes[0].toString());
assertThat(accessAttributes.length).isEqualTo(1);
assertThat(accessAttributes[0].toString()).isEqualTo("CUSTOMPREFIX_ADMIN");
}
@Test
@ -101,8 +99,8 @@ public class Jsr250MethodSecurityMetadataSourceTests {
mds.setDefaultRolePrefix("");
ConfigAttribute[] accessAttributes = findAttributes("adminMethod");
assertEquals(1, accessAttributes.length);
assertEquals("ADMIN", accessAttributes[0].toString());
assertThat(accessAttributes.length).isEqualTo(1);
assertThat(accessAttributes[0].toString()).isEqualTo("ADMIN");
}
@Test
@ -110,15 +108,15 @@ public class Jsr250MethodSecurityMetadataSourceTests {
mds.setDefaultRolePrefix(null);
ConfigAttribute[] accessAttributes = findAttributes("adminMethod");
assertEquals(1, accessAttributes.length);
assertEquals("ADMIN", accessAttributes[0].toString());
assertThat(accessAttributes.length).isEqualTo(1);
assertThat(accessAttributes[0].toString()).isEqualTo("ADMIN");
}
@Test
public void alreadyHasDefaultPrefix() throws Exception {
ConfigAttribute[] accessAttributes = findAttributes("roleAdminMethod");
assertEquals(1, accessAttributes.length);
assertEquals("ROLE_ADMIN", accessAttributes[0].toString());
assertThat(accessAttributes.length).isEqualTo(1);
assertThat(accessAttributes[0].toString()).isEqualTo("ROLE_ADMIN");
}
// JSR-250 Spec Tests
@ -148,8 +146,8 @@ public class Jsr250MethodSecurityMetadataSourceTests {
"overriden");
Collection<ConfigAttribute> accessAttributes = mds.getAttributes(mi);
assertEquals(1, accessAttributes.size());
assertEquals("ROLE_DERIVED", accessAttributes.toArray()[0].toString());
assertThat(accessAttributes).hasSize(1);
assertThat(accessAttributes.toArray()[0].toString()).isEqualTo("ROLE_DERIVED");
}
@Test
@ -159,8 +157,8 @@ public class Jsr250MethodSecurityMetadataSourceTests {
"defaults");
Collection<ConfigAttribute> accessAttributes = mds.getAttributes(mi);
assertEquals(1, accessAttributes.size());
assertEquals("ROLE_DERIVED", accessAttributes.toArray()[0].toString());
assertThat(accessAttributes).hasSize(1);
assertThat(accessAttributes.toArray()[0].toString()).isEqualTo("ROLE_DERIVED");
}
@Test
@ -170,8 +168,8 @@ public class Jsr250MethodSecurityMetadataSourceTests {
"explicitMethod");
Collection<ConfigAttribute> accessAttributes = mds.getAttributes(mi);
assertEquals(1, accessAttributes.size());
assertEquals("ROLE_EXPLICIT", accessAttributes.toArray()[0].toString());
assertThat(accessAttributes).hasSize(1);
assertThat(accessAttributes.toArray()[0].toString()).isEqualTo("ROLE_EXPLICIT");
}
/**
@ -206,8 +204,8 @@ public class Jsr250MethodSecurityMetadataSourceTests {
"overridenIgnored");
Collection<ConfigAttribute> accessAttributes = mds.getAttributes(mi);
assertEquals(1, accessAttributes.size());
assertEquals("ROLE_DERIVED", accessAttributes.toArray()[0].toString());
assertThat(accessAttributes).hasSize(1);
assertThat(accessAttributes.toArray()[0].toString()).isEqualTo("ROLE_DERIVED");
}
// ~ Inner Classes

View File

@ -1,6 +1,6 @@
package org.springframework.security.access.annotation;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.ArrayList;
import java.util.List;
@ -27,19 +27,19 @@ public class Jsr250VoterTests {
attrs.add(new Jsr250SecurityConfig("B"));
attrs.add(new Jsr250SecurityConfig("C"));
assertEquals(AccessDecisionVoter.ACCESS_GRANTED, voter.vote(
new TestingAuthenticationToken("user", "pwd", "A"), new Object(), attrs));
assertEquals(AccessDecisionVoter.ACCESS_GRANTED, voter.vote(
new TestingAuthenticationToken("user", "pwd", "B"), new Object(), attrs));
assertEquals(AccessDecisionVoter.ACCESS_GRANTED, voter.vote(
new TestingAuthenticationToken("user", "pwd", "C"), new Object(), attrs));
assertThat(voter.vote(
new TestingAuthenticationToken("user", "pwd", "A"), new Object(), attrs)).isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
assertThat(voter.vote(
new TestingAuthenticationToken("user", "pwd", "B"), new Object(), attrs)).isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
assertThat(voter.vote(
new TestingAuthenticationToken("user", "pwd", "C"), new Object(), attrs)).isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
assertEquals(AccessDecisionVoter.ACCESS_DENIED, voter.vote(
assertThat(voter.vote(
new TestingAuthenticationToken("user", "pwd", "NONE"), new Object(),
attrs));
attrs)).isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
assertEquals(AccessDecisionVoter.ACCESS_ABSTAIN, voter.vote(
assertThat(voter.vote(
new TestingAuthenticationToken("user", "pwd", "A"), new Object(),
SecurityConfig.createList("A", "B", "C")));
SecurityConfig.createList("A", "B", "C"))).isEqualTo(AccessDecisionVoter.ACCESS_ABSTAIN);
}
}

View File

@ -14,11 +14,11 @@
*/
package org.springframework.security.access.annotation;
import static org.fest.assertions.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
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.junit.Assert.fail;
import static org.assertj.core.api.Assertions.fail;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
@ -71,14 +71,14 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
Collection<ConfigAttribute> attrs = mds.findAttributes(method,
DepartmentServiceImpl.class);
assertNotNull(attrs);
assertThat(attrs).isNotNull();
// expect 1 attribute
assertTrue("Did not find 1 attribute", attrs.size() == 1);
assertThat(attrs.size() == 1).as("Did not find 1 attribute").isTrue();
// should have 1 SecurityConfig
for (ConfigAttribute sc : attrs) {
assertEquals("Found an incorrect role", "ROLE_ADMIN", sc.getAttribute());
assertThat(sc.getAttribute()).as("Found an incorrect role").isEqualTo("ROLE_ADMIN");
}
Method superMethod = null;
@ -94,14 +94,14 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
Collection<ConfigAttribute> superAttrs = this.mds.findAttributes(superMethod,
DepartmentServiceImpl.class);
assertNotNull(superAttrs);
assertThat(superAttrs).isNotNull();
// This part of the test relates to SEC-274
// expect 1 attribute
assertEquals("Did not find 1 attribute", 1, superAttrs.size());
assertThat(superAttrs).as("Did not find 1 attribute").hasSize(1);
// should have 1 SecurityConfig
for (ConfigAttribute sc : superAttrs) {
assertEquals("Found an incorrect role", "ROLE_ADMIN", sc.getAttribute());
assertThat(sc.getAttribute()).as("Found an incorrect role").isEqualTo("ROLE_ADMIN");
}
}
@ -110,15 +110,15 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
Collection<ConfigAttribute> attrs = this.mds
.findAttributes(BusinessService.class);
assertNotNull(attrs);
assertThat(attrs).isNotNull();
// expect 1 annotation
assertEquals(1, attrs.size());
assertThat(attrs).hasSize(1);
// should have 1 SecurityConfig
SecurityConfig sc = (SecurityConfig) attrs.toArray()[0];
assertEquals("ROLE_USER", sc.getAttribute());
assertThat(sc.getAttribute()).isEqualTo("ROLE_USER");
}
@Test
@ -136,17 +136,17 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
Collection<ConfigAttribute> attrs = this.mds.findAttributes(method,
BusinessService.class);
assertNotNull(attrs);
assertThat(attrs).isNotNull();
// expect 2 attributes
assertEquals(2, attrs.size());
assertThat(attrs).hasSize(2);
boolean user = false;
boolean admin = false;
// should have 2 SecurityConfigs
for (ConfigAttribute sc : attrs) {
assertTrue(sc instanceof SecurityConfig);
assertThat(sc instanceof SecurityConfig).isTrue();
if (sc.getAttribute().equals("ROLE_USER")) {
user = true;
@ -157,7 +157,7 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
}
// expect to have ROLE_USER and ROLE_ADMIN
assertTrue(user && admin);
assertThat(user && admin).isTrue();
}
// SEC-1491
@ -167,8 +167,8 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
new CustomSecurityAnnotationMetadataExtractor());
Collection<ConfigAttribute> attrs = mds
.findAttributes(CustomAnnotatedService.class);
assertEquals(1, attrs.size());
assertEquals(SecurityEnum.ADMIN, attrs.toArray()[0]);
assertThat(attrs).hasSize(1);
assertThat(attrs.toArray()[0]).isEqualTo(SecurityEnum.ADMIN);
}
@Test
@ -180,8 +180,8 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtClassLevel).toArray(
new ConfigAttribute[0]);
assertEquals(1, attrs.length);
assertEquals("CUSTOM", attrs[0].getAttribute());
assertThat(attrs.length).isEqualTo(1);
assertThat(attrs[0].getAttribute()).isEqualTo("CUSTOM");
}
@Test
@ -193,8 +193,8 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtInterfaceLevel).toArray(
new ConfigAttribute[0]);
assertEquals(1, attrs.length);
assertEquals("CUSTOM", attrs[0].getAttribute());
assertThat(attrs.length).isEqualTo(1);
assertThat(attrs[0].getAttribute()).isEqualTo("CUSTOM");
}
@Test
@ -205,8 +205,8 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtMethodLevel).toArray(
new ConfigAttribute[0]);
assertEquals(1, attrs.length);
assertEquals("CUSTOM", attrs[0].getAttribute());
assertThat(attrs.length).isEqualTo(1);
assertThat(attrs[0].getAttribute()).isEqualTo("CUSTOM");
}
@Test
@ -214,7 +214,7 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
MockMethodInvocation mi = MethodInvocationFactory.createSec2150MethodInvocation();
Collection<ConfigAttribute> attributes = mds.getAttributes(mi);
assertThat(attributes.size()).isEqualTo(1);
assertThat(attributes).onProperty("attribute").containsOnly("ROLE_PERSON");
assertThat(attributes).extracting("attribute").containsOnly("ROLE_PERSON");
}
// Inner classes

View File

@ -1,6 +1,7 @@
package org.springframework.security.access.expression;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.junit.Before;
@ -37,8 +38,8 @@ public class AbstractSecurityExpressionHandlerTests {
Expression expression = handler.getExpressionParser().parseExpression(
"@number10.compareTo(@number20) < 0");
assertTrue((Boolean) expression.getValue(handler.createEvaluationContext(
mock(Authentication.class), new Object())));
assertThat(expression.getValue(handler.createEvaluationContext(
mock(Authentication.class), new Object()))).isEqualTo(true);
}
@Test(expected = IllegalArgumentException.class)
@ -50,7 +51,7 @@ public class AbstractSecurityExpressionHandlerTests {
public void setExpressionParser() {
SpelExpressionParser parser = new SpelExpressionParser();
handler.setExpressionParser(parser);
assertTrue(parser == handler.getExpressionParser());
assertThat(parser == handler.getExpressionParser()).isTrue();
}
}

View File

@ -1,9 +1,9 @@
package org.springframework.security.access.expression;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.fest.assertions.Assertions.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Collection;
@ -35,10 +35,10 @@ public class SecurityExpressionRootTests {
@Test
public void denyAllIsFalsePermitAllTrue() throws Exception {
assertFalse(root.denyAll());
assertFalse(root.denyAll);
assertTrue(root.permitAll());
assertTrue(root.permitAll);
assertThat(root.denyAll()).isFalse();
assertThat(root.denyAll).isFalse();
assertThat(root.permitAll()).isTrue();
assertThat(root.permitAll).isTrue();
}
@Test
@ -46,8 +46,8 @@ public class SecurityExpressionRootTests {
AuthenticationTrustResolver atr = mock(AuthenticationTrustResolver.class);
root.setTrustResolver(atr);
when(atr.isRememberMe(JOE)).thenReturn(true);
assertTrue(root.isRememberMe());
assertFalse(root.isFullyAuthenticated());
assertThat(root.isRememberMe()).isTrue();
assertThat(root.isFullyAuthenticated()).isFalse();
}
@Test
@ -59,13 +59,13 @@ public class SecurityExpressionRootTests {
}
});
assertTrue(root.hasRole("C"));
assertTrue(root.hasAuthority("ROLE_C"));
assertFalse(root.hasRole("A"));
assertFalse(root.hasRole("B"));
assertTrue(root.hasAnyRole("C", "A", "B"));
assertTrue(root.hasAnyAuthority("ROLE_C", "ROLE_A", "ROLE_B"));
assertFalse(root.hasAnyRole("A", "B"));
assertThat(root.hasRole("C")).isTrue();
assertThat(root.hasAuthority("ROLE_C")).isTrue();
assertThat(root.hasRole("A")).isFalse();
assertThat(root.hasRole("B")).isFalse();
assertThat(root.hasAnyRole("C", "A", "B")).isTrue();
assertThat(root.hasAnyAuthority("ROLE_C", "ROLE_A", "ROLE_B")).isTrue();
assertThat(root.hasAnyRole("A", "B")).isFalse();
}
@Test

View File

@ -1,6 +1,6 @@
package org.springframework.security.access.expression.method;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.reflect.Method;
import java.util.ArrayList;
@ -28,9 +28,9 @@ public class MethodExpressionVoterTests {
public void hasRoleExpressionAllowsUserWithRole() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(),
methodTakingAnArray());
assertEquals(AccessDecisionVoter.ACCESS_GRANTED, am.vote(joe, mi,
assertThat(am.vote(joe, mi,
createAttributes(new PreInvocationExpressionAttribute(null, null,
"hasRole('blah')"))));
"hasRole('blah')")))).isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
}
@Test
@ -39,16 +39,17 @@ public class MethodExpressionVoterTests {
cad.add(new PreInvocationExpressionAttribute(null, null, "hasRole('joedoesnt')"));
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(),
methodTakingAnArray());
assertEquals(AccessDecisionVoter.ACCESS_DENIED, am.vote(joe, mi, cad));
assertThat(am.vote(joe, mi, cad)).isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
}
@Test
public void matchingArgAgainstAuthenticationNameIsSuccessful() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(),
methodTakingAString(), "joe");
assertEquals(AccessDecisionVoter.ACCESS_GRANTED, am.vote(joe, mi,
assertThat(am.vote(joe, mi,
createAttributes(new PreInvocationExpressionAttribute(null, null,
"(#argument == principal) and (principal == 'joe')"))));
"(#argument == principal) and (principal == 'joe')"))))
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
}
@Test
@ -56,11 +57,12 @@ public class MethodExpressionVoterTests {
Collection arg = createCollectionArg("joe", "bob", "sam");
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(),
methodTakingACollection(), arg);
assertEquals(AccessDecisionVoter.ACCESS_GRANTED, am.vote(joe, mi,
assertThat(am.vote(joe, mi,
createAttributes(new PreInvocationExpressionAttribute(
"(filterObject == 'jim')", "collection", null))));
"(filterObject == 'jim')", "collection", null))))
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
// All objects should have been removed, because the expression is always false
assertEquals(0, arg.size());
assertThat(arg).isEmpty();
}
@Test
@ -71,9 +73,7 @@ public class MethodExpressionVoterTests {
am.vote(joe, mi, createAttributes(new PreInvocationExpressionAttribute(
"(filterObject == 'joe' or filterObject == 'sam')", "collection",
"permitAll")));
assertEquals("joe and sam should still be in the list", 2, arg.size());
assertEquals("joe", arg.get(0));
assertEquals("sam", arg.get(1));
assertThat(arg).containsExactly("joe","sam");
}
@Test(expected = IllegalArgumentException.class)
@ -104,12 +104,12 @@ public class MethodExpressionVoterTests {
public void ruleDefinedInAClassMethodIsApplied() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(),
methodTakingAString(), "joe");
assertEquals(
AccessDecisionVoter.ACCESS_GRANTED,
am.vote(joe,
mi,
createAttributes(new PreInvocationExpressionAttribute(null, null,
"T(org.springframework.security.access.expression.method.SecurityRules).isJoe(#argument)"))));
assertThat(
am.vote(joe, mi,
createAttributes(new PreInvocationExpressionAttribute(null, null,
"T(org.springframework.security.access.expression.method.SecurityRules).isJoe(#argument)"))))
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
}
private List<ConfigAttribute> createAttributes(ConfigAttribute... attributes) {

View File

@ -1,6 +1,6 @@
package org.springframework.security.access.expression.method;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
@ -44,19 +44,19 @@ public class MethodSecurityExpressionRootTests {
ctx.setVariable("var", "somestring");
Expression e = parser.parseExpression("#var.length() == 10");
assertTrue(ExpressionUtils.evaluateAsBoolean(e, ctx));
assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isTrue();
}
@Test
public void isAnonymousReturnsTrueIfTrustResolverReportsAnonymous() {
when(trustResolver.isAnonymous(user)).thenReturn(true);
assertTrue(root.isAnonymous());
assertThat(root.isAnonymous()).isTrue();
}
@Test
public void isAnonymousReturnsFalseIfTrustResolverReportsNonAnonymous() {
when(trustResolver.isAnonymous(user)).thenReturn(false);
assertFalse(root.isAnonymous());
assertThat(root.isAnonymous()).isFalse();
}
@Test
@ -68,7 +68,7 @@ public class MethodSecurityExpressionRootTests {
root.setPermissionEvaluator(pe);
when(pe.hasPermission(user, dummyDomainObject, "ignored")).thenReturn(false);
assertFalse(root.hasPermission(dummyDomainObject, "ignored"));
assertThat(root.hasPermission(dummyDomainObject, "ignored")).isFalse();
}
@ -81,7 +81,7 @@ public class MethodSecurityExpressionRootTests {
root.setPermissionEvaluator(pe);
when(pe.hasPermission(user, dummyDomainObject, "ignored")).thenReturn(true);
assertTrue(root.hasPermission(dummyDomainObject, "ignored"));
assertThat(root.hasPermission(dummyDomainObject, "ignored")).isTrue();
}
@Test
@ -95,13 +95,13 @@ public class MethodSecurityExpressionRootTests {
Expression e = parser.parseExpression("hasPermission(#domainObject, 0xA)");
// evaluator returns true
assertTrue(ExpressionUtils.evaluateAsBoolean(e, ctx));
assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isTrue();
e = parser.parseExpression("hasPermission(#domainObject, 10)");
// evaluator returns true
assertTrue(ExpressionUtils.evaluateAsBoolean(e, ctx));
assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isTrue();
e = parser.parseExpression("hasPermission(#domainObject, 0xFF)");
// evaluator returns false, make sure return value matches
assertFalse(ExpressionUtils.evaluateAsBoolean(e, ctx));
assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isFalse();
}
@Test
@ -119,11 +119,11 @@ public class MethodSecurityExpressionRootTests {
when(pe.hasPermission(user, "x", i)).thenReturn(true);
Expression e = parser.parseExpression("hasPermission(this, 2)");
assertTrue(ExpressionUtils.evaluateAsBoolean(e, ctx));
assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isTrue();
e = parser.parseExpression("hasPermission(this, 2)");
assertFalse(ExpressionUtils.evaluateAsBoolean(e, ctx));
assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isFalse();
e = parser.parseExpression("hasPermission(this.x, 2)");
assertTrue(ExpressionUtils.evaluateAsBoolean(e, ctx));
assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isTrue();
}
}

View File

@ -1,10 +1,6 @@
package org.springframework.security.access.expression.method;
import static org.fest.assertions.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
@ -78,12 +74,12 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(voidImpl1).toArray(
new ConfigAttribute[0]);
assertEquals(1, attrs.length);
assertTrue(attrs[0] instanceof PreInvocationExpressionAttribute);
assertThat(attrs.length).isEqualTo(1);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0];
assertNotNull(pre.getAuthorizeExpression());
assertEquals("someExpression", pre.getAuthorizeExpression().getExpressionString());
assertNull(pre.getFilterExpression());
assertThat(pre.getAuthorizeExpression()).isNotNull();
assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("someExpression");
assertThat(pre.getFilterExpression()).isNull();
}
@Test
@ -91,13 +87,12 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(voidImpl2).toArray(
new ConfigAttribute[0]);
assertEquals(1, attrs.length);
assertTrue(attrs[0] instanceof PreInvocationExpressionAttribute);
assertThat(attrs.length).isEqualTo(1);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0];
assertEquals("someExpression", pre.getAuthorizeExpression().getExpressionString());
assertNotNull(pre.getFilterExpression());
assertEquals("somePreFilterExpression", pre.getFilterExpression()
.getExpressionString());
assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("someExpression");
assertThat(pre.getFilterExpression()).isNotNull();
assertThat(pre.getFilterExpression().getExpressionString()).isEqualTo("somePreFilterExpression");
}
@Test
@ -105,13 +100,12 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(voidImpl3).toArray(
new ConfigAttribute[0]);
assertEquals(1, attrs.length);
assertTrue(attrs[0] instanceof PreInvocationExpressionAttribute);
assertThat(attrs.length).isEqualTo(1);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0];
assertEquals("permitAll", pre.getAuthorizeExpression().getExpressionString());
assertNotNull(pre.getFilterExpression());
assertEquals("somePreFilterExpression", pre.getFilterExpression()
.getExpressionString());
assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("permitAll");
assertThat(pre.getFilterExpression()).isNotNull();
assertThat(pre.getFilterExpression().getExpressionString()).isEqualTo("somePreFilterExpression");
}
@Test
@ -119,15 +113,14 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(listImpl1).toArray(
new ConfigAttribute[0]);
assertEquals(2, attrs.length);
assertTrue(attrs[0] instanceof PreInvocationExpressionAttribute);
assertTrue(attrs[1] instanceof PostInvocationExpressionAttribute);
assertThat(attrs.length).isEqualTo(2);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
assertThat(attrs[1] instanceof PostInvocationExpressionAttribute).isTrue();
PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0];
PostInvocationExpressionAttribute post = (PostInvocationExpressionAttribute) attrs[1];
assertEquals("permitAll", pre.getAuthorizeExpression().getExpressionString());
assertNotNull(post.getFilterExpression());
assertEquals("somePostFilterExpression", post.getFilterExpression()
.getExpressionString());
assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("permitAll");
assertThat(post.getFilterExpression()).isNotNull();
assertThat(post.getFilterExpression().getExpressionString()).isEqualTo("somePostFilterExpression");
}
@Test
@ -135,15 +128,13 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(notherListImpl1).toArray(
new ConfigAttribute[0]);
assertEquals(1, attrs.length);
assertTrue(attrs[0] instanceof PreInvocationExpressionAttribute);
assertThat(attrs.length).isEqualTo(1);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0];
assertNotNull(pre.getFilterExpression());
assertNotNull(pre.getAuthorizeExpression());
assertEquals("interfaceMethodAuthzExpression", pre.getAuthorizeExpression()
.getExpressionString());
assertEquals("interfacePreFilterExpression", pre.getFilterExpression()
.getExpressionString());
assertThat(pre.getFilterExpression()).isNotNull();
assertThat(pre.getAuthorizeExpression()).isNotNull();
assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("interfaceMethodAuthzExpression");
assertThat(pre.getFilterExpression().getExpressionString()).isEqualTo("interfacePreFilterExpression");
}
@Test
@ -151,15 +142,13 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(notherListImpl2).toArray(
new ConfigAttribute[0]);
assertEquals(1, attrs.length);
assertTrue(attrs[0] instanceof PreInvocationExpressionAttribute);
assertThat(attrs.length).isEqualTo(1);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0];
assertNotNull(pre.getFilterExpression());
assertNotNull(pre.getAuthorizeExpression());
assertEquals("interfaceMethodAuthzExpression", pre.getAuthorizeExpression()
.getExpressionString());
assertEquals("classMethodPreFilterExpression", pre.getFilterExpression()
.getExpressionString());
assertThat(pre.getFilterExpression()).isNotNull();
assertThat(pre.getAuthorizeExpression()).isNotNull();
assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("interfaceMethodAuthzExpression");
assertThat(pre.getFilterExpression().getExpressionString()).isEqualTo("classMethodPreFilterExpression");
}
@Test
@ -167,7 +156,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtClassLevel).toArray(
new ConfigAttribute[0]);
assertEquals(1, attrs.length);
assertThat(attrs.length).isEqualTo(1);
}
@Test
@ -175,7 +164,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtInterfaceLevel).toArray(
new ConfigAttribute[0]);
assertEquals(1, attrs.length);
assertThat(attrs.length).isEqualTo(1);
}
@Test
@ -183,7 +172,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtMethodLevel).toArray(
new ConfigAttribute[0]);
assertEquals(1, attrs.length);
assertThat(attrs.length).isEqualTo(1);
}
@Test

View File

@ -1,6 +1,6 @@
package org.springframework.security.access.hierarchicalroles;
import static junit.framework.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.*;
import org.springframework.security.core.GrantedAuthority;
@ -22,13 +22,13 @@ public class RoleHierarchyAuthoritiesMapperTests {
Collection<? extends GrantedAuthority> authorities = mapper
.mapAuthorities(AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_D"));
assertEquals(4, authorities.size());
assertThat(authorities).hasSize(4);
mapper = new RoleHierarchyAuthoritiesMapper(new NullRoleHierarchy());
authorities = mapper.mapAuthorities(AuthorityUtils.createAuthorityList("ROLE_A",
"ROLE_D"));
assertEquals(2, authorities.size());
assertThat(authorities).hasSize(2);
}
}

View File

@ -14,6 +14,9 @@
package org.springframework.security.access.hierarchicalroles;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
@ -38,12 +41,10 @@ public class RoleHierarchyImplTests extends TestCase {
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B");
assertNotNull(roleHierarchyImpl.getReachableGrantedAuthorities(authorities0));
assertEquals(0, roleHierarchyImpl.getReachableGrantedAuthorities(authorities0)
.size());
assertNotNull(roleHierarchyImpl.getReachableGrantedAuthorities(authorities1));
assertEquals(0, roleHierarchyImpl.getReachableGrantedAuthorities(authorities1)
.size());
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities0)).isNotNull();
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities0)).isEmpty();;
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities1)).isNotNull();
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities1)).isEmpty();;
}
public void testSimpleRoleHierarchy() {

View File

@ -14,7 +14,7 @@
package org.springframework.security.access.hierarchicalroles;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.ArrayList;
import java.util.Collection;
@ -45,29 +45,29 @@ public class TestHelperTests {
List<GrantedAuthority> authorities5 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_A");
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null,
null));
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities1));
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities2));
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities2, authorities1));
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null,
null)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities1)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities2)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities2, authorities1)).isTrue();
assertFalse(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null,
authorities1));
assertFalse(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, null));
assertFalse(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities3));
assertFalse(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities3, authorities1));
assertFalse(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities4));
assertFalse(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities4, authorities1));
assertFalse(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities4, authorities5));
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null,
authorities1)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, null)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities3)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities3, authorities1)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities4)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities4, authorities1)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities4, authorities5)).isFalse();
}
// SEC-863
@ -103,25 +103,25 @@ public class TestHelperTests {
authoritiesStrings5.add("ROLE_A");
authoritiesStrings5.add("ROLE_A");
assertTrue(CollectionUtils.isEqualCollection(
assertThat(CollectionUtils.isEqualCollection(
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities1),
authoritiesStrings1));
authoritiesStrings1)).isTrue();
assertTrue(CollectionUtils.isEqualCollection(
assertThat(CollectionUtils.isEqualCollection(
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities2),
authoritiesStrings2));
authoritiesStrings2)).isTrue();
assertTrue(CollectionUtils.isEqualCollection(
assertThat(CollectionUtils.isEqualCollection(
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities3),
authoritiesStrings3));
authoritiesStrings3)).isTrue();
assertTrue(CollectionUtils.isEqualCollection(
assertThat(CollectionUtils.isEqualCollection(
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities4),
authoritiesStrings4));
authoritiesStrings4)).isTrue();
assertTrue(CollectionUtils.isEqualCollection(
assertThat(CollectionUtils.isEqualCollection(
HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities5),
authoritiesStrings5));
authoritiesStrings5)).isTrue();
}
// SEC-863
@ -138,29 +138,29 @@ public class TestHelperTests {
List<GrantedAuthority> authorities5 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_A");
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null,
null));
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities1));
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities2));
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities2, authorities1));
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null,
null)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities1)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities2)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities2, authorities1)).isTrue();
assertFalse(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null,
authorities1));
assertFalse(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, null));
assertFalse(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities3));
assertFalse(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities3, authorities1));
assertFalse(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities4));
assertFalse(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities4, authorities1));
assertFalse(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities4, authorities5));
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null,
authorities1)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, null)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities3)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities3, authorities1)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities1, authorities4)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities4, authorities1)).isFalse();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities4, authorities5)).isFalse();
}
// SEC-863
@ -170,9 +170,9 @@ public class TestHelperTests {
.createAuthorityList("ROLE_A", "ROLE_B");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_B");
assertTrue(HierarchicalRolesTestHelper
assertThat(HierarchicalRolesTestHelper
.containTheSameGrantedAuthoritiesCompareByAuthorityString(authorities1,
authorities2));
authorities2)).isTrue();
}
// SEC-863
@ -180,13 +180,13 @@ public class TestHelperTests {
public void testCreateAuthorityList() {
List<GrantedAuthority> authorities1 = HierarchicalRolesTestHelper
.createAuthorityList("ROLE_A");
assertEquals(authorities1.size(), 1);
assertEquals("ROLE_A", authorities1.get(0).getAuthority());
assertThat(1).isEqualTo(authorities1.size());
assertThat(authorities1.get(0).getAuthority()).isEqualTo("ROLE_A");
List<GrantedAuthority> authorities2 = HierarchicalRolesTestHelper
.createAuthorityList("ROLE_A", "ROLE_C");
assertEquals(authorities2.size(), 2);
assertEquals("ROLE_A", authorities2.get(0).getAuthority());
assertEquals("ROLE_C", authorities2.get(1).getAuthority());
assertThat(2).isEqualTo(authorities2.size());
assertThat(authorities2.get(0).getAuthority()).isEqualTo("ROLE_A");
assertThat(authorities2.get(1).getAuthority()).isEqualTo("ROLE_C");
}
}

View File

@ -15,6 +15,8 @@
package org.springframework.security.access.intercept;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collection;
import java.util.List;
import java.util.Vector;
@ -51,7 +53,7 @@ public class AfterInvocationProviderManagerTests extends TestCase {
list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class,
new SecurityConfig("GIVE_ME_SWAP3")));
manager.setProviders(list);
assertEquals(list, manager.getProviders());
assertThat(manager.getProviders()).isEqualTo(list);
manager.afterPropertiesSet();
List<ConfigAttribute> attr1 = SecurityConfig
@ -65,20 +67,20 @@ public class AfterInvocationProviderManagerTests extends TestCase {
List<ConfigAttribute> attr4 = SecurityConfig
.createList(new String[] { "NEVER_CAUSES_SWAP" });
assertEquals("swap1", manager.decide(null, new SimpleMethodInvocation(), attr1,
"content-before-swapping"));
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr1,
"content-before-swapping")).isEqualTo("swap1");
assertEquals("swap2", manager.decide(null, new SimpleMethodInvocation(), attr2,
"content-before-swapping"));
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr2,
"content-before-swapping")).isEqualTo("swap2");
assertEquals("swap3", manager.decide(null, new SimpleMethodInvocation(), attr3,
"content-before-swapping"));
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr3,
"content-before-swapping")).isEqualTo("swap3");
assertEquals("content-before-swapping", manager.decide(null,
new SimpleMethodInvocation(), attr4, "content-before-swapping"));
assertThat(manager.decide(null,
new SimpleMethodInvocation(), attr4, "content-before-swapping")).isEqualTo("content-before-swapping");
assertEquals("swap3", manager.decide(null, new SimpleMethodInvocation(),
attr2and3, "content-before-swapping"));
assertThat(manager.decide(null, new SimpleMethodInvocation(),
attr2and3, "content-before-swapping")).isEqualTo("swap3");
}
public void testRejectsEmptyProvidersList() {

View File

@ -15,7 +15,7 @@
package org.springframework.security.access.intercept;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.List;
@ -41,9 +41,9 @@ public class InterceptorStatusTokenTests {
SecurityContext ctx = SecurityContextHolder.createEmptyContext();
InterceptorStatusToken token = new InterceptorStatusToken(ctx, true, attr, mi);
assertTrue(token.isContextHolderRefreshRequired());
assertEquals(attr, token.getAttributes());
assertEquals(mi, token.getSecureObject());
assertSame(ctx, token.getSecurityContext());
assertThat(token.isContextHolderRefreshRequired()).isTrue();
assertThat(token.getAttributes()).isEqualTo(attr);
assertThat(token.getSecureObject()).isEqualTo(mi);
assertThat(token.getSecurityContext()).isSameAs(ctx);
}
}

View File

@ -15,6 +15,8 @@
package org.springframework.security.access.intercept;
import static org.assertj.core.api.Assertions.assertThat;
import junit.framework.TestCase;
import org.springframework.security.access.SecurityConfig;
@ -35,16 +37,16 @@ public class NullRunAsManagerTests extends TestCase {
public void testAlwaysReturnsNull() {
NullRunAsManager runAs = new NullRunAsManager();
assertNull(runAs.buildRunAs(null, null, null));
assertThat(runAs.buildRunAs(null, null, null)).isNull();
}
public void testAlwaysSupportsClass() {
NullRunAsManager runAs = new NullRunAsManager();
assertTrue(runAs.supports(String.class));
assertThat(runAs.supports(String.class)).isTrue();
}
public void testNeverSupportsAttribute() {
NullRunAsManager runAs = new NullRunAsManager();
assertFalse(runAs.supports(new SecurityConfig("X")));
assertThat(runAs.supports(new SecurityConfig("X"))).isFalse();
}
}

View File

@ -15,7 +15,7 @@
package org.springframework.security.access.intercept;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.*;
import org.springframework.security.authentication.BadCredentialsException;
@ -54,7 +54,7 @@ public class RunAsImplAuthenticationProviderTests {
result instanceof RunAsUserToken);
RunAsUserToken resultCast = (RunAsUserToken) result;
assertEquals("my_password".hashCode(), resultCast.getKeyHash());
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
}
@Test(expected = IllegalArgumentException.class)
@ -68,14 +68,14 @@ public class RunAsImplAuthenticationProviderTests {
public void testStartupSuccess() throws Exception {
RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider();
provider.setKey("hello_world");
assertEquals("hello_world", provider.getKey());
assertThat(provider.getKey()).isEqualTo("hello_world");
provider.afterPropertiesSet();
}
@Test
public void testSupports() {
RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider();
assertTrue(provider.supports(RunAsUserToken.class));
assertTrue(!provider.supports(TestingAuthenticationToken.class));
assertThat(provider.supports(RunAsUserToken.class)).isTrue();
assertThat(!provider.supports(TestingAuthenticationToken.class)).isTrue();
}
}

View File

@ -15,6 +15,8 @@
package org.springframework.security.access.intercept;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Set;
import junit.framework.TestCase;
@ -32,7 +34,7 @@ import org.springframework.security.core.authority.AuthorityUtils;
public class RunAsManagerImplTests extends TestCase {
public void testAlwaysSupportsClass() {
RunAsManagerImpl runAs = new RunAsManagerImpl();
assertTrue(runAs.supports(String.class));
assertThat(runAs.supports(String.class)).isTrue();
}
public void testDoesNotReturnAdditionalAuthoritiesIfCalledWithoutARunAsSetting()
@ -46,7 +48,7 @@ public class RunAsManagerImplTests extends TestCase {
Authentication resultingToken = runAs.buildRunAs(inputToken, new Object(),
SecurityConfig.createList("SOMETHING_WE_IGNORE"));
assertEquals(null, resultingToken);
assertThat(resultingToken).isEqualTo(null);
}
public void testRespectsRolePrefix() throws Exception {
@ -62,17 +64,17 @@ public class RunAsManagerImplTests extends TestCase {
assertTrue("Should have returned a RunAsUserToken",
result instanceof RunAsUserToken);
assertEquals(inputToken.getPrincipal(), result.getPrincipal());
assertEquals(inputToken.getCredentials(), result.getCredentials());
assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal());
assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials());
Set<String> authorities = AuthorityUtils.authorityListToSet(result
.getAuthorities());
assertTrue(authorities.contains("FOOBAR_RUN_AS_SOMETHING"));
assertTrue(authorities.contains("ONE"));
assertTrue(authorities.contains("TWO"));
assertThat(authorities.contains("FOOBAR_RUN_AS_SOMETHING")).isTrue();
assertThat(authorities.contains("ONE")).isTrue();
assertThat(authorities.contains("TWO")).isTrue();
RunAsUserToken resultCast = (RunAsUserToken) result;
assertEquals("my_password".hashCode(), resultCast.getKeyHash());
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
}
public void testReturnsAdditionalGrantedAuthorities() throws Exception {
@ -90,17 +92,17 @@ public class RunAsManagerImplTests extends TestCase {
fail("Should have returned a RunAsUserToken");
}
assertEquals(inputToken.getPrincipal(), result.getPrincipal());
assertEquals(inputToken.getCredentials(), result.getCredentials());
assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal());
assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials());
Set<String> authorities = AuthorityUtils.authorityListToSet(result
.getAuthorities());
assertTrue(authorities.contains("ROLE_RUN_AS_SOMETHING"));
assertTrue(authorities.contains("ROLE_ONE"));
assertTrue(authorities.contains("ROLE_TWO"));
assertThat(authorities.contains("ROLE_RUN_AS_SOMETHING")).isTrue();
assertThat(authorities.contains("ROLE_ONE")).isTrue();
assertThat(authorities.contains("ROLE_TWO")).isTrue();
RunAsUserToken resultCast = (RunAsUserToken) result;
assertEquals("my_password".hashCode(), resultCast.getKeyHash());
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
}
public void testStartupDetectsMissingKey() throws Exception {
@ -111,7 +113,7 @@ public class RunAsManagerImplTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
@ -119,13 +121,13 @@ public class RunAsManagerImplTests extends TestCase {
RunAsManagerImpl runAs = new RunAsManagerImpl();
runAs.setKey("hello_world");
runAs.afterPropertiesSet();
assertEquals("hello_world", runAs.getKey());
assertThat(runAs.getKey()).isEqualTo("hello_world");
}
public void testSupports() throws Exception {
RunAsManager runAs = new RunAsManagerImpl();
assertTrue(runAs.supports(new SecurityConfig("RUN_AS_SOMETHING")));
assertTrue(!runAs.supports(new SecurityConfig("ROLE_WHICH_IS_IGNORED")));
assertTrue(!runAs.supports(new SecurityConfig("role_LOWER_CASE_FAILS")));
assertThat(runAs.supports(new SecurityConfig("RUN_AS_SOMETHING"))).isTrue();
assertThat(!runAs.supports(new SecurityConfig("ROLE_WHICH_IS_IGNORED"))).isTrue();
assertThat(!runAs.supports(new SecurityConfig("role_LOWER_CASE_FAILS"))).isTrue();
}
}

View File

@ -15,7 +15,7 @@
package org.springframework.security.access.intercept.aopalliance;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
@ -100,11 +100,11 @@ public class MethodSecurityInterceptorTests {
AfterInvocationManager aim = mock(AfterInvocationManager.class);
interceptor.setRunAsManager(runAs);
interceptor.setAfterInvocationManager(aim);
assertEquals(adm, interceptor.getAccessDecisionManager());
assertEquals(runAs, interceptor.getRunAsManager());
assertEquals(authman, interceptor.getAuthenticationManager());
assertEquals(mds, interceptor.getSecurityMetadataSource());
assertEquals(aim, interceptor.getAfterInvocationManager());
assertThat(interceptor.getAccessDecisionManager()).isEqualTo(adm);
assertThat(interceptor.getRunAsManager()).isEqualTo(runAs);
assertThat(interceptor.getAuthenticationManager()).isEqualTo(authman);
assertThat(interceptor.getSecurityMetadataSource()).isEqualTo(mds);
assertThat(interceptor.getAfterInvocationManager()).isEqualTo(aim);
}
@Test(expected = IllegalArgumentException.class)
@ -198,17 +198,15 @@ public class MethodSecurityInterceptorTests {
public void callingAPublicMethodFacadeWillNotRepeatSecurityChecksWhenPassedToTheSecuredMethodItFronts() {
mdsReturnsNull();
String result = advisedTarget.publicMakeLowerCase("HELLO");
assertEquals("hello Authentication empty", result);
assertThat(result).isEqualTo("hello Authentication empty");
}
@Test
public void callingAPublicMethodWhenPresentingAnAuthenticationObjectDoesntChangeItsAuthenticatedProperty() {
mdsReturnsNull();
SecurityContextHolder.getContext().setAuthentication(token);
assertEquals(
"hello org.springframework.security.authentication.TestingAuthenticationToken false",
advisedTarget.publicMakeLowerCase("HELLO"));
assertTrue(!token.isAuthenticated());
assertThat(advisedTarget.publicMakeLowerCase("HELLO")).isEqualTo("hello org.springframework.security.authentication.TestingAuthenticationToken false");
assertThat(!token.isAuthenticated()).isTrue();
}
@Test(expected = AuthenticationException.class)
@ -235,9 +233,7 @@ public class MethodSecurityInterceptorTests {
String result = advisedTarget.makeLowerCase("HELLO");
// Note we check the isAuthenticated remained true in following line
assertEquals(
"hello org.springframework.security.authentication.TestingAuthenticationToken true",
result);
assertThat(result).isEqualTo("hello org.springframework.security.authentication.TestingAuthenticationToken true");
verify(eventPublisher).publishEvent(any(AuthorizedEvent.class));
}
@ -254,7 +250,7 @@ public class MethodSecurityInterceptorTests {
try {
advisedTarget.makeUpperCase("HELLO");
fail();
fail("Expected Exception");
}
catch (AccessDeniedException expected) {
}
@ -280,12 +276,10 @@ public class MethodSecurityInterceptorTests {
.thenReturn(runAsToken);
String result = advisedTarget.makeUpperCase("hello");
assertEquals(
"HELLO org.springframework.security.access.intercept.RunAsUserToken true",
result);
assertThat(result).isEqualTo("HELLO org.springframework.security.access.intercept.RunAsUserToken true");
// Check we've changed back
assertSame(ctx, SecurityContextHolder.getContext());
assertSame(token, SecurityContextHolder.getContext().getAuthentication());
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token);
}
// SEC-1967
@ -312,8 +306,8 @@ public class MethodSecurityInterceptorTests {
}
// Check we've changed back
assertSame(ctx, SecurityContextHolder.getContext());
assertSame(token, SecurityContextHolder.getContext().getAuthentication());
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token);
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)

View File

@ -15,6 +15,9 @@
package org.springframework.security.access.intercept.aopalliance;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import java.lang.reflect.Method;
@ -42,7 +45,7 @@ public class MethodSecurityMetadataSourceAdvisorTests extends TestCase {
when(mds.getAttributes(method, clazz)).thenReturn(null);
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor(
"", mds, "");
assertFalse(advisor.getPointcut().getMethodMatcher().matches(method, clazz));
assertThat(advisor.getPointcut().getMethodMatcher().matches(method, clazz)).isFalse();
}
public void testAdvisorReturnsTrueWhenMethodInvocationIsDefined() throws Exception {
@ -54,6 +57,6 @@ public class MethodSecurityMetadataSourceAdvisorTests extends TestCase {
SecurityConfig.createList("ROLE_A"));
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor(
"", mds, "");
assertTrue(advisor.getPointcut().getMethodMatcher().matches(method, clazz));
assertThat(advisor.getPointcut().getMethodMatcher().matches(method, clazz)).isTrue();
}
}

View File

@ -15,7 +15,7 @@
package org.springframework.security.access.intercept.aspectj;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
@ -134,10 +134,10 @@ public class AspectJMethodSecurityInterceptorTests {
when(joinPoint.getTarget()).thenReturn(to);
when(joinPoint.getArgs()).thenReturn(new Object[] { "Hi" });
MethodInvocationAdapter mia = new MethodInvocationAdapter(joinPoint);
assertEquals("Hi", mia.getArguments()[0]);
assertEquals(m, mia.getStaticPart());
assertEquals(m, mia.getMethod());
assertSame(to, mia.getThis());
assertThat(mia.getArguments()[0]).isEqualTo("Hi");
assertThat(mia.getStaticPart()).isEqualTo(m);
assertThat(mia.getMethod()).isEqualTo(m);
assertThat(mia.getThis()).isSameAs(to);
}
@Test
@ -184,8 +184,8 @@ public class AspectJMethodSecurityInterceptorTests {
}
// Check we've changed back
assertSame(ctx, SecurityContextHolder.getContext());
assertSame(token, SecurityContextHolder.getContext().getAuthentication());
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token);
}
// SEC-1967
@ -211,7 +211,7 @@ public class AspectJMethodSecurityInterceptorTests {
}
// Check we've changed back
assertSame(ctx, SecurityContextHolder.getContext());
assertSame(token, SecurityContextHolder.getContext().getAuthentication());
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token);
}
}

View File

@ -1,6 +1,6 @@
package org.springframework.security.access.intercept.method;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.reflect.Method;
import java.util.List;
@ -35,7 +35,7 @@ public class MapBasedMethodSecurityMetadataSourceTests {
public void wildcardedMatchIsOverwrittenByMoreSpecificMatch() {
mds.addSecureMethod(MockService.class, "some*", ROLE_A);
mds.addSecureMethod(MockService.class, "someMethod*", ROLE_B);
assertEquals(ROLE_B, mds.getAttributes(someMethodInteger, MockService.class));
assertThat(mds.getAttributes(someMethodInteger, MockService.class)).isEqualTo(ROLE_B);
}
@Test
@ -43,8 +43,8 @@ public class MapBasedMethodSecurityMetadataSourceTests {
mds.addSecureMethod(MockService.class, someMethodInteger, ROLE_A);
mds.addSecureMethod(MockService.class, someMethodString, ROLE_B);
assertEquals(ROLE_A, mds.getAttributes(someMethodInteger, MockService.class));
assertEquals(ROLE_B, mds.getAttributes(someMethodString, MockService.class));
assertThat(mds.getAttributes(someMethodInteger, MockService.class)).isEqualTo(ROLE_A);
assertThat(mds.getAttributes(someMethodString, MockService.class)).isEqualTo(ROLE_B);
}
@SuppressWarnings("unused")

View File

@ -15,7 +15,7 @@
package org.springframework.security.access.intercept.method;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.*;
@ -80,7 +80,7 @@ public class MethodInvocationPrivilegeEvaluatorTests {
mipe.setSecurityInterceptor(interceptor);
mipe.afterPropertiesSet();
assertTrue(mipe.isAllowed(mi, token));
assertThat(mipe.isAllowed(mi, token)).isTrue();
}
@Test
@ -92,7 +92,7 @@ public class MethodInvocationPrivilegeEvaluatorTests {
mipe.setSecurityInterceptor(interceptor);
when(mds.getAttributes(mi)).thenReturn(role);
assertTrue(mipe.isAllowed(mi, token));
assertThat(mipe.isAllowed(mi, token)).isTrue();
}
@Test
@ -105,7 +105,7 @@ public class MethodInvocationPrivilegeEvaluatorTests {
when(mds.getAttributes(mi)).thenReturn(role);
doThrow(new AccessDeniedException("rejected")).when(adm).decide(token, mi, role);
assertFalse(mipe.isAllowed(mi, token));
assertThat(mipe.isAllowed(mi, token)).isFalse();
}
@Test
@ -119,6 +119,6 @@ public class MethodInvocationPrivilegeEvaluatorTests {
when(mds.getAttributes(mi)).thenReturn(role);
doThrow(new AccessDeniedException("rejected")).when(adm).decide(token, mi, role);
assertFalse(mipe.isAllowed(mi, token));
assertThat(mipe.isAllowed(mi, token)).isFalse();
}
}

View File

@ -1,6 +1,6 @@
package org.springframework.security.access.method;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.aopalliance.intercept.MethodInvocation;
@ -27,13 +27,13 @@ public class DelegatingMethodSecurityMetadataSourceTests {
.thenReturn(null);
sources.add(delegate);
mds = new DelegatingMethodSecurityMetadataSource(sources);
assertSame(sources, mds.getMethodSecurityMetadataSources());
assertTrue(mds.getAllConfigAttributes().isEmpty());
assertThat(mds.getMethodSecurityMetadataSources()).isSameAs(sources);
assertThat(mds.getAllConfigAttributes().isEmpty()).isTrue();
MethodInvocation mi = new SimpleMethodInvocation(null,
String.class.getMethod("toString"));
assertEquals(Collections.emptyList(), mds.getAttributes(mi));
assertThat(mds.getAttributes(mi)).isEqualTo(Collections.emptyList());
// Exercise the cached case
assertEquals(Collections.emptyList(), mds.getAttributes(mi));
assertThat(mds.getAttributes(mi)).isEqualTo(Collections.emptyList());
}
@Test
@ -46,15 +46,14 @@ public class DelegatingMethodSecurityMetadataSourceTests {
when(delegate.getAttributes(toString, String.class)).thenReturn(attributes);
sources.add(delegate);
mds = new DelegatingMethodSecurityMetadataSource(sources);
assertSame(sources, mds.getMethodSecurityMetadataSources());
assertTrue(mds.getAllConfigAttributes().isEmpty());
assertThat(mds.getMethodSecurityMetadataSources()).isSameAs(sources);
assertThat(mds.getAllConfigAttributes().isEmpty()).isTrue();
MethodInvocation mi = new SimpleMethodInvocation("", toString);
assertSame(attributes, mds.getAttributes(mi));
assertThat(mds.getAttributes(mi)).isSameAs(attributes);
// Exercise the cached case
assertSame(attributes, mds.getAttributes(mi));
assertTrue(mds.getAttributes(
new SimpleMethodInvocation(null, String.class.getMethod("length")))
.isEmpty());
assertThat(mds.getAttributes(mi)).isSameAs(attributes);
assertThat(mds.getAttributes(
new SimpleMethodInvocation(null, String.class.getMethod("length")))).isEmpty();;
}
}

View File

@ -1,6 +1,6 @@
package org.springframework.security.access.prepost;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.Before;
@ -24,17 +24,17 @@ public class PreInvocationAuthorizationAdviceVoterTests {
@Test
public void supportsMethodInvocation() {
assertTrue(voter.supports(MethodInvocation.class));
assertThat(voter.supports(MethodInvocation.class)).isTrue();
}
// SEC-2031
@Test
public void supportsProxyMethodInvocation() {
assertTrue(voter.supports(ProxyMethodInvocation.class));
assertThat(voter.supports(ProxyMethodInvocation.class)).isTrue();
}
@Test
public void supportsMethodInvocationAdapter() {
assertTrue(voter.supports(MethodInvocationAdapter.class));
assertThat(voter.supports(MethodInvocationAdapter.class)).isTrue();
}
}

View File

@ -15,6 +15,8 @@
package org.springframework.security.access.vote;
import static org.assertj.core.api.Assertions.assertThat;
import junit.framework.TestCase;
import org.springframework.security.access.AccessDecisionVoter;
@ -45,9 +47,9 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
DenyAgainVoter denyVoter = new DenyAgainVoter();
list.add(denyVoter);
MockDecisionManagerImpl mock = new MockDecisionManagerImpl(list);
assertTrue(!mock.isAllowIfAllAbstainDecisions()); // default
assertThat(!mock.isAllowIfAllAbstainDecisions()).isTrue(); // default
mock.setAllowIfAllAbstainDecisions(true);
assertTrue(mock.isAllowIfAllAbstainDecisions()); // changed
assertThat(mock.isAllowIfAllAbstainDecisions()).isTrue(); // changed
}
public void testDelegatesSupportsClassRequests() throws Exception {
@ -57,8 +59,8 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
MockDecisionManagerImpl mock = new MockDecisionManagerImpl(list);
assertTrue(mock.supports(String.class));
assertTrue(!mock.supports(Integer.class));
assertThat(mock.supports(String.class)).isTrue();
assertThat(!mock.supports(Integer.class)).isTrue();
}
public void testDelegatesSupportsRequests() throws Exception {
@ -71,10 +73,10 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
MockDecisionManagerImpl mock = new MockDecisionManagerImpl(list);
ConfigAttribute attr = new SecurityConfig("DENY_AGAIN_FOR_SURE");
assertTrue(mock.supports(attr));
assertThat(mock.supports(attr)).isTrue();
ConfigAttribute badAttr = new SecurityConfig("WE_DONT_SUPPORT_THIS");
assertTrue(!mock.supports(badAttr));
assertThat(!mock.supports(badAttr)).isTrue();
}
public void testProperlyStoresListOfVoters() throws Exception {
@ -84,7 +86,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
list.add(voter);
list.add(denyVoter);
MockDecisionManagerImpl mock = new MockDecisionManagerImpl(list);
assertEquals(list.size(), mock.getDecisionVoters().size());
assertThat(mock.getDecisionVoters().size()).isEqualTo(list.size());
}
public void testRejectsEmptyList() throws Exception {
@ -95,7 +97,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
@ -105,13 +107,13 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testRoleVoterAlwaysReturnsTrueToSupports() {
RoleVoter rv = new RoleVoter();
assertTrue(rv.supports(String.class));
assertThat(rv.supports(String.class)).isTrue();
}
public void testWillNotStartIfDecisionVotersNotSet() throws Exception {
@ -120,7 +122,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
}

View File

@ -1,6 +1,6 @@
package org.springframework.security.access.vote;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.*;
@ -28,8 +28,8 @@ public class AbstractAclVoterTests {
@Test
public void supportsMethodInvocations() throws Exception {
assertTrue(voter.supports(MethodInvocation.class));
assertFalse(voter.supports(String.class));
assertThat(voter.supports(MethodInvocation.class)).isTrue();
assertThat(voter.supports(String.class)).isFalse();
}
@Test
@ -38,7 +38,7 @@ public class AbstractAclVoterTests {
voter.setProcessDomainObjectClass(String.class);
MethodInvocation mi = MethodInvocationUtils.create(new TestClass(),
"methodTakingAString", "The Argument");
assertEquals("The Argument", voter.getDomainObjectInstance(mi));
assertThat(voter.getDomainObjectInstance(mi)).isEqualTo("The Argument");
}
@Test
@ -46,7 +46,7 @@ public class AbstractAclVoterTests {
voter.setProcessDomainObjectClass(String.class);
MethodInvocation mi = MethodInvocationUtils.create(new TestClass(),
"methodTakingAListAndAString", new ArrayList<Object>(), "The Argument");
assertEquals("The Argument", voter.getDomainObjectInstance(mi));
assertThat(voter.getDomainObjectInstance(mi)).isEqualTo("The Argument");
}
@SuppressWarnings("unused")

View File

@ -15,7 +15,8 @@
package org.springframework.security.access.vote;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
@ -97,7 +98,7 @@ public class AffirmativeBasedTests {
public void onlyAbstainVotesDeniesAccessWithDefault() throws Exception {
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>> asList(
abstain, abstain, abstain));
assertTrue(!mgr.isAllowIfAllAbstainDecisions()); // check default
assertThat(!mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
mgr.decide(user, new Object(), attrs);
}
@ -108,7 +109,7 @@ public class AffirmativeBasedTests {
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>> asList(
abstain, abstain, abstain));
mgr.setAllowIfAllAbstainDecisions(true);
assertTrue(mgr.isAllowIfAllAbstainDecisions()); // check changed
assertThat(mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check changed
mgr.decide(user, new Object(), attrs);
}

View File

@ -15,6 +15,8 @@
package org.springframework.security.access.vote;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import junit.framework.TestCase;
@ -95,19 +97,19 @@ public class AuthenticatedVoterTests extends TestCase {
fail("Expected IAE");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testSupports() {
AuthenticatedVoter voter = new AuthenticatedVoter();
assertTrue(voter.supports(String.class));
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)));
assertFalse(voter.supports(new SecurityConfig("FOO")));
assertThat(voter.supports(new SecurityConfig("FOO"))).isFalse();
}
}

View File

@ -15,7 +15,7 @@
package org.springframework.security.access.vote;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.*;
import org.springframework.security.access.AccessDecisionVoter;
@ -39,7 +39,7 @@ public class ConsensusBasedTests {
TestingAuthenticationToken auth = makeTestToken();
ConsensusBased mgr = makeDecisionManager();
mgr.setAllowIfEqualGrantedDeniedDecisions(false);
assertTrue(!mgr.isAllowIfEqualGrantedDeniedDecisions()); // check changed
assertThat(!mgr.isAllowIfEqualGrantedDeniedDecisions()).isTrue(); // check changed
List<ConfigAttribute> config = SecurityConfig.createList("ROLE_1",
"DENY_FOR_SURE");
@ -53,13 +53,13 @@ public class ConsensusBasedTests {
TestingAuthenticationToken auth = makeTestToken();
ConsensusBased mgr = makeDecisionManager();
assertTrue(mgr.isAllowIfEqualGrantedDeniedDecisions()); // check default
assertThat(mgr.isAllowIfEqualGrantedDeniedDecisions()).isTrue(); // check default
List<ConfigAttribute> config = SecurityConfig.createList("ROLE_1",
"DENY_FOR_SURE");
mgr.decide(auth, new Object(), config);
assertTrue(true);
}
@Test
@ -68,7 +68,7 @@ public class ConsensusBasedTests {
ConsensusBased mgr = makeDecisionManager();
mgr.decide(auth, new Object(), SecurityConfig.createList("ROLE_2"));
assertTrue(true);
}
@Test(expected = AccessDeniedException.class)
@ -85,7 +85,7 @@ public class ConsensusBasedTests {
TestingAuthenticationToken auth = makeTestToken();
ConsensusBased mgr = makeDecisionManager();
assertTrue(!mgr.isAllowIfAllAbstainDecisions()); // check default
assertThat(!mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
mgr.decide(auth, new Object(), SecurityConfig.createList("IGNORED_BY_ALL"));
}
@ -95,7 +95,7 @@ public class ConsensusBasedTests {
TestingAuthenticationToken auth = makeTestToken();
ConsensusBased mgr = makeDecisionManager();
mgr.setAllowIfAllAbstainDecisions(true);
assertTrue(mgr.isAllowIfAllAbstainDecisions()); // check changed
assertThat(mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check changed
mgr.decide(auth, new Object(), SecurityConfig.createList("IGNORED_BY_ALL"));
}

View File

@ -1,6 +1,6 @@
package org.springframework.security.access.vote;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.springframework.security.access.SecurityConfig;
@ -20,7 +20,6 @@ public class RoleHierarchyVoterTests {
"password", "ROLE_A");
RoleHierarchyVoter voter = new RoleHierarchyVoter(roleHierarchyImpl);
assertEquals(RoleHierarchyVoter.ACCESS_GRANTED,
voter.vote(auth, new Object(), SecurityConfig.createList("ROLE_B")));
assertThat(voter.vote(auth, new Object(), SecurityConfig.createList("ROLE_B"))).isEqualTo(RoleHierarchyVoter.ACCESS_GRANTED);
}
}

View File

@ -1,7 +1,6 @@
package org.springframework.security.access.vote;
import static org.fest.assertions.Assertions.assertThat;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.security.access.AccessDecisionVoter;
@ -20,8 +19,7 @@ public class RoleVoterTests {
voter.setRolePrefix("");
Authentication userAB = new TestingAuthenticationToken("user", "pass", "A", "B");
// Vote on attribute list that has two attributes A and C (i.e. only one matching)
assertEquals(AccessDecisionVoter.ACCESS_GRANTED,
voter.vote(userAB, this, SecurityConfig.createList("A", "C")));
assertThat(voter.vote(userAB, this, SecurityConfig.createList("A", "C"))).isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
}
// SEC-3128

View File

@ -15,6 +15,8 @@
package org.springframework.security.access.vote;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.Vector;
@ -84,7 +86,6 @@ public class UnanimousBasedTests extends TestCase {
fail("Should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
assertTrue(true);
}
}
@ -95,7 +96,6 @@ public class UnanimousBasedTests extends TestCase {
List<ConfigAttribute> config = SecurityConfig.createList("ROLE_2");
mgr.decide(auth, new Object(), config);
assertTrue(true);
}
public void testOneDenyVoteTwoAbstainVotesDeniesAccess() throws Exception {
@ -109,7 +109,6 @@ public class UnanimousBasedTests extends TestCase {
fail("Should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
assertTrue(true);
}
}
@ -121,14 +120,13 @@ public class UnanimousBasedTests extends TestCase {
"FOOBAR_1", "FOOBAR_2" });
mgr.decide(auth, new Object(), config);
assertTrue(true);
}
public void testThreeAbstainVotesDeniesAccessWithDefault() throws Exception {
TestingAuthenticationToken auth = makeTestToken();
UnanimousBased mgr = makeDecisionManager();
assertTrue(!mgr.isAllowIfAllAbstainDecisions()); // check default
assertThat(!mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
List<ConfigAttribute> config = SecurityConfig.createList("IGNORED_BY_ALL");
@ -137,7 +135,6 @@ public class UnanimousBasedTests extends TestCase {
fail("Should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
assertTrue(true);
}
}
@ -145,12 +142,11 @@ public class UnanimousBasedTests extends TestCase {
TestingAuthenticationToken auth = makeTestToken();
UnanimousBased mgr = makeDecisionManager();
mgr.setAllowIfAllAbstainDecisions(true);
assertTrue(mgr.isAllowIfAllAbstainDecisions()); // check changed
assertThat(mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check changed
List<ConfigAttribute> config = SecurityConfig.createList("IGNORED_BY_ALL");
mgr.decide(auth, new Object(), config);
assertTrue(true);
}
public void testTwoAffirmativeVotesTwoAbstainVotesGrantsAccess() throws Exception {
@ -161,6 +157,5 @@ public class UnanimousBasedTests extends TestCase {
"ROLE_2" });
mgr.decide(auth, new Object(), config);
assertTrue(true);
}
}

View File

@ -15,7 +15,7 @@
package org.springframework.security.authentication;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.*;
import org.springframework.security.core.GrantedAuthority;
@ -49,7 +49,7 @@ public class AbstractAuthenticationTokenTests {
authorities);
List<GrantedAuthority> gotAuthorities = (List<GrantedAuthority>) token
.getAuthorities();
assertNotSame(authorities, gotAuthorities);
assertThat(gotAuthorities).isNotSameAs(authorities);
gotAuthorities.set(0, new SimpleGrantedAuthority("ROLE_SUPER_USER"));
}
@ -58,9 +58,9 @@ public class AbstractAuthenticationTokenTests {
public void testGetters() throws Exception {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password",
authorities);
assertEquals("Test", token.getPrincipal());
assertEquals("Password", token.getCredentials());
assertEquals("Test", token.getName());
assertThat(token.getPrincipal()).isEqualTo("Test");
assertThat(token.getCredentials()).isEqualTo("Password");
assertThat(token.getName()).isEqualTo("Test");
}
@Test
@ -71,12 +71,12 @@ public class AbstractAuthenticationTokenTests {
authorities);
MockAuthenticationImpl token3 = new MockAuthenticationImpl(null, null,
AuthorityUtils.NO_AUTHORITIES);
assertEquals(token1.hashCode(), token2.hashCode());
assertTrue(token1.hashCode() != token3.hashCode());
assertThat(token2.hashCode()).isEqualTo(token1.hashCode());
assertThat(token1.hashCode() != token3.hashCode()).isTrue();
token2.setAuthenticated(true);
assertTrue(token1.hashCode() != token2.hashCode());
assertThat(token1.hashCode() != token2.hashCode()).isTrue();
}
@Test
@ -85,53 +85,53 @@ public class AbstractAuthenticationTokenTests {
authorities);
MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test", "Password",
authorities);
assertEquals(token1, token2);
assertThat(token2).isEqualTo(token1);
MockAuthenticationImpl token3 = new MockAuthenticationImpl("Test",
"Password_Changed", authorities);
assertTrue(!token1.equals(token3));
assertThat(!token1.equals(token3)).isTrue();
MockAuthenticationImpl token4 = new MockAuthenticationImpl("Test_Changed",
"Password", authorities);
assertTrue(!token1.equals(token4));
assertThat(!token1.equals(token4)).isTrue();
MockAuthenticationImpl token5 = new MockAuthenticationImpl("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO_CHANGED"));
assertTrue(!token1.equals(token5));
assertThat(!token1.equals(token5)).isTrue();
MockAuthenticationImpl token6 = new MockAuthenticationImpl("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE"));
assertTrue(!token1.equals(token6));
assertThat(!token1.equals(token6)).isTrue();
MockAuthenticationImpl token7 = new MockAuthenticationImpl("Test", "Password",
null);
assertTrue(!token1.equals(token7));
assertTrue(!token7.equals(token1));
assertThat(!token1.equals(token7)).isTrue();
assertThat(!token7.equals(token1)).isTrue();
assertTrue(!token1.equals(Integer.valueOf(100)));
assertThat(!token1.equals(Integer.valueOf(100))).isTrue();
}
@Test
public void testSetAuthenticated() throws Exception {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password",
authorities);
assertTrue(!token.isAuthenticated());
assertThat(!token.isAuthenticated()).isTrue();
token.setAuthenticated(true);
assertTrue(token.isAuthenticated());
assertThat(token.isAuthenticated()).isTrue();
}
@Test
public void testToStringWithAuthorities() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password",
authorities);
assertTrue(token.toString().lastIndexOf("ROLE_TWO") != -1);
assertThat(token.toString().lastIndexOf("ROLE_TWO") != -1).isTrue();
}
@Test
public void testToStringWithNullAuthorities() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password",
null);
assertTrue(token.toString().lastIndexOf("Not granted any authorities") != -1);
assertThat(token.toString().lastIndexOf("Not granted any authorities") != -1).isTrue();
}
// ~ Inner Classes

View File

@ -15,6 +15,8 @@
package org.springframework.security.authentication;
import static org.assertj.core.api.Assertions.assertThat;
import junit.framework.TestCase;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
@ -56,11 +58,11 @@ public class AuthenticationTrustResolverImplTests extends TestCase {
assertEquals(AnonymousAuthenticationToken.class,
trustResolver.getAnonymousClass());
trustResolver.setAnonymousClass(TestingAuthenticationToken.class);
assertEquals(TestingAuthenticationToken.class, trustResolver.getAnonymousClass());
assertThat(trustResolver.getAnonymousClass()).isEqualTo(TestingAuthenticationToken.class);
assertEquals(RememberMeAuthenticationToken.class,
trustResolver.getRememberMeClass());
trustResolver.setRememberMeClass(TestingAuthenticationToken.class);
assertEquals(TestingAuthenticationToken.class, trustResolver.getRememberMeClass());
assertThat(trustResolver.getRememberMeClass()).isEqualTo(TestingAuthenticationToken.class);
}
}

View File

@ -15,7 +15,7 @@
package org.springframework.security.authentication;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
@ -59,12 +59,12 @@ public class ProviderManagerTests {
"Test", "Password");
ProviderManager mgr = makeProviderManager();
Authentication result = mgr.authenticate(token);
assertNull(result.getCredentials());
assertThat(result.getCredentials()).isNull();
mgr.setEraseCredentialsAfterAuthentication(false);
token = new UsernamePasswordAuthenticationToken("Test", "Password");
result = mgr.authenticate(token);
assertNotNull(result.getCredentials());
assertThat(result.getCredentials()).isNotNull();
}
@Test
@ -77,7 +77,7 @@ public class ProviderManagerTests {
mgr.setAuthenticationEventPublisher(publisher);
Authentication result = mgr.authenticate(a);
assertEquals(a, result);
assertThat(result).isEqualTo(a);
verify(publisher).publishAuthenticationSuccess(result);
}
@ -90,7 +90,7 @@ public class ProviderManagerTests {
mgr.setAuthenticationEventPublisher(publisher);
Authentication result = mgr.authenticate(a);
assertSame(a, result);
assertThat(result).isSameAs(a);
verify(publisher).publishAuthenticationSuccess(result);
}
@ -124,7 +124,7 @@ public class ProviderManagerTests {
request.setDetails(requestDetails);
Authentication result = authMgr.authenticate(request);
assertEquals(resultDetails, result.getDetails());
assertThat(result.getDetails()).isEqualTo(resultDetails);
}
@Test
@ -137,8 +137,8 @@ public class ProviderManagerTests {
request.setDetails(details);
Authentication result = authMgr.authenticate(request);
assertNotNull(result.getCredentials());
assertSame(details, result.getDetails());
assertThat(result.getCredentials()).isNotNull();
assertThat(result.getDetails()).isSameAs(details);
}
@Test
@ -148,7 +148,7 @@ public class ProviderManagerTests {
ProviderManager mgr = new ProviderManager(
Arrays.asList(createProviderWhichThrows(new BadCredentialsException("",
new Throwable())), createProviderWhichReturns(authReq)));
assertSame(authReq, mgr.authenticate(mock(Authentication.class)));
assertThat(mgr.authenticate(mock(Authentication.class))).isSameAs(authReq);
}
@Test
@ -194,7 +194,7 @@ public class ProviderManagerTests {
when(parent.authenticate(authReq)).thenReturn(authReq);
ProviderManager mgr = new ProviderManager(
Arrays.asList(mock(AuthenticationProvider.class)), parent);
assertSame(authReq, mgr.authenticate(authReq));
assertThat(mgr.authenticate(authReq)).isSameAs(authReq);
}
@Test
@ -256,7 +256,7 @@ public class ProviderManagerTests {
fail("Expected exception");
}
catch (BadCredentialsException e) {
assertSame(expected, e);
assertThat(e).isSameAs(expected);
}
verify(publisher).publishAuthenticationFailure(expected, authReq);
}
@ -276,7 +276,7 @@ public class ProviderManagerTests {
fail("Expected exception");
}
catch (LockedException e) {
assertSame(expected, e);
assertThat(e).isSameAs(expected);
}
verify(publisher).publishAuthenticationFailure(expected, authReq);
}

View File

@ -15,6 +15,8 @@
package org.springframework.security.authentication;
import static org.assertj.core.api.Assertions.assertThat;
import junit.framework.TestCase;
import org.springframework.security.authentication.TestingAuthenticationProvider;
@ -35,20 +37,17 @@ public class TestingAuthenticationProviderTests extends TestCase {
"Password", "ROLE_ONE", "ROLE_TWO");
Authentication result = provider.authenticate(token);
assertTrue(result instanceof TestingAuthenticationToken);
assertThat(result instanceof TestingAuthenticationToken).isTrue();
TestingAuthenticationToken castResult = (TestingAuthenticationToken) result;
assertEquals("Test", castResult.getPrincipal());
assertEquals("Password", castResult.getCredentials());
assertTrue(AuthorityUtils.authorityListToSet(castResult.getAuthorities())
.contains("ROLE_ONE"));
assertTrue(AuthorityUtils.authorityListToSet(castResult.getAuthorities())
.contains("ROLE_TWO"));
assertThat(castResult.getPrincipal()).isEqualTo("Test");
assertThat(castResult.getCredentials()).isEqualTo("Password");
assertThat(AuthorityUtils.authorityListToSet(castResult.getAuthorities())).contains("ROLE_ONE","ROLE_TWO");
}
public void testSupports() {
TestingAuthenticationProvider provider = new TestingAuthenticationProvider();
assertTrue(provider.supports(TestingAuthenticationToken.class));
assertTrue(!provider.supports(String.class));
assertThat(provider.supports(TestingAuthenticationToken.class)).isTrue();
assertThat(!provider.supports(String.class)).isTrue();
}
}

View File

@ -15,9 +15,9 @@
package org.springframework.security.authentication;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.fail;
import org.junit.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@ -40,22 +40,22 @@ public class UsernamePasswordAuthenticationTokenTests {
// check default given we passed some GrantedAuthorty[]s (well, we passed empty
// list)
assertTrue(token.isAuthenticated());
assertThat(token.isAuthenticated()).isTrue();
// check explicit set to untrusted (we can safely go from trusted to untrusted,
// but not the reverse)
token.setAuthenticated(false);
assertTrue(!token.isAuthenticated());
assertThat(!token.isAuthenticated()).isTrue();
// Now let's create a UsernamePasswordAuthenticationToken without any
// GrantedAuthorty[]s (different constructor)
token = new UsernamePasswordAuthenticationToken("Test", "Password");
assertTrue(!token.isAuthenticated());
assertThat(!token.isAuthenticated()).isTrue();
// check we're allowed to still set it to untrusted
token.setAuthenticated(false);
assertTrue(!token.isAuthenticated());
assertThat(!token.isAuthenticated()).isTrue();
// check denied changing it to trusted
try {
@ -71,11 +71,11 @@ public class UsernamePasswordAuthenticationTokenTests {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE",
"ROLE_TWO"));
assertEquals("Test", token.getPrincipal());
assertEquals("Password", token.getCredentials());
assertTrue(AuthorityUtils.authorityListToSet(token.getAuthorities()).contains(
assertThat(token.getPrincipal()).isEqualTo("Test");
assertThat(token.getCredentials()).isEqualTo("Password");
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities()).contains(
"ROLE_ONE"));
assertTrue(AuthorityUtils.authorityListToSet(token.getAuthorities()).contains(
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities()).contains(
"ROLE_TWO"));
}

View File

@ -15,7 +15,7 @@
package org.springframework.security.authentication.anonymous;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.*;
import org.springframework.security.authentication.AnonymousAuthenticationProvider;
@ -59,7 +59,7 @@ public class AnonymousAuthenticationProviderTests {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
@ -67,7 +67,7 @@ public class AnonymousAuthenticationProviderTests {
public void testGettersSetters() throws Exception {
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider(
"qwerty");
assertEquals("qwerty", aap.getKey());
assertThat(aap.getKey()).isEqualTo("qwerty");
}
@Test
@ -77,10 +77,10 @@ public class AnonymousAuthenticationProviderTests {
TestingAuthenticationToken token = new TestingAuthenticationToken("user",
"password", "ROLE_A");
assertFalse(aap.supports(TestingAuthenticationToken.class));
assertThat(aap.supports(TestingAuthenticationToken.class)).isFalse();
// Try it anyway
assertNull(aap.authenticate(token));
assertThat(aap.authenticate(token)).isNull();
}
@Test
@ -93,14 +93,14 @@ public class AnonymousAuthenticationProviderTests {
Authentication result = aap.authenticate(token);
assertEquals(result, token);
assertThat(token).isEqualTo(result);
}
@Test
public void testSupports() {
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider(
"qwerty");
assertTrue(aap.supports(AnonymousAuthenticationToken.class));
assertFalse(aap.supports(TestingAuthenticationToken.class));
assertThat(aap.supports(AnonymousAuthenticationToken.class)).isTrue();
assertThat(aap.supports(TestingAuthenticationToken.class)).isFalse();
}
}

View File

@ -15,6 +15,8 @@
package org.springframework.security.authentication.anonymous;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import junit.framework.TestCase;
@ -73,21 +75,19 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("key",
"Test", ROLES_12);
assertEquals(token1, token2);
assertThat(token2).isEqualTo(token1);
}
public void testGetters() {
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key",
"Test", ROLES_12);
assertEquals("key".hashCode(), token.getKeyHash());
assertEquals("Test", token.getPrincipal());
assertEquals("", token.getCredentials());
assertTrue(AuthorityUtils.authorityListToSet(token.getAuthorities()).contains(
"ROLE_ONE"));
assertTrue(AuthorityUtils.authorityListToSet(token.getAuthorities()).contains(
"ROLE_TWO"));
assertTrue(token.isAuthenticated());
assertThat(token.getKeyHash()).isEqualTo("key".hashCode());
assertThat(token.getPrincipal()).isEqualTo("Test");
assertThat(token.getCredentials()).isEqualTo("");
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains(
"ROLE_ONE","ROLE_TWO");
assertThat(token.isAuthenticated()).isTrue();
}
public void testNoArgConstructorDoesntExist() {
@ -107,7 +107,7 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken("key",
"DIFFERENT_PRINCIPAL", ROLES_12);
assertFalse(token1.equals(token2));
assertThat(token1.equals(token2)).isFalse();
}
public void testNotEqualsDueToDifferentAuthenticationClass() {
@ -116,7 +116,7 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken(
"Test", "Password", ROLES_12);
assertFalse(token1.equals(token2));
assertThat(token1.equals(token2)).isFalse();
}
public void testNotEqualsDueToKey() {
@ -126,14 +126,14 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
AnonymousAuthenticationToken token2 = new AnonymousAuthenticationToken(
"DIFFERENT_KEY", "Test", ROLES_12);
assertFalse(token1.equals(token2));
assertThat(token1.equals(token2)).isFalse();
}
public void testSetAuthenticatedIgnored() {
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key",
"Test", ROLES_12);
assertTrue(token.isAuthenticated());
assertThat(token.isAuthenticated()).isTrue();
token.setAuthenticated(false);
assertTrue(!token.isAuthenticated());
assertThat(!token.isAuthenticated()).isTrue();
}
}

View File

@ -15,6 +15,8 @@
package org.springframework.security.authentication.dao;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;
@ -77,7 +79,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
assertTrue(true);
}
}
@ -94,7 +96,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
fail("Expected BadCredenialsException");
}
catch (BadCredentialsException expected) {
assertTrue(true);
}
}
@ -111,7 +113,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
fail("Should have thrown AccountExpiredException");
}
catch (AccountExpiredException expected) {
assertTrue(true);
}
}
@ -128,7 +130,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
fail("Should have thrown LockedException");
}
catch (LockedException expected) {
assertTrue(true);
}
}
@ -145,7 +147,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
fail("Should have thrown CredentialsExpiredException");
}
catch (CredentialsExpiredException expected) {
assertTrue(true);
}
// Check that wrong password causes BadCredentialsException, rather than
@ -157,7 +159,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
assertTrue(true);
}
}
@ -174,7 +176,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
fail("Should have thrown DisabledException");
}
catch (DisabledException expected) {
assertTrue(true);
}
}
@ -207,7 +209,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
assertTrue(true);
}
}
@ -224,7 +226,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
assertTrue(true);
}
}
@ -243,7 +245,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
fail("Should have thrown UsernameNotFoundException");
}
catch (UsernameNotFoundException expected) {
assertTrue(true);
}
}
@ -252,7 +254,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
"INVALID_USER", "koala");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
assertTrue(provider.isHideUserNotFoundExceptions());
assertThat(provider.isHideUserNotFoundExceptions()).isTrue();
provider.setUserDetailsService(new MockAuthenticationDaoUserrod());
provider.setUserCache(new MockUserCache());
@ -261,7 +263,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
assertTrue(true);
}
}
@ -278,7 +280,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
assertTrue(true);
}
}
@ -298,13 +300,11 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result;
assertEquals(User.class, castResult.getPrincipal().getClass());
assertEquals("koala", castResult.getCredentials());
assertTrue(AuthorityUtils.authorityListToSet(castResult.getAuthorities())
.contains("ROLE_ONE"));
assertTrue(AuthorityUtils.authorityListToSet(castResult.getAuthorities())
.contains("ROLE_TWO"));
assertEquals("192.168.0.1", castResult.getDetails());
assertThat(castResult.getPrincipal().getClass()).isEqualTo(User.class);
assertThat(castResult.getCredentials()).isEqualTo("koala");
assertThat(AuthorityUtils.authorityListToSet(castResult.getAuthorities()))
.contains("ROLE_ONE","ROLE_TWO");
assertThat(castResult.getDetails()).isEqualTo("192.168.0.1");
}
public void testAuthenticatesASecondTime() {
@ -328,7 +328,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
fail("Should have returned instance of UsernamePasswordAuthenticationToken");
}
assertEquals(result.getCredentials(), result2.getCredentials());
assertThat(result2.getCredentials()).isEqualTo(result.getCredentials());
}
public void testAuthenticatesWhenASaltIsUsed() {
@ -349,14 +349,12 @@ public class DaoAuthenticationProviderTests extends TestCase {
fail("Should have returned instance of UsernamePasswordAuthenticationToken");
}
assertEquals(User.class, result.getPrincipal().getClass());
assertThat(result.getPrincipal().getClass()).isEqualTo(User.class);
// We expect original credentials user submitted to be returned
assertEquals("koala", result.getCredentials());
assertTrue(AuthorityUtils.authorityListToSet(result.getAuthorities()).contains(
"ROLE_ONE"));
assertTrue(AuthorityUtils.authorityListToSet(result.getAuthorities()).contains(
"ROLE_TWO"));
assertThat(result.getCredentials()).isEqualTo("koala");
assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities()))
.contains("ROLE_ONE","ROLE_TWO");
}
public void testAuthenticatesWithForcePrincipalAsString() {
@ -375,8 +373,8 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result;
assertEquals(String.class, castResult.getPrincipal().getClass());
assertEquals("rod", castResult.getPrincipal());
assertThat(castResult.getPrincipal().getClass()).isEqualTo(String.class);
assertThat(castResult.getPrincipal()).isEqualTo("rod");
}
public void testDetectsNullBeingReturnedFromAuthenticationDao() {
@ -400,17 +398,17 @@ public class DaoAuthenticationProviderTests extends TestCase {
public void testGettersSetters() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(new ShaPasswordEncoder());
assertEquals(ShaPasswordEncoder.class, provider.getPasswordEncoder().getClass());
assertThat(provider.getPasswordEncoder().getClass()).isEqualTo(ShaPasswordEncoder.class);
provider.setSaltSource(new SystemWideSaltSource());
assertEquals(SystemWideSaltSource.class, provider.getSaltSource().getClass());
assertThat(provider.getSaltSource().getClass()).isEqualTo(SystemWideSaltSource.class);
provider.setUserCache(new EhCacheBasedUserCache());
assertEquals(EhCacheBasedUserCache.class, provider.getUserCache().getClass());
assertThat(provider.getUserCache().getClass()).isEqualTo(EhCacheBasedUserCache.class);
assertFalse(provider.isForcePrincipalAsString());
assertThat(provider.isForcePrincipalAsString()).isFalse();
provider.setForcePrincipalAsString(true);
assertTrue(provider.isForcePrincipalAsString());
assertThat(provider.isForcePrincipalAsString()).isTrue();
}
public void testGoesBackToAuthenticationDaoToObtainLatestPasswordIfCachedPasswordSeemsIncorrect() {
@ -427,7 +425,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
provider.authenticate(token);
// Check "rod = koala" ended up in the cache
assertEquals("koala", cache.getUserFromCache("rod").getPassword());
assertThat(cache.getUserFromCache("rod").getPassword()).isEqualTo("koala");
// Now change the password the AuthenticationDao will return
authenticationDao.setPassword("easternLongNeckTurtle");
@ -438,7 +436,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
// To get this far, the new password was accepted
// Check the cache was updated
assertEquals("easternLongNeckTurtle", cache.getUserFromCache("rod").getPassword());
assertThat(cache.getUserFromCache("rod").getPassword()).isEqualTo("easternLongNeckTurtle");
}
public void testStartupFailsIfNoAuthenticationDao() throws Exception {
@ -449,14 +447,14 @@ public class DaoAuthenticationProviderTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testStartupFailsIfNoUserCacheSet() throws Exception {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(new MockAuthenticationDaoUserrod());
assertEquals(NullUserCache.class, provider.getUserCache().getClass());
assertThat(provider.getUserCache().getClass()).isEqualTo(NullUserCache.class);
provider.setUserCache(null);
try {
@ -464,7 +462,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
@ -473,15 +471,15 @@ public class DaoAuthenticationProviderTests extends TestCase {
UserDetailsService userDetailsService = new MockAuthenticationDaoUserrod();
provider.setUserDetailsService(userDetailsService);
provider.setUserCache(new MockUserCache());
assertEquals(userDetailsService, provider.getUserDetailsService());
assertThat(provider.getUserDetailsService()).isEqualTo(userDetailsService);
provider.afterPropertiesSet();
assertTrue(true);
}
public void testSupports() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
assertTrue(provider.supports(UsernamePasswordAuthenticationToken.class));
assertTrue(!provider.supports(TestingAuthenticationToken.class));
assertThat(provider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
assertThat(!provider.supports(TestingAuthenticationToken.class)).isTrue();
}
// SEC-2056

View File

@ -55,13 +55,13 @@ public class ReflectionSaltSourceTests {
ReflectionSaltSource saltSource = new ReflectionSaltSource();
saltSource.setUserPropertyToUse("getUsername");
assertEquals("scott", saltSource.getSalt(user));
assertThat(saltSource.getSalt(user)).isEqualTo("scott");
}
@Test
public void propertyNameAsPropertyToUseReturnsCorrectSaltValue() {
ReflectionSaltSource saltSource = new ReflectionSaltSource();
saltSource.setUserPropertyToUse("password");
assertEquals("wombat", saltSource.getSalt(user));
assertThat(saltSource.getSalt(user)).isEqualTo("wombat");
}
}

View File

@ -15,7 +15,7 @@
package org.springframework.security.authentication.dao.salt;
import static org.fest.assertions.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import org.springframework.security.authentication.dao.SystemWideSaltSource;
@ -57,21 +57,21 @@ public class SystemWideSaltSourceTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertEquals("A systemWideSalt must be set", expected.getMessage());
assertThat(expected.getMessage()).isEqualTo("A systemWideSalt must be set");
}
}
public void testGettersSetters() {
SystemWideSaltSource saltSource = new SystemWideSaltSource();
saltSource.setSystemWideSalt("helloWorld");
assertEquals("helloWorld", saltSource.getSystemWideSalt());
assertThat(saltSource.getSystemWideSalt()).isEqualTo("helloWorld");
}
public void testNormalOperation() throws Exception {
SystemWideSaltSource saltSource = new SystemWideSaltSource();
saltSource.setSystemWideSalt("helloWorld");
saltSource.afterPropertiesSet();
assertEquals("helloWorld", saltSource.getSalt(null));
assertThat(saltSource.getSalt(null)).isEqualTo("helloWorld");
}
// SEC-2173

View File

@ -34,14 +34,14 @@ public class BasePasswordEncoderTests extends TestCase {
String merged = pwd.nowMergePasswordAndSalt("password", null, true);
String[] demerged = pwd.nowDemergePasswordAndSalt(merged);
assertEquals("password", demerged[0]);
assertEquals("", demerged[1]);
assertThat(demerged[0]).isEqualTo("password");
assertThat(demerged[1]).isEqualTo("");
merged = pwd.nowMergePasswordAndSalt("password", "", true);
demerged = pwd.nowDemergePasswordAndSalt(merged);
assertEquals("password", demerged[0]);
assertEquals("", demerged[1]);
assertThat(demerged[0]).isEqualTo("password");
assertThat(demerged[1]).isEqualTo("");
}
public void testDemergeWithEmptyStringIsRejected() {
@ -52,7 +52,7 @@ public class BasePasswordEncoderTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertEquals("Cannot pass a null or empty String", expected.getMessage());
assertThat(expected.getMessage()).isEqualTo("Cannot pass a null or empty String");
}
}
@ -64,7 +64,7 @@ public class BasePasswordEncoderTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertEquals("Cannot pass a null or empty String", expected.getMessage());
assertThat(expected.getMessage()).isEqualTo("Cannot pass a null or empty String");
}
}
@ -72,34 +72,34 @@ public class BasePasswordEncoderTests extends TestCase {
MockPasswordEncoder pwd = new MockPasswordEncoder();
String merged = pwd.nowMergePasswordAndSalt("password", "foo", true);
assertEquals("password{foo}", merged);
assertThat(merged).isEqualTo("password{foo}");
String[] demerged = pwd.nowDemergePasswordAndSalt(merged);
assertEquals("password", demerged[0]);
assertEquals("foo", demerged[1]);
assertThat(demerged[0]).isEqualTo("password");
assertThat(demerged[1]).isEqualTo("foo");
}
public void testMergeDemergeWithDelimitersInPassword() {
MockPasswordEncoder pwd = new MockPasswordEncoder();
String merged = pwd.nowMergePasswordAndSalt("p{ass{w{o}rd", "foo", true);
assertEquals("p{ass{w{o}rd{foo}", merged);
assertThat(merged).isEqualTo("p{ass{w{o}rd{foo}");
String[] demerged = pwd.nowDemergePasswordAndSalt(merged);
assertEquals("p{ass{w{o}rd", demerged[0]);
assertEquals("foo", demerged[1]);
assertThat(demerged[0]).isEqualTo("p{ass{w{o}rd");
assertThat(demerged[1]).isEqualTo("foo");
}
public void testMergeDemergeWithNullAsPassword() {
MockPasswordEncoder pwd = new MockPasswordEncoder();
String merged = pwd.nowMergePasswordAndSalt(null, "foo", true);
assertEquals("{foo}", merged);
assertThat(merged).isEqualTo("{foo}");
String[] demerged = pwd.nowDemergePasswordAndSalt(merged);
assertEquals("", demerged[0]);
assertEquals("foo", demerged[1]);
assertThat(demerged[0]).isEqualTo("");
assertThat(demerged[1]).isEqualTo("foo");
}
public void testStrictMergeRejectsDelimitersInSalt1() {
@ -110,7 +110,7 @@ public class BasePasswordEncoderTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertEquals("Cannot use { or } in salt.toString()", expected.getMessage());
assertThat(expected.getMessage()).isEqualTo("Cannot use { or } in salt.toString()");
}
}
@ -122,7 +122,7 @@ public class BasePasswordEncoderTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertEquals("Cannot use { or } in salt.toString()", expected.getMessage());
assertThat(expected.getMessage()).isEqualTo("Cannot use { or } in salt.toString()");
}
}

View File

@ -24,45 +24,45 @@ public class Md4PasswordEncoderTests extends TestCase {
Md4PasswordEncoder md4 = new Md4PasswordEncoder();
md4.setEncodeHashAsBase64(true);
String encodedPassword = md4.encodePassword("ww_uni123", null);
assertEquals("8zobtq72iAt0W6KNqavGwg==", encodedPassword);
assertThat(encodedPassword).isEqualTo("8zobtq72iAt0W6KNqavGwg==");
}
public void testEncodeSaltedPassword() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder();
md4.setEncodeHashAsBase64(true);
String encodedPassword = md4.encodePassword("ww_uni123", "Alan K Stewart");
assertEquals("ZplT6P5Kv6Rlu6W4FIoYNA==", encodedPassword);
assertThat(encodedPassword).isEqualTo("ZplT6P5Kv6Rlu6W4FIoYNA==");
}
public void testEncodeNullPassword() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder();
md4.setEncodeHashAsBase64(true);
String encodedPassword = md4.encodePassword(null, null);
assertEquals("MdbP4NFq6TG3PFnX4MCJwA==", encodedPassword);
assertThat(encodedPassword).isEqualTo("MdbP4NFq6TG3PFnX4MCJwA==");
}
public void testEncodeEmptyPassword() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder();
md4.setEncodeHashAsBase64(true);
String encodedPassword = md4.encodePassword("", null);
assertEquals("MdbP4NFq6TG3PFnX4MCJwA==", encodedPassword);
assertThat(encodedPassword).isEqualTo("MdbP4NFq6TG3PFnX4MCJwA==");
}
public void testNonAsciiPasswordHasCorrectHash() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder();
String encodedPassword = md4.encodePassword("\u4F60\u597d", null);
assertEquals("a7f1196539fd1f85f754ffd185b16e6e", encodedPassword);
assertThat(encodedPassword).isEqualTo("a7f1196539fd1f85f754ffd185b16e6e");
}
public void testIsHexPasswordValid() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder();
assertTrue(md4.isPasswordValid("31d6cfe0d16ae931b73c59d7e0c089c0", "", null));
assertThat(md4.isPasswordValid("31d6cfe0d16ae931b73c59d7e0c089c0", "", null)).isTrue();
}
public void testIsPasswordValid() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder();
md4.setEncodeHashAsBase64(true);
assertTrue(md4.isPasswordValid("8zobtq72iAt0W6KNqavGwg==", "ww_uni123", null));
assertThat(md4.isPasswordValid("8zobtq72iAt0W6KNqavGwg==", "ww_uni123", null)).isTrue();
}
public void testIsSaltedPasswordValid() {

View File

@ -15,7 +15,7 @@
package org.springframework.security.authentication.encoding;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
@ -40,10 +40,10 @@ public class Md5PasswordEncoderTests {
String badRaw = "abc321";
String salt = "THIS_IS_A_SALT";
String encoded = pe.encodePassword(raw, salt);
assertTrue(pe.isPasswordValid(encoded, raw, salt));
assertFalse(pe.isPasswordValid(encoded, badRaw, salt));
assertEquals("a68aafd90299d0b137de28fb4bb68573", encoded);
assertEquals("MD5", pe.getAlgorithm());
assertThat(pe.isPasswordValid(encoded, raw, salt)).isTrue();
assertThat(pe.isPasswordValid(encoded, badRaw, salt)).isFalse();
assertThat(encoded).isEqualTo("a68aafd90299d0b137de28fb4bb68573");
assertThat(pe.getAlgorithm()).isEqualTo("MD5");
}
@Test
@ -52,7 +52,7 @@ public class Md5PasswordEncoderTests {
// $ echo -n "你好" | md5
// 7eca689f0d3389d9dea66ae112e5cfd7
String encodedPassword = md5.encodePassword("\u4F60\u597d", null);
assertEquals("7eca689f0d3389d9dea66ae112e5cfd7", encodedPassword);
assertThat(encodedPassword).isEqualTo("7eca689f0d3389d9dea66ae112e5cfd7");
}
@Test
@ -63,9 +63,9 @@ public class Md5PasswordEncoderTests {
String badRaw = "abc321";
String salt = "THIS_IS_A_SALT";
String encoded = pe.encodePassword(raw, salt);
assertTrue(pe.isPasswordValid(encoded, raw, salt));
assertFalse(pe.isPasswordValid(encoded, badRaw, salt));
assertTrue(encoded.length() != 32);
assertThat(pe.isPasswordValid(encoded, raw, salt)).isTrue();
assertThat(pe.isPasswordValid(encoded, badRaw, salt)).isFalse();
assertThat(encoded.length() != 32).isTrue();
}
@Test

View File

@ -1,6 +1,6 @@
package org.springframework.security.authentication.encoding;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
@ -11,24 +11,24 @@ public class PasswordEncoderUtilsTests {
@Test
public void differentLength() {
assertFalse(PasswordEncoderUtils.equals("abc", "a"));
assertFalse(PasswordEncoderUtils.equals("a", "abc"));
assertThat(PasswordEncoderUtils.equals("abc", "a")).isFalse();
assertThat(PasswordEncoderUtils.equals("a", "abc")).isFalse();
}
@Test
public void equalsNull() {
assertFalse(PasswordEncoderUtils.equals(null, "a"));
assertFalse(PasswordEncoderUtils.equals("a", null));
assertTrue(PasswordEncoderUtils.equals(null, null));
assertThat(PasswordEncoderUtils.equals(null, "a")).isFalse();
assertThat(PasswordEncoderUtils.equals("a", null)).isFalse();
assertThat(PasswordEncoderUtils.equals(null, null)).isTrue();
}
@Test
public void equalsCaseSensitive() {
assertFalse(PasswordEncoderUtils.equals("aBc", "abc"));
assertThat(PasswordEncoderUtils.equals("aBc", "abc")).isFalse();
}
@Test
public void equalsSuccess() {
assertTrue(PasswordEncoderUtils.equals("abcdef", "abcdef"));
assertThat(PasswordEncoderUtils.equals("abcdef", "abcdef")).isTrue();
}
}

Some files were not shown because too many files have changed in this diff Show More