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

View File

@ -1,6 +1,7 @@
package org.springframework.security.acls; 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.Matchers.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
@ -36,7 +37,7 @@ public class AclPermissionEvaluatorTests {
when(service.readAclById(any(ObjectIdentity.class), anyList())).thenReturn(acl); when(service.readAclById(any(ObjectIdentity.class), anyList())).thenReturn(acl);
when(acl.isGranted(anyList(), anyList(), eq(false))).thenReturn(true); 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 @Test
@ -56,7 +57,7 @@ public class AclPermissionEvaluatorTests {
when(service.readAclById(any(ObjectIdentity.class), anyList())).thenReturn(acl); when(service.readAclById(any(ObjectIdentity.class), anyList())).thenReturn(acl);
when(acl.isGranted(anyList(), anyList(), eq(false))).thenReturn(true); 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); Locale.setDefault(systemLocale);
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,6 @@
package org.springframework.security.acls.domain; package org.springframework.security.acls.domain;
import static org.junit.Assert.*; import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@ -46,14 +46,14 @@ public class AuditLoggerTests {
public void nonAuditableAceIsIgnored() { public void nonAuditableAceIsIgnored() {
AccessControlEntry ace = mock(AccessControlEntry.class); AccessControlEntry ace = mock(AccessControlEntry.class);
logger.logIfNeeded(true, ace); logger.logIfNeeded(true, ace);
assertEquals(0, bytes.size()); assertThat(bytes.size()).isEqualTo(0);
} }
@Test @Test
public void successIsNotLoggedIfAceDoesntRequireSuccessAudit() throws Exception { public void successIsNotLoggedIfAceDoesntRequireSuccessAudit() throws Exception {
when(ace.isAuditSuccess()).thenReturn(false); when(ace.isAuditSuccess()).thenReturn(false);
logger.logIfNeeded(true, ace); logger.logIfNeeded(true, ace);
assertEquals(0, bytes.size()); assertThat(bytes.size()).isEqualTo(0);
} }
@Test @Test
@ -61,20 +61,20 @@ public class AuditLoggerTests {
when(ace.isAuditSuccess()).thenReturn(true); when(ace.isAuditSuccess()).thenReturn(true);
logger.logIfNeeded(true, ace); logger.logIfNeeded(true, ace);
assertTrue(bytes.toString().startsWith("GRANTED due to ACE")); assertThat(bytes.toString().startsWith("GRANTED due to ACE")).isTrue();
} }
@Test @Test
public void failureIsntLoggedIfAceDoesntRequireFailureAudit() throws Exception { public void failureIsntLoggedIfAceDoesntRequireFailureAudit() throws Exception {
when(ace.isAuditFailure()).thenReturn(false); when(ace.isAuditFailure()).thenReturn(false);
logger.logIfNeeded(false, ace); logger.logIfNeeded(false, ace);
assertEquals(0, bytes.size()); assertThat(bytes.size()).isEqualTo(0);
} }
@Test @Test
public void failureIsLoggedIfAceRequiresFailureAudit() throws Exception { public void failureIsLoggedIfAceRequiresFailureAudit() throws Exception {
when(ace.isAuditFailure()).thenReturn(true); when(ace.isAuditFailure()).thenReturn(true);
logger.logIfNeeded(false, ace); 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; package org.springframework.security.acls.domain;
import static org.junit.Assert.*; import static org.assertj.core.api.Assertions.*;
import org.junit.Test; import org.junit.Test;
import org.springframework.security.acls.domain.IdentityUnavailableException; import org.springframework.security.acls.domain.IdentityUnavailableException;
@ -66,8 +66,8 @@ public class ObjectIdentityImplTests {
@Test @Test
public void gettersReturnExpectedValues() throws Exception { public void gettersReturnExpectedValues() throws Exception {
ObjectIdentity obj = new ObjectIdentityImpl(DOMAIN_CLASS, Long.valueOf(1)); ObjectIdentity obj = new ObjectIdentityImpl(DOMAIN_CLASS, Long.valueOf(1));
assertEquals(Long.valueOf(1), obj.getIdentifier()); assertThat(obj.getIdentifier()).isEqualTo(Long.valueOf(1));
assertEquals(MockIdDomainObject.class.getName(), obj.getType()); assertThat(obj.getType()).isEqualTo(MockIdDomainObject.class.getName());
} }
@Test @Test
@ -121,23 +121,22 @@ public class ObjectIdentityImplTests {
mockObj.setId(Long.valueOf(1)); mockObj.setId(Long.valueOf(1));
String string = "SOME_STRING"; String string = "SOME_STRING";
assertNotSame(obj, string); assertThat(string).isNotSameAs(obj);
assertFalse(obj.equals(null)); assertThat(obj.equals(null)).isFalse();
assertFalse(obj.equals("DIFFERENT_OBJECT_TYPE")); assertThat(obj.equals("DIFFERENT_OBJECT_TYPE")).isFalse();
assertFalse(obj.equals(new ObjectIdentityImpl(DOMAIN_CLASS, Long.valueOf(2)))); assertThat(obj.equals(new ObjectIdentityImpl(DOMAIN_CLASS, Long.valueOf(2)))).isFalse();
assertFalse(obj assertThat(obj).isNotEqualTo(new ObjectIdentityImpl(
.equals(new ObjectIdentityImpl(
"org.springframework.security.acls.domain.ObjectIdentityImplTests$MockOtherIdDomainObject", "org.springframework.security.acls.domain.ObjectIdentityImplTests$MockOtherIdDomainObject",
Long.valueOf(1)))); Long.valueOf(1)));
assertEquals(new ObjectIdentityImpl(DOMAIN_CLASS, Long.valueOf(1)), obj); assertThat(new ObjectIdentityImpl(DOMAIN_CLASS, 1L)).isEqualTo(obj);
assertEquals(obj, new ObjectIdentityImpl(mockObj)); assertThat(new ObjectIdentityImpl(mockObj)).isEqualTo(obj);
} }
@Test @Test
public void hashcodeIsDifferentForDifferentJavaTypes() throws Exception { public void hashcodeIsDifferentForDifferentJavaTypes() throws Exception {
ObjectIdentity obj = new ObjectIdentityImpl(Object.class, Long.valueOf(1)); ObjectIdentity obj = new ObjectIdentityImpl(Object.class, Long.valueOf(1));
ObjectIdentity obj2 = new ObjectIdentityImpl(String.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 @Test
@ -145,23 +144,23 @@ public class ObjectIdentityImplTests {
ObjectIdentity obj = new ObjectIdentityImpl(Object.class, new Long(5)); ObjectIdentity obj = new ObjectIdentityImpl(Object.class, new Long(5));
ObjectIdentity obj2 = new ObjectIdentityImpl(Object.class, Integer.valueOf(5)); ObjectIdentity obj2 = new ObjectIdentityImpl(Object.class, Integer.valueOf(5));
assertEquals(obj, obj2); assertThat(obj2).isEqualTo(obj);
assertEquals(obj.hashCode(), obj2.hashCode()); assertThat(obj2.hashCode()).isEqualTo(obj.hashCode());
} }
@Test @Test
public void equalStringIdsAreEqualAndHaveSameHashcode() throws Exception { public void equalStringIdsAreEqualAndHaveSameHashcode() throws Exception {
ObjectIdentity obj = new ObjectIdentityImpl(Object.class, "1000"); ObjectIdentity obj = new ObjectIdentityImpl(Object.class, "1000");
ObjectIdentity obj2 = new ObjectIdentityImpl(Object.class, "1000"); ObjectIdentity obj2 = new ObjectIdentityImpl(Object.class, "1000");
assertEquals(obj, obj2); assertThat(obj2).isEqualTo(obj);
assertEquals(obj.hashCode(), obj2.hashCode()); assertThat(obj2.hashCode()).isEqualTo(obj.hashCode());
} }
@Test @Test
public void stringAndNumericIdsAreNotEqual() throws Exception { public void stringAndNumericIdsAreNotEqual() throws Exception {
ObjectIdentity obj = new ObjectIdentityImpl(Object.class, "1000"); ObjectIdentity obj = new ObjectIdentityImpl(Object.class, "1000");
ObjectIdentity obj2 = new ObjectIdentityImpl(Object.class, Long.valueOf(1000)); ObjectIdentity obj2 = new ObjectIdentityImpl(Object.class, Long.valueOf(1000));
assertFalse(obj.equals(obj2)); assertThat(obj.equals(obj2)).isFalse();
} }
// ~ Inner Classes // ~ Inner Classes

View File

@ -1,5 +1,8 @@
package org.springframework.security.acls.domain; 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.ObjectIdentityImpl;
import org.springframework.security.acls.domain.ObjectIdentityRetrievalStrategyImpl; import org.springframework.security.acls.domain.ObjectIdentityRetrievalStrategyImpl;
import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.ObjectIdentity;
@ -23,8 +26,8 @@ public class ObjectIdentityRetrievalStrategyImplTests extends TestCase {
ObjectIdentityRetrievalStrategy retStrategy = new ObjectIdentityRetrievalStrategyImpl(); ObjectIdentityRetrievalStrategy retStrategy = new ObjectIdentityRetrievalStrategyImpl();
ObjectIdentity identity = retStrategy.getObjectIdentity(domain); ObjectIdentity identity = retStrategy.getObjectIdentity(domain);
assertNotNull(identity); assertThat(identity).isNotNull();
assertEquals(identity, new ObjectIdentityImpl(domain)); assertThat(new ObjectIdentityImpl(domain)).isEqualTo(identity);
} }
// ~ Inner Classes // ~ Inner Classes

View File

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

View File

@ -1,6 +1,7 @@
package org.springframework.security.acls.jdbc; 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.Cache;
import net.sf.ehcache.CacheManager; import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache; import net.sf.ehcache.Ehcache;
@ -45,14 +46,12 @@ public class BasicLookupStrategyTests {
@BeforeClass @BeforeClass
public static void initCacheManaer() { public static void initCacheManaer() {
cacheManager = CacheManager.create(); cacheManager = CacheManager.create();
cacheManager cacheManager.addCache(new Cache("basiclookuptestcache", 500, false, false, 30, 30));
.addCache(new Cache("basiclookuptestcache", 500, false, false, 30, 30));
} }
@BeforeClass @BeforeClass
public static void createDatabase() throws Exception { public static void createDatabase() throws Exception {
dataSource = new SingleConnectionDataSource("jdbc:hsqldb:mem:lookupstrategytest", dataSource = new SingleConnectionDataSource("jdbc:hsqldb:mem:lookupstrategytest", "sa", "", true);
"sa", "", true);
dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate = new JdbcTemplate(dataSource);
@ -75,9 +74,7 @@ public class BasicLookupStrategyTests {
@Before @Before
public void populateDatabase() { public void populateDatabase() {
String query = "INSERT INTO acl_sid(ID,PRINCIPAL,SID) VALUES (1,1,'ben');" String query = "INSERT INTO acl_sid(ID,PRINCIPAL,SID) VALUES (1,1,'ben');"
+ "INSERT INTO acl_class(ID,CLASS) VALUES (2,'" + "INSERT INTO acl_class(ID,CLASS) VALUES (2,'" + TARGET_CLASS + "');"
+ 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 (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 (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);" + "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 @After
public void emptyDatabase() { public void emptyDatabase() {
String query = "DELETE FROM acl_entry;" String query = "DELETE FROM acl_entry;" + "DELETE FROM acl_object_identity WHERE ID = 7;"
+ "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 = 6;" + "DELETE FROM acl_object_identity WHERE ID = 4;" + "DELETE FROM acl_object_identity WHERE ID = 3;"
+ "DELETE FROM acl_object_identity WHERE ID = 5;" + "DELETE FROM acl_object_identity WHERE ID = 2;" + "DELETE FROM acl_object_identity WHERE ID = 1;"
+ "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;"; + "DELETE FROM acl_class;" + "DELETE FROM acl_sid;";
jdbcTemplate.execute(query); jdbcTemplate.execute(query);
} }
@ -123,33 +116,29 @@ public class BasicLookupStrategyTests {
@Test @Test
public void testAclsRetrievalWithDefaultBatchSize() throws Exception { public void testAclsRetrievalWithDefaultBatchSize() throws Exception {
ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(100)); ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(100));
ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, new Long( ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(101));
101)); // Deliberately use an integer for the child, to reproduce bug report in
// Deliberately use an integer for the child, to reproduce bug report in SEC-819 // SEC-819
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, Integer.valueOf(102));
Integer.valueOf(102));
Map<ObjectIdentity, Acl> map = this.strategy.readAclsById( Map<ObjectIdentity, Acl> map = this.strategy
Arrays.asList(topParentOid, middleParentOid, childOid), null); .readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
checkEntries(topParentOid, middleParentOid, childOid, map); checkEntries(topParentOid, middleParentOid, childOid, map);
} }
@Test @Test
public void testAclsRetrievalFromCacheOnly() throws Exception { public void testAclsRetrievalFromCacheOnly() throws Exception {
ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, Integer.valueOf(100));
Integer.valueOf(100)); ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(101));
ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(
101));
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(102)); ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(102));
// Objects were put in cache // Objects were put in cache
strategy.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), strategy.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
null);
// Let's empty the database to force acls retrieval from cache // Let's empty the database to force acls retrieval from cache
emptyDatabase(); emptyDatabase();
Map<ObjectIdentity, Acl> map = this.strategy.readAclsById( Map<ObjectIdentity, Acl> map = this.strategy
Arrays.asList(topParentOid, middleParentOid, childOid), null); .readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
checkEntries(topParentOid, middleParentOid, childOid, map); checkEntries(topParentOid, middleParentOid, childOid, map);
} }
@ -157,99 +146,83 @@ public class BasicLookupStrategyTests {
@Test @Test
public void testAclsRetrievalWithCustomBatchSize() throws Exception { public void testAclsRetrievalWithCustomBatchSize() throws Exception {
ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(100)); ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(100));
ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, Integer.valueOf(101));
Integer.valueOf(101));
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(102)); 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 // acls
this.strategy.setBatchSize(1); this.strategy.setBatchSize(1);
Map<ObjectIdentity, Acl> map = this.strategy.readAclsById( Map<ObjectIdentity, Acl> map = this.strategy
Arrays.asList(topParentOid, middleParentOid, childOid), null); .readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
checkEntries(topParentOid, middleParentOid, childOid, map); checkEntries(topParentOid, middleParentOid, childOid, map);
} }
private void checkEntries(ObjectIdentity topParentOid, private void checkEntries(ObjectIdentity topParentOid, ObjectIdentity middleParentOid, ObjectIdentity childOid,
ObjectIdentity middleParentOid, ObjectIdentity childOid,
Map<ObjectIdentity, Acl> map) throws Exception { Map<ObjectIdentity, Acl> map) throws Exception {
Assert.assertEquals(3, map.size()); assertThat(map).hasSize(3);
MutableAcl topParent = (MutableAcl) map.get(topParentOid); MutableAcl topParent = (MutableAcl) map.get(topParentOid);
MutableAcl middleParent = (MutableAcl) map.get(middleParentOid); MutableAcl middleParent = (MutableAcl) map.get(middleParentOid);
MutableAcl child = (MutableAcl) map.get(childOid); MutableAcl child = (MutableAcl) map.get(childOid);
// Check the retrieved versions has IDs // Check the retrieved versions has IDs
Assert.assertNotNull(topParent.getId()); assertThat(topParent.getId()).isNotNull();
Assert.assertNotNull(middleParent.getId()); assertThat(middleParent.getId()).isNotNull();
Assert.assertNotNull(child.getId()); assertThat(child.getId()).isNotNull();
// Check their parents were correctly retrieved // Check their parents were correctly retrieved
Assert.assertNull(topParent.getParentAcl()); assertThat(topParent.getParentAcl()).isNull();
Assert.assertEquals(topParentOid, middleParent.getParentAcl().getObjectIdentity()); assertThat(middleParent.getParentAcl().getObjectIdentity()).isEqualTo(topParentOid);
Assert.assertEquals(middleParentOid, child.getParentAcl().getObjectIdentity()); assertThat(child.getParentAcl().getObjectIdentity()).isEqualTo(middleParentOid);
// Check their ACEs were correctly retrieved // Check their ACEs were correctly retrieved
Assert.assertEquals(2, topParent.getEntries().size()); assertThat(topParent.getEntries()).hasSize(2);
Assert.assertEquals(1, middleParent.getEntries().size()); assertThat(middleParent.getEntries()).hasSize(1);
Assert.assertEquals(1, child.getEntries().size()); assertThat(child.getEntries()).hasSize(1);
// Check object identities were correctly retrieved // Check object identities were correctly retrieved
Assert.assertEquals(topParentOid, topParent.getObjectIdentity()); assertThat(topParent.getObjectIdentity()).isEqualTo(topParentOid);
Assert.assertEquals(middleParentOid, middleParent.getObjectIdentity()); assertThat(middleParent.getObjectIdentity()).isEqualTo(middleParentOid);
Assert.assertEquals(childOid, child.getObjectIdentity()); assertThat(child.getObjectIdentity()).isEqualTo(childOid);
// Check each entry // Check each entry
Assert.assertTrue(topParent.isEntriesInheriting()); assertThat(topParent.isEntriesInheriting()).isTrue();
Assert.assertEquals(topParent.getId(), Long.valueOf(1)); assertThat(Long.valueOf(1)).isEqualTo(topParent.getId());
Assert.assertEquals(topParent.getOwner(), new PrincipalSid("ben")); assertThat(new PrincipalSid("ben")).isEqualTo(topParent.getOwner());
Assert.assertEquals(topParent.getEntries().get(0).getId(), Long.valueOf(1)); assertThat(Long.valueOf(1)).isEqualTo(topParent.getEntries().get(0).getId());
Assert.assertEquals(topParent.getEntries().get(0).getPermission(), assertThat(topParent.getEntries().get(0).getPermission()).isEqualTo(BasePermission.READ);
BasePermission.READ); assertThat(topParent.getEntries().get(0).getSid()).isEqualTo(new PrincipalSid("ben"));
Assert.assertEquals(topParent.getEntries().get(0).getSid(), new PrincipalSid( assertThat(((AuditableAccessControlEntry) topParent.getEntries().get(0)).isAuditFailure()).isFalse();
"ben")); assertThat(((AuditableAccessControlEntry) topParent.getEntries().get(0)).isAuditSuccess()).isFalse();
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries().get(0)) assertThat((topParent.getEntries().get(0)).isGranting()).isTrue();
.isAuditFailure());
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries().get(0))
.isAuditSuccess());
Assert.assertTrue((topParent.getEntries().get(0)).isGranting());
Assert.assertEquals(topParent.getEntries().get(1).getId(), Long.valueOf(2)); assertThat(Long.valueOf(2)).isEqualTo(topParent.getEntries().get(1).getId());
Assert.assertEquals(topParent.getEntries().get(1).getPermission(), assertThat(topParent.getEntries().get(1).getPermission()).isEqualTo(BasePermission.WRITE);
BasePermission.WRITE); assertThat(topParent.getEntries().get(1).getSid()).isEqualTo(new PrincipalSid("ben"));
Assert.assertEquals(topParent.getEntries().get(1).getSid(), new PrincipalSid( assertThat(((AuditableAccessControlEntry) topParent.getEntries().get(1)).isAuditFailure()).isFalse();
"ben")); assertThat(((AuditableAccessControlEntry) topParent.getEntries().get(1)).isAuditSuccess()).isFalse();
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries().get(1)) assertThat(topParent.getEntries().get(1).isGranting()).isFalse();
.isAuditFailure());
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries().get(1))
.isAuditSuccess());
Assert.assertFalse(topParent.getEntries().get(1).isGranting());
Assert.assertTrue(middleParent.isEntriesInheriting()); assertThat(middleParent.isEntriesInheriting()).isTrue();
Assert.assertEquals(middleParent.getId(), Long.valueOf(2)); assertThat(Long.valueOf(2)).isEqualTo(middleParent.getId());
Assert.assertEquals(middleParent.getOwner(), new PrincipalSid("ben")); assertThat(new PrincipalSid("ben")).isEqualTo(middleParent.getOwner());
Assert.assertEquals(middleParent.getEntries().get(0).getId(), Long.valueOf(3)); assertThat(Long.valueOf(3)).isEqualTo(middleParent.getEntries().get(0).getId());
Assert.assertEquals(middleParent.getEntries().get(0).getPermission(), assertThat(middleParent.getEntries().get(0).getPermission()).isEqualTo(BasePermission.DELETE);
BasePermission.DELETE); assertThat(middleParent.getEntries().get(0).getSid()).isEqualTo(new PrincipalSid("ben"));
Assert.assertEquals(middleParent.getEntries().get(0).getSid(), new PrincipalSid( assertThat(((AuditableAccessControlEntry) middleParent.getEntries().get(0)).isAuditFailure()).isFalse();
"ben")); assertThat(((AuditableAccessControlEntry) middleParent.getEntries().get(0)).isAuditSuccess()).isFalse();
Assert.assertFalse(((AuditableAccessControlEntry) middleParent.getEntries() assertThat(middleParent.getEntries().get(0).isGranting()).isTrue();
.get(0)).isAuditFailure());
Assert.assertFalse(((AuditableAccessControlEntry) middleParent.getEntries()
.get(0)).isAuditSuccess());
Assert.assertTrue(middleParent.getEntries().get(0).isGranting());
Assert.assertTrue(child.isEntriesInheriting()); assertThat(child.isEntriesInheriting()).isTrue();
Assert.assertEquals(child.getId(), Long.valueOf(3)); assertThat(Long.valueOf(3)).isEqualTo(child.getId());
Assert.assertEquals(child.getOwner(), new PrincipalSid("ben")); assertThat(new PrincipalSid("ben")).isEqualTo(child.getOwner());
Assert.assertEquals(child.getEntries().get(0).getId(), Long.valueOf(4)); assertThat(Long.valueOf(4)).isEqualTo(child.getEntries().get(0).getId());
Assert.assertEquals(child.getEntries().get(0).getPermission(), assertThat(child.getEntries().get(0).getPermission()).isEqualTo(BasePermission.DELETE);
BasePermission.DELETE); assertThat(new PrincipalSid("ben")).isEqualTo(child.getEntries().get(0).getSid());
Assert.assertEquals(child.getEntries().get(0).getSid(), new PrincipalSid("ben")); assertThat(((AuditableAccessControlEntry) child.getEntries().get(0)).isAuditFailure()).isFalse();
Assert.assertFalse(((AuditableAccessControlEntry) child.getEntries().get(0)) assertThat(((AuditableAccessControlEntry) child.getEntries().get(0)).isAuditSuccess()).isFalse();
.isAuditFailure()); assertThat((child.getEntries().get(0)).isGranting()).isFalse();
Assert.assertFalse(((AuditableAccessControlEntry) child.getEntries().get(0))
.isAuditSuccess());
Assert.assertFalse((child.getEntries().get(0)).isGranting());
} }
@Test @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);"; 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); jdbcTemplate.execute(query);
ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, Long.valueOf(100));
Long.valueOf(100)); ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, Long.valueOf(101));
ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS,
Long.valueOf(101));
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, Long.valueOf(102)); ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, Long.valueOf(102));
ObjectIdentity middleParent2Oid = new ObjectIdentityImpl(TARGET_CLASS, ObjectIdentity middleParent2Oid = new ObjectIdentityImpl(TARGET_CLASS, Long.valueOf(103));
Long.valueOf(103));
// Retrieve the child // Retrieve the child
Map<ObjectIdentity, Acl> map = this.strategy.readAclsById( Map<ObjectIdentity, Acl> map = this.strategy.readAclsById(Arrays.asList(childOid), null);
Arrays.asList(childOid), null);
// Check that the child and all its parents were retrieved // Check that the child and all its parents were retrieved
Assert.assertNotNull(map.get(childOid)); assertThat(map.get(childOid)).isNotNull();
Assert.assertEquals(childOid, map.get(childOid).getObjectIdentity()); assertThat(map.get(childOid).getObjectIdentity()).isEqualTo(childOid);
Assert.assertNotNull(map.get(middleParentOid)); assertThat(map.get(middleParentOid)).isNotNull();
Assert.assertEquals(middleParentOid, map.get(middleParentOid).getObjectIdentity()); assertThat(map.get(middleParentOid).getObjectIdentity()).isEqualTo(middleParentOid);
Assert.assertNotNull(map.get(topParentOid)); assertThat(map.get(topParentOid)).isNotNull();
Assert.assertEquals(topParentOid, map.get(topParentOid).getObjectIdentity()); assertThat(map.get(topParentOid).getObjectIdentity()).isEqualTo(topParentOid);
// The second parent shouldn't have been retrieved // The second parent shouldn't have been retrieved
Assert.assertNull(map.get(middleParent2Oid)); assertThat(map.get(middleParent2Oid)).isNull();
} }
/** /**
* Test created from SEC-590. * Test created from SEC-590.
*/ */
@Test @Test
public void testReadAllObjectIdentitiesWhenLastElementIsAlreadyCached() public void testReadAllObjectIdentitiesWhenLastElementIsAlreadyCached() throws Exception {
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);" 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 (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);" + "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)"; + "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); jdbcTemplate.execute(query);
ObjectIdentity grandParentOid = new ObjectIdentityImpl(TARGET_CLASS, ObjectIdentity grandParentOid = new ObjectIdentityImpl(TARGET_CLASS, new Long(104));
new Long(104));
ObjectIdentity parent1Oid = new ObjectIdentityImpl(TARGET_CLASS, new Long(105)); ObjectIdentity parent1Oid = new ObjectIdentityImpl(TARGET_CLASS, new Long(105));
ObjectIdentity parent2Oid = new ObjectIdentityImpl(TARGET_CLASS, ObjectIdentity parent2Oid = new ObjectIdentityImpl(TARGET_CLASS, Integer.valueOf(106));
Integer.valueOf(106)); ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, Integer.valueOf(107));
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 // and child
List<Permission> checkPermission = Arrays.asList(BasePermission.READ); List<Permission> checkPermission = Arrays.asList(BasePermission.READ);
List<Sid> sids = Arrays.asList(BEN_SID); List<Sid> sids = Arrays.asList(BEN_SID);
@ -312,25 +278,25 @@ public class BasicLookupStrategyTests {
Map<ObjectIdentity, Acl> foundAcls = strategy.readAclsById(childOids, sids); Map<ObjectIdentity, Acl> foundAcls = strategy.readAclsById(childOids, sids);
Acl foundChildAcl = foundAcls.get(childOid); Acl foundChildAcl = foundAcls.get(childOid);
Assert.assertNotNull(foundChildAcl); assertThat(foundChildAcl).isNotNull();
Assert.assertTrue(foundChildAcl.isGranted(checkPermission, sids, false)); 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 // element have to be one which
// is already in cache and the element before it must not be stored in cache // is already in cache and the element before it must not be stored in
List<ObjectIdentity> allOids = Arrays.asList(grandParentOid, parent1Oid, // cache
parent2Oid, childOid); List<ObjectIdentity> allOids = Arrays.asList(grandParentOid, parent1Oid, parent2Oid, childOid);
try { try {
foundAcls = strategy.readAclsById(allOids, sids); foundAcls = strategy.readAclsById(allOids, sids);
Assert.assertTrue(true);
} } catch (NotFoundException notExpected) {
catch (NotFoundException notExpected) { fail("It shouldn't have thrown NotFoundException");
Assert.fail("It shouldn't have thrown NotFoundException");
} }
Acl foundParent2Acl = foundAcls.get(parent2Oid); Acl foundParent2Acl = foundAcls.get(parent2Oid);
Assert.assertNotNull(foundParent2Acl); assertThat(foundParent2Acl).isNotNull();
Assert.assertTrue(foundParent2Acl.isGranted(checkPermission, sids, false)); assertThat(foundParent2Acl.isGranted(checkPermission, sids, false)).isTrue();
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
@ -348,16 +314,16 @@ public class BasicLookupStrategyTests {
public void testCreatePrincipalSid() { public void testCreatePrincipalSid() {
Sid result = strategy.createSid(true, "sid"); Sid result = strategy.createSid(true, "sid");
Assert.assertEquals(PrincipalSid.class, result.getClass()); assertThat(result.getClass()).isEqualTo(PrincipalSid.class);
Assert.assertEquals("sid", ((PrincipalSid) result).getPrincipal()); assertThat(((PrincipalSid) result).getPrincipal()).isEqualTo("sid");
} }
@Test @Test
public void testCreateGrantedAuthority() { public void testCreateGrantedAuthority() {
Sid result = strategy.createSid(false, "sid"); Sid result = strategy.createSid(false, "sid");
Assert.assertEquals(GrantedAuthoritySid.class, result.getClass()); assertThat(result.getClass()).isEqualTo(GrantedAuthoritySid.class);
Assert.assertEquals("sid", ((GrantedAuthoritySid) result).getGrantedAuthority()); 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.Matchers.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import static org.junit.Assert.*; import static org.assertj.core.api.Assertions.*;
import static org.fest.assertions.Assertions.*;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@ -94,7 +93,6 @@ public class EhCacheBasedAclCacheTests {
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertTrue(true);
} }
try { try {
@ -103,7 +101,6 @@ public class EhCacheBasedAclCacheTests {
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertTrue(true);
} }
try { try {
@ -112,7 +109,6 @@ public class EhCacheBasedAclCacheTests {
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertTrue(true);
} }
try { try {
@ -121,7 +117,6 @@ public class EhCacheBasedAclCacheTests {
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertTrue(true);
} }
try { try {
@ -130,7 +125,6 @@ public class EhCacheBasedAclCacheTests {
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertTrue(true);
} }
} }
@ -149,15 +143,15 @@ public class EhCacheBasedAclCacheTests {
MutableAcl retrieved = (MutableAcl) ois.readObject(); MutableAcl retrieved = (MutableAcl) ois.readObject();
ois.close(); ois.close();
assertEquals(acl, retrieved); assertThat(retrieved).isEqualTo(acl);
Object retrieved1 = FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy", Object retrieved1 = FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy",
retrieved); retrieved);
assertEquals(null, retrieved1); assertThat(retrieved1).isEqualTo(null);
Object retrieved2 = FieldUtils.getProtectedFieldValue( Object retrieved2 = FieldUtils.getProtectedFieldValue(
"permissionGrantingStrategy", retrieved); "permissionGrantingStrategy", retrieved);
assertEquals(null, retrieved2); assertThat(retrieved2).isEqualTo(null);
} }
@Test @Test

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -15,6 +15,8 @@
package org.springframework.security.cas.authentication; package org.springframework.security.cas.authentication;
import static org.assertj.core.api.Assertions.*;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.jasig.cas.client.validation.Assertion; import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.AssertionImpl; import org.jasig.cas.client.validation.AssertionImpl;
@ -97,7 +99,6 @@ public class CasAuthenticationTokenTests extends TestCase {
fail("Should have thrown IllegalArgumentException"); fail("Should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertTrue(true);
} }
} }
@ -110,7 +111,7 @@ public class CasAuthenticationTokenTests extends TestCase {
CasAuthenticationToken token2 = new CasAuthenticationToken("key", CasAuthenticationToken token2 = new CasAuthenticationToken("key",
makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion); makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion);
assertEquals(token1, token2); assertThat(token2).isEqualTo(token1);
} }
public void testGetters() { public void testGetters() {
@ -118,16 +119,15 @@ public class CasAuthenticationTokenTests extends TestCase {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key", CasAuthenticationToken token = new CasAuthenticationToken("key",
makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion); makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion);
assertEquals("key".hashCode(), token.getKeyHash()); assertThat(token.getKeyHash()).isEqualTo("key".hashCode());
assertEquals(makeUserDetails(), token.getPrincipal()); assertThat(token.getPrincipal()).isEqualTo(makeUserDetails());
assertEquals("Password", token.getCredentials()); assertThat(token.getCredentials()).isEqualTo("Password");
assertTrue(token.getAuthorities() assertThat(token.getAuthorities())
.contains(new SimpleGrantedAuthority("ROLE_ONE"))); .contains(new SimpleGrantedAuthority("ROLE_ONE"));
assertTrue(token.getAuthorities() assertThat(token.getAuthorities())
.contains(new SimpleGrantedAuthority("ROLE_TWO"))); .contains(new SimpleGrantedAuthority("ROLE_TWO"));
assertEquals(assertion, token.getAssertion()); assertThat(token.getAssertion()).isEqualTo(assertion);
assertEquals(makeUserDetails().getUsername(), token.getUserDetails() assertThat(token.getUserDetails().getUsername()).isEqualTo(makeUserDetails().getUsername());
.getUsername());
} }
public void testNoArgConstructorDoesntExist() { public void testNoArgConstructorDoesntExist() {
@ -136,7 +136,7 @@ public class CasAuthenticationTokenTests extends TestCase {
fail("Should have thrown NoSuchMethodException"); fail("Should have thrown NoSuchMethodException");
} }
catch (NoSuchMethodException expected) { catch (NoSuchMethodException expected) {
assertTrue(true);
} }
} }
@ -150,7 +150,7 @@ public class CasAuthenticationTokenTests extends TestCase {
makeUserDetails("OTHER_NAME"), "Password", ROLES, makeUserDetails(), makeUserDetails("OTHER_NAME"), "Password", ROLES, makeUserDetails(),
assertion); assertion);
assertTrue(!token1.equals(token2)); assertThat(!token1.equals(token2)).isTrue();
} }
public void testNotEqualsDueToDifferentAuthenticationClass() { public void testNotEqualsDueToDifferentAuthenticationClass() {
@ -161,7 +161,7 @@ public class CasAuthenticationTokenTests extends TestCase {
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken( UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken(
"Test", "Password", ROLES); "Test", "Password", ROLES);
assertTrue(!token1.equals(token2)); assertThat(!token1.equals(token2)).isTrue();
} }
public void testNotEqualsDueToKey() { public void testNotEqualsDueToKey() {
@ -173,7 +173,7 @@ public class CasAuthenticationTokenTests extends TestCase {
CasAuthenticationToken token2 = new CasAuthenticationToken("DIFFERENT_KEY", CasAuthenticationToken token2 = new CasAuthenticationToken("DIFFERENT_KEY",
makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion); makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion);
assertTrue(!token1.equals(token2)); assertThat(!token1.equals(token2)).isTrue();
} }
public void testNotEqualsDueToAssertion() { public void testNotEqualsDueToAssertion() {
@ -186,16 +186,16 @@ public class CasAuthenticationTokenTests extends TestCase {
CasAuthenticationToken token2 = new CasAuthenticationToken("key", CasAuthenticationToken token2 = new CasAuthenticationToken("key",
makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion2); makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion2);
assertTrue(!token1.equals(token2)); assertThat(!token1.equals(token2)).isTrue();
} }
public void testSetAuthenticated() { public void testSetAuthenticated() {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key", CasAuthenticationToken token = new CasAuthenticationToken("key",
makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion); makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion);
assertTrue(token.isAuthenticated()); assertThat(token.isAuthenticated()).isTrue();
token.setAuthenticated(false); token.setAuthenticated(false);
assertTrue(!token.isAuthenticated()); assertThat(!token.isAuthenticated()).isTrue();
} }
public void testToString() { public void testToString() {
@ -203,6 +203,6 @@ public class CasAuthenticationTokenTests extends TestCase {
CasAuthenticationToken token = new CasAuthenticationToken("key", CasAuthenticationToken token = new CasAuthenticationToken("key",
makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion); makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion);
String result = token.toString(); 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.CasAuthenticationToken;
import org.springframework.security.cas.authentication.EhCacheBasedTicketCache; import org.springframework.security.cas.authentication.EhCacheBasedTicketCache;
import static org.junit.Assert.*; import static org.assertj.core.api.Assertions.*;
/** /**
* Tests {@link EhCacheBasedTicketCache}. * Tests {@link EhCacheBasedTicketCache}.
@ -59,15 +59,15 @@ public class EhCacheBasedTicketCacheTests extends AbstractStatelessTicketCacheTe
// Check it gets stored in the cache // Check it gets stored in the cache
cache.putTicketInCache(token); 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 // Check it gets removed from the cache
cache.removeTicketFromCache(getToken()); 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 // Check it doesn't return values for null or unknown service tickets
assertNull(cache.getByTicketId(null)); assertThat(cache.getByTicketId(null)).isNull();
assertNull(cache.getByTicketId("UNKNOWN_SERVICE_TICKET")); assertThat(cache.getByTicketId("UNKNOWN_SERVICE_TICKET")).isNull();
} }
@Test @Test
@ -79,11 +79,11 @@ public class EhCacheBasedTicketCacheTests extends AbstractStatelessTicketCacheTe
fail("Should have thrown IllegalArgumentException"); fail("Should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertTrue(true);
} }
Ehcache myCache = cacheManager.getCache("castickets"); Ehcache myCache = cacheManager.getCache("castickets");
cache.setCache(myCache); 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.NullStatelessTicketCache;
import org.springframework.security.cas.authentication.StatelessTicketCache; 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} * Test cases for the @link {@link NullStatelessTicketCache}
@ -33,14 +33,14 @@ public class NullStatelessTicketCacheTests extends AbstractStatelessTicketCacheT
@Test @Test
public void testGetter() { public void testGetter() {
assertNull(cache.getByTicketId(null)); assertThat(cache.getByTicketId(null)).isNull();
assertNull(cache.getByTicketId("test")); assertThat(cache.getByTicketId("test")).isNull();
} }
@Test @Test
public void testInsertAndGet() { public void testInsertAndGet() {
final CasAuthenticationToken token = getToken(); final CasAuthenticationToken token = getToken();
cache.putTicketInCache(token); 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.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import static org.junit.Assert.*; import static org.assertj.core.api.Assertions.*;
/** /**
* Tests * Tests
@ -50,15 +50,15 @@ public class SpringCacheBasedTicketCacheTests extends AbstractStatelessTicketCac
// Check it gets stored in the cache // Check it gets stored in the cache
cache.putTicketInCache(token); 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 // Check it gets removed from the cache
cache.removeTicketFromCache(getToken()); 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 // Check it doesn't return values for null or unknown service tickets
assertNull(cache.getByTicketId(null)); assertThat(cache.getByTicketId(null)).isNull();
assertNull(cache.getByTicketId("UNKNOWN_SERVICE_TICKET")); assertThat(cache.getByTicketId("UNKNOWN_SERVICE_TICKET")).isNull();
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -15,7 +15,7 @@
*/ */
package org.springframework.security.config.annotation; 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.ArrayList;
import java.util.LinkedList; import java.util.LinkedList;

View File

@ -25,7 +25,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
import javax.sql.DataSource 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 static org.junit.Assert.fail
import org.aopalliance.intercept.MethodInterceptor import org.aopalliance.intercept.MethodInterceptor

View File

@ -15,7 +15,7 @@
*/ */
package org.springframework.security.config.annotation.method.configuration 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 static org.junit.Assert.fail
import java.io.Serializable; 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 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 static org.junit.Assert.fail
import java.lang.reflect.Method import java.lang.reflect.Method

View File

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

View File

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

View File

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

View File

@ -15,7 +15,7 @@
*/ */
package org.springframework.security.config.annotation.web.configurers; 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; import javax.servlet.http.HttpServletResponse;

View File

@ -15,7 +15,7 @@
*/ */
package org.springframework.security.config.annotation.web.configurers; 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 static org.mockito.Mockito.mock;
import org.junit.After; import org.junit.After;

View File

@ -15,7 +15,7 @@
*/ */
package org.springframework.security.config.annotation.web.configurers; 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; import javax.servlet.http.HttpServletResponse;

View File

@ -15,7 +15,7 @@
*/ */
package org.springframework.security.config.annotation.web.configurers; 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; import javax.servlet.http.HttpServletResponse;

View File

@ -31,7 +31,7 @@ import org.springframework.util.AntPathMatcher;
import java.util.Collection; 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; import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)

View File

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

View File

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

View File

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

View File

@ -1,6 +1,6 @@
package org.springframework.security.config.authentication; 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.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager; import org.springframework.security.authentication.ProviderManager;
@ -118,7 +118,7 @@ public class AuthenticationProviderBeanDefinitionParserTests {
ShaPasswordEncoder encoder = (ShaPasswordEncoder) FieldUtils.getFieldValue( ShaPasswordEncoder encoder = (ShaPasswordEncoder) FieldUtils.getFieldValue(
getProvider(), "passwordEncoder"); getProvider(), "passwordEncoder");
assertEquals("SHA-256", encoder.getAlgorithm()); assertThat(encoder.getAlgorithm()).isEqualTo("SHA-256");
} }
@Test @Test

View File

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

View File

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

View File

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

View File

@ -15,7 +15,7 @@
*/ */
package org.springframework.security.config.http.customconfigurer; 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 static org.springframework.security.config.http.customconfigurer.CustomConfigurer.customConfigurer;
import java.util.Properties; import java.util.Properties;

View File

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

View File

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

View File

@ -1,6 +1,6 @@
package org.springframework.security.intercept.method.aopalliance; 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.After;
import org.junit.Before; import org.junit.Before;

View File

@ -15,7 +15,7 @@
package org.springframework.security.access; 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.junit.Test;
import org.springframework.security.access.event.AuthorizationFailureEvent; import org.springframework.security.access.event.AuthorizationFailureEvent;
@ -61,8 +61,8 @@ public class AuthorizationFailureEventTests {
public void gettersReturnCtorSuppliedData() throws Exception { public void gettersReturnCtorSuppliedData() throws Exception {
AuthorizationFailureEvent event = new AuthorizationFailureEvent(new Object(), AuthorizationFailureEvent event = new AuthorizationFailureEvent(new Object(),
attributes, foo, exception); attributes, foo, exception);
assertSame(attributes, event.getConfigAttributes()); assertThat(event.getConfigAttributes()).isSameAs(attributes);
assertSame(exception, event.getAccessDeniedException()); assertThat(event.getAccessDeniedException()).isSameAs(exception);
assertSame(foo, event.getAuthentication()); assertThat(event.getAuthentication()).isSameAs(foo);
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,6 @@
package org.springframework.security.access.expression.method; 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.any;
import static org.mockito.Matchers.eq; import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
@ -44,19 +44,19 @@ public class MethodSecurityExpressionRootTests {
ctx.setVariable("var", "somestring"); ctx.setVariable("var", "somestring");
Expression e = parser.parseExpression("#var.length() == 10"); Expression e = parser.parseExpression("#var.length() == 10");
assertTrue(ExpressionUtils.evaluateAsBoolean(e, ctx)); assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isTrue();
} }
@Test @Test
public void isAnonymousReturnsTrueIfTrustResolverReportsAnonymous() { public void isAnonymousReturnsTrueIfTrustResolverReportsAnonymous() {
when(trustResolver.isAnonymous(user)).thenReturn(true); when(trustResolver.isAnonymous(user)).thenReturn(true);
assertTrue(root.isAnonymous()); assertThat(root.isAnonymous()).isTrue();
} }
@Test @Test
public void isAnonymousReturnsFalseIfTrustResolverReportsNonAnonymous() { public void isAnonymousReturnsFalseIfTrustResolverReportsNonAnonymous() {
when(trustResolver.isAnonymous(user)).thenReturn(false); when(trustResolver.isAnonymous(user)).thenReturn(false);
assertFalse(root.isAnonymous()); assertThat(root.isAnonymous()).isFalse();
} }
@Test @Test
@ -68,7 +68,7 @@ public class MethodSecurityExpressionRootTests {
root.setPermissionEvaluator(pe); root.setPermissionEvaluator(pe);
when(pe.hasPermission(user, dummyDomainObject, "ignored")).thenReturn(false); 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); root.setPermissionEvaluator(pe);
when(pe.hasPermission(user, dummyDomainObject, "ignored")).thenReturn(true); when(pe.hasPermission(user, dummyDomainObject, "ignored")).thenReturn(true);
assertTrue(root.hasPermission(dummyDomainObject, "ignored")); assertThat(root.hasPermission(dummyDomainObject, "ignored")).isTrue();
} }
@Test @Test
@ -95,13 +95,13 @@ public class MethodSecurityExpressionRootTests {
Expression e = parser.parseExpression("hasPermission(#domainObject, 0xA)"); Expression e = parser.parseExpression("hasPermission(#domainObject, 0xA)");
// evaluator returns true // evaluator returns true
assertTrue(ExpressionUtils.evaluateAsBoolean(e, ctx)); assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isTrue();
e = parser.parseExpression("hasPermission(#domainObject, 10)"); e = parser.parseExpression("hasPermission(#domainObject, 10)");
// evaluator returns true // evaluator returns true
assertTrue(ExpressionUtils.evaluateAsBoolean(e, ctx)); assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isTrue();
e = parser.parseExpression("hasPermission(#domainObject, 0xFF)"); e = parser.parseExpression("hasPermission(#domainObject, 0xFF)");
// evaluator returns false, make sure return value matches // evaluator returns false, make sure return value matches
assertFalse(ExpressionUtils.evaluateAsBoolean(e, ctx)); assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isFalse();
} }
@Test @Test
@ -119,11 +119,11 @@ public class MethodSecurityExpressionRootTests {
when(pe.hasPermission(user, "x", i)).thenReturn(true); when(pe.hasPermission(user, "x", i)).thenReturn(true);
Expression e = parser.parseExpression("hasPermission(this, 2)"); Expression e = parser.parseExpression("hasPermission(this, 2)");
assertTrue(ExpressionUtils.evaluateAsBoolean(e, ctx)); assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isTrue();
e = parser.parseExpression("hasPermission(this, 2)"); e = parser.parseExpression("hasPermission(this, 2)");
assertFalse(ExpressionUtils.evaluateAsBoolean(e, ctx)); assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isFalse();
e = parser.parseExpression("hasPermission(this.x, 2)"); 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; package org.springframework.security.access.expression.method;
import static org.fest.assertions.Assertions.assertThat; import static org.assertj.core.api.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 java.lang.annotation.ElementType; import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited; import java.lang.annotation.Inherited;
@ -78,12 +74,12 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(voidImpl1).toArray( ConfigAttribute[] attrs = mds.getAttributes(voidImpl1).toArray(
new ConfigAttribute[0]); new ConfigAttribute[0]);
assertEquals(1, attrs.length); assertThat(attrs.length).isEqualTo(1);
assertTrue(attrs[0] instanceof PreInvocationExpressionAttribute); assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0]; PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0];
assertNotNull(pre.getAuthorizeExpression()); assertThat(pre.getAuthorizeExpression()).isNotNull();
assertEquals("someExpression", pre.getAuthorizeExpression().getExpressionString()); assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("someExpression");
assertNull(pre.getFilterExpression()); assertThat(pre.getFilterExpression()).isNull();
} }
@Test @Test
@ -91,13 +87,12 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(voidImpl2).toArray( ConfigAttribute[] attrs = mds.getAttributes(voidImpl2).toArray(
new ConfigAttribute[0]); new ConfigAttribute[0]);
assertEquals(1, attrs.length); assertThat(attrs.length).isEqualTo(1);
assertTrue(attrs[0] instanceof PreInvocationExpressionAttribute); assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0]; PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0];
assertEquals("someExpression", pre.getAuthorizeExpression().getExpressionString()); assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("someExpression");
assertNotNull(pre.getFilterExpression()); assertThat(pre.getFilterExpression()).isNotNull();
assertEquals("somePreFilterExpression", pre.getFilterExpression() assertThat(pre.getFilterExpression().getExpressionString()).isEqualTo("somePreFilterExpression");
.getExpressionString());
} }
@Test @Test
@ -105,13 +100,12 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(voidImpl3).toArray( ConfigAttribute[] attrs = mds.getAttributes(voidImpl3).toArray(
new ConfigAttribute[0]); new ConfigAttribute[0]);
assertEquals(1, attrs.length); assertThat(attrs.length).isEqualTo(1);
assertTrue(attrs[0] instanceof PreInvocationExpressionAttribute); assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0]; PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0];
assertEquals("permitAll", pre.getAuthorizeExpression().getExpressionString()); assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("permitAll");
assertNotNull(pre.getFilterExpression()); assertThat(pre.getFilterExpression()).isNotNull();
assertEquals("somePreFilterExpression", pre.getFilterExpression() assertThat(pre.getFilterExpression().getExpressionString()).isEqualTo("somePreFilterExpression");
.getExpressionString());
} }
@Test @Test
@ -119,15 +113,14 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(listImpl1).toArray( ConfigAttribute[] attrs = mds.getAttributes(listImpl1).toArray(
new ConfigAttribute[0]); new ConfigAttribute[0]);
assertEquals(2, attrs.length); assertThat(attrs.length).isEqualTo(2);
assertTrue(attrs[0] instanceof PreInvocationExpressionAttribute); assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
assertTrue(attrs[1] instanceof PostInvocationExpressionAttribute); assertThat(attrs[1] instanceof PostInvocationExpressionAttribute).isTrue();
PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0]; PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0];
PostInvocationExpressionAttribute post = (PostInvocationExpressionAttribute) attrs[1]; PostInvocationExpressionAttribute post = (PostInvocationExpressionAttribute) attrs[1];
assertEquals("permitAll", pre.getAuthorizeExpression().getExpressionString()); assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("permitAll");
assertNotNull(post.getFilterExpression()); assertThat(post.getFilterExpression()).isNotNull();
assertEquals("somePostFilterExpression", post.getFilterExpression() assertThat(post.getFilterExpression().getExpressionString()).isEqualTo("somePostFilterExpression");
.getExpressionString());
} }
@Test @Test
@ -135,15 +128,13 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(notherListImpl1).toArray( ConfigAttribute[] attrs = mds.getAttributes(notherListImpl1).toArray(
new ConfigAttribute[0]); new ConfigAttribute[0]);
assertEquals(1, attrs.length); assertThat(attrs.length).isEqualTo(1);
assertTrue(attrs[0] instanceof PreInvocationExpressionAttribute); assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0]; PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0];
assertNotNull(pre.getFilterExpression()); assertThat(pre.getFilterExpression()).isNotNull();
assertNotNull(pre.getAuthorizeExpression()); assertThat(pre.getAuthorizeExpression()).isNotNull();
assertEquals("interfaceMethodAuthzExpression", pre.getAuthorizeExpression() assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("interfaceMethodAuthzExpression");
.getExpressionString()); assertThat(pre.getFilterExpression().getExpressionString()).isEqualTo("interfacePreFilterExpression");
assertEquals("interfacePreFilterExpression", pre.getFilterExpression()
.getExpressionString());
} }
@Test @Test
@ -151,15 +142,13 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(notherListImpl2).toArray( ConfigAttribute[] attrs = mds.getAttributes(notherListImpl2).toArray(
new ConfigAttribute[0]); new ConfigAttribute[0]);
assertEquals(1, attrs.length); assertThat(attrs.length).isEqualTo(1);
assertTrue(attrs[0] instanceof PreInvocationExpressionAttribute); assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0]; PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0];
assertNotNull(pre.getFilterExpression()); assertThat(pre.getFilterExpression()).isNotNull();
assertNotNull(pre.getAuthorizeExpression()); assertThat(pre.getAuthorizeExpression()).isNotNull();
assertEquals("interfaceMethodAuthzExpression", pre.getAuthorizeExpression() assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("interfaceMethodAuthzExpression");
.getExpressionString()); assertThat(pre.getFilterExpression().getExpressionString()).isEqualTo("classMethodPreFilterExpression");
assertEquals("classMethodPreFilterExpression", pre.getFilterExpression()
.getExpressionString());
} }
@Test @Test
@ -167,7 +156,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtClassLevel).toArray( ConfigAttribute[] attrs = mds.getAttributes(annotatedAtClassLevel).toArray(
new ConfigAttribute[0]); new ConfigAttribute[0]);
assertEquals(1, attrs.length); assertThat(attrs.length).isEqualTo(1);
} }
@Test @Test
@ -175,7 +164,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtInterfaceLevel).toArray( ConfigAttribute[] attrs = mds.getAttributes(annotatedAtInterfaceLevel).toArray(
new ConfigAttribute[0]); new ConfigAttribute[0]);
assertEquals(1, attrs.length); assertThat(attrs.length).isEqualTo(1);
} }
@Test @Test
@ -183,7 +172,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtMethodLevel).toArray( ConfigAttribute[] attrs = mds.getAttributes(annotatedAtMethodLevel).toArray(
new ConfigAttribute[0]); new ConfigAttribute[0]);
assertEquals(1, attrs.length); assertThat(attrs.length).isEqualTo(1);
} }
@Test @Test

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -15,6 +15,8 @@
package org.springframework.security.access.intercept; package org.springframework.security.access.intercept;
import static org.assertj.core.api.Assertions.assertThat;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.springframework.security.access.SecurityConfig; import org.springframework.security.access.SecurityConfig;
@ -35,16 +37,16 @@ public class NullRunAsManagerTests extends TestCase {
public void testAlwaysReturnsNull() { public void testAlwaysReturnsNull() {
NullRunAsManager runAs = new NullRunAsManager(); NullRunAsManager runAs = new NullRunAsManager();
assertNull(runAs.buildRunAs(null, null, null)); assertThat(runAs.buildRunAs(null, null, null)).isNull();
} }
public void testAlwaysSupportsClass() { public void testAlwaysSupportsClass() {
NullRunAsManager runAs = new NullRunAsManager(); NullRunAsManager runAs = new NullRunAsManager();
assertTrue(runAs.supports(String.class)); assertThat(runAs.supports(String.class)).isTrue();
} }
public void testNeverSupportsAttribute() { public void testNeverSupportsAttribute() {
NullRunAsManager runAs = new NullRunAsManager(); 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; package org.springframework.security.access.intercept;
import static org.junit.Assert.*; import static org.assertj.core.api.Assertions.*;
import org.junit.*; import org.junit.*;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
@ -54,7 +54,7 @@ public class RunAsImplAuthenticationProviderTests {
result instanceof RunAsUserToken); result instanceof RunAsUserToken);
RunAsUserToken resultCast = (RunAsUserToken) result; RunAsUserToken resultCast = (RunAsUserToken) result;
assertEquals("my_password".hashCode(), resultCast.getKeyHash()); assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
@ -68,14 +68,14 @@ public class RunAsImplAuthenticationProviderTests {
public void testStartupSuccess() throws Exception { public void testStartupSuccess() throws Exception {
RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider(); RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider();
provider.setKey("hello_world"); provider.setKey("hello_world");
assertEquals("hello_world", provider.getKey()); assertThat(provider.getKey()).isEqualTo("hello_world");
provider.afterPropertiesSet(); provider.afterPropertiesSet();
} }
@Test @Test
public void testSupports() { public void testSupports() {
RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider(); RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider();
assertTrue(provider.supports(RunAsUserToken.class)); assertThat(provider.supports(RunAsUserToken.class)).isTrue();
assertTrue(!provider.supports(TestingAuthenticationToken.class)); assertThat(!provider.supports(TestingAuthenticationToken.class)).isTrue();
} }
} }

View File

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

View File

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

View File

@ -15,6 +15,9 @@
package org.springframework.security.access.intercept.aopalliance; package org.springframework.security.access.intercept.aopalliance;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -42,7 +45,7 @@ public class MethodSecurityMetadataSourceAdvisorTests extends TestCase {
when(mds.getAttributes(method, clazz)).thenReturn(null); when(mds.getAttributes(method, clazz)).thenReturn(null);
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor( MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor(
"", mds, ""); "", mds, "");
assertFalse(advisor.getPointcut().getMethodMatcher().matches(method, clazz)); assertThat(advisor.getPointcut().getMethodMatcher().matches(method, clazz)).isFalse();
} }
public void testAdvisorReturnsTrueWhenMethodInvocationIsDefined() throws Exception { public void testAdvisorReturnsTrueWhenMethodInvocationIsDefined() throws Exception {
@ -54,6 +57,6 @@ public class MethodSecurityMetadataSourceAdvisorTests extends TestCase {
SecurityConfig.createList("ROLE_A")); SecurityConfig.createList("ROLE_A"));
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor( MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor(
"", mds, ""); "", 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; 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.Matchers.any;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
@ -134,10 +134,10 @@ public class AspectJMethodSecurityInterceptorTests {
when(joinPoint.getTarget()).thenReturn(to); when(joinPoint.getTarget()).thenReturn(to);
when(joinPoint.getArgs()).thenReturn(new Object[] { "Hi" }); when(joinPoint.getArgs()).thenReturn(new Object[] { "Hi" });
MethodInvocationAdapter mia = new MethodInvocationAdapter(joinPoint); MethodInvocationAdapter mia = new MethodInvocationAdapter(joinPoint);
assertEquals("Hi", mia.getArguments()[0]); assertThat(mia.getArguments()[0]).isEqualTo("Hi");
assertEquals(m, mia.getStaticPart()); assertThat(mia.getStaticPart()).isEqualTo(m);
assertEquals(m, mia.getMethod()); assertThat(mia.getMethod()).isEqualTo(m);
assertSame(to, mia.getThis()); assertThat(mia.getThis()).isSameAs(to);
} }
@Test @Test
@ -184,8 +184,8 @@ public class AspectJMethodSecurityInterceptorTests {
} }
// Check we've changed back // Check we've changed back
assertSame(ctx, SecurityContextHolder.getContext()); assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertSame(token, SecurityContextHolder.getContext().getAuthentication()); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token);
} }
// SEC-1967 // SEC-1967
@ -211,7 +211,7 @@ public class AspectJMethodSecurityInterceptorTests {
} }
// Check we've changed back // Check we've changed back
assertSame(ctx, SecurityContextHolder.getContext()); assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertSame(token, SecurityContextHolder.getContext().getAuthentication()); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token);
} }
} }

View File

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

View File

@ -15,7 +15,7 @@
package org.springframework.security.access.intercept.method; 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 static org.mockito.Mockito.*;
import java.util.*; import java.util.*;
@ -80,7 +80,7 @@ public class MethodInvocationPrivilegeEvaluatorTests {
mipe.setSecurityInterceptor(interceptor); mipe.setSecurityInterceptor(interceptor);
mipe.afterPropertiesSet(); mipe.afterPropertiesSet();
assertTrue(mipe.isAllowed(mi, token)); assertThat(mipe.isAllowed(mi, token)).isTrue();
} }
@Test @Test
@ -92,7 +92,7 @@ public class MethodInvocationPrivilegeEvaluatorTests {
mipe.setSecurityInterceptor(interceptor); mipe.setSecurityInterceptor(interceptor);
when(mds.getAttributes(mi)).thenReturn(role); when(mds.getAttributes(mi)).thenReturn(role);
assertTrue(mipe.isAllowed(mi, token)); assertThat(mipe.isAllowed(mi, token)).isTrue();
} }
@Test @Test
@ -105,7 +105,7 @@ public class MethodInvocationPrivilegeEvaluatorTests {
when(mds.getAttributes(mi)).thenReturn(role); when(mds.getAttributes(mi)).thenReturn(role);
doThrow(new AccessDeniedException("rejected")).when(adm).decide(token, mi, role); doThrow(new AccessDeniedException("rejected")).when(adm).decide(token, mi, role);
assertFalse(mipe.isAllowed(mi, token)); assertThat(mipe.isAllowed(mi, token)).isFalse();
} }
@Test @Test
@ -119,6 +119,6 @@ public class MethodInvocationPrivilegeEvaluatorTests {
when(mds.getAttributes(mi)).thenReturn(role); when(mds.getAttributes(mi)).thenReturn(role);
doThrow(new AccessDeniedException("rejected")).when(adm).decide(token, mi, 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; package org.springframework.security.access.method;
import static org.junit.Assert.*; import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import org.aopalliance.intercept.MethodInvocation; import org.aopalliance.intercept.MethodInvocation;
@ -27,13 +27,13 @@ public class DelegatingMethodSecurityMetadataSourceTests {
.thenReturn(null); .thenReturn(null);
sources.add(delegate); sources.add(delegate);
mds = new DelegatingMethodSecurityMetadataSource(sources); mds = new DelegatingMethodSecurityMetadataSource(sources);
assertSame(sources, mds.getMethodSecurityMetadataSources()); assertThat(mds.getMethodSecurityMetadataSources()).isSameAs(sources);
assertTrue(mds.getAllConfigAttributes().isEmpty()); assertThat(mds.getAllConfigAttributes().isEmpty()).isTrue();
MethodInvocation mi = new SimpleMethodInvocation(null, MethodInvocation mi = new SimpleMethodInvocation(null,
String.class.getMethod("toString")); String.class.getMethod("toString"));
assertEquals(Collections.emptyList(), mds.getAttributes(mi)); assertThat(mds.getAttributes(mi)).isEqualTo(Collections.emptyList());
// Exercise the cached case // Exercise the cached case
assertEquals(Collections.emptyList(), mds.getAttributes(mi)); assertThat(mds.getAttributes(mi)).isEqualTo(Collections.emptyList());
} }
@Test @Test
@ -46,15 +46,14 @@ public class DelegatingMethodSecurityMetadataSourceTests {
when(delegate.getAttributes(toString, String.class)).thenReturn(attributes); when(delegate.getAttributes(toString, String.class)).thenReturn(attributes);
sources.add(delegate); sources.add(delegate);
mds = new DelegatingMethodSecurityMetadataSource(sources); mds = new DelegatingMethodSecurityMetadataSource(sources);
assertSame(sources, mds.getMethodSecurityMetadataSources()); assertThat(mds.getMethodSecurityMetadataSources()).isSameAs(sources);
assertTrue(mds.getAllConfigAttributes().isEmpty()); assertThat(mds.getAllConfigAttributes().isEmpty()).isTrue();
MethodInvocation mi = new SimpleMethodInvocation("", toString); MethodInvocation mi = new SimpleMethodInvocation("", toString);
assertSame(attributes, mds.getAttributes(mi)); assertThat(mds.getAttributes(mi)).isSameAs(attributes);
// Exercise the cached case // Exercise the cached case
assertSame(attributes, mds.getAttributes(mi)); assertThat(mds.getAttributes(mi)).isSameAs(attributes);
assertTrue(mds.getAttributes( assertThat(mds.getAttributes(
new SimpleMethodInvocation(null, String.class.getMethod("length"))) new SimpleMethodInvocation(null, String.class.getMethod("length")))).isEmpty();;
.isEmpty());
} }
} }

View File

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

View File

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

View File

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

View File

@ -15,6 +15,8 @@
package org.springframework.security.access.vote; package org.springframework.security.access.vote;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
@ -95,19 +97,19 @@ public class AuthenticatedVoterTests extends TestCase {
fail("Expected IAE"); fail("Expected IAE");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertTrue(true);
} }
} }
public void testSupports() { public void testSupports() {
AuthenticatedVoter voter = new AuthenticatedVoter(); AuthenticatedVoter voter = new AuthenticatedVoter();
assertTrue(voter.supports(String.class)); assertThat(voter.supports(String.class)).isTrue();
assertTrue(voter.supports(new SecurityConfig( assertTrue(voter.supports(new SecurityConfig(
AuthenticatedVoter.IS_AUTHENTICATED_ANONYMOUSLY))); AuthenticatedVoter.IS_AUTHENTICATED_ANONYMOUSLY)));
assertTrue(voter.supports(new SecurityConfig( assertTrue(voter.supports(new SecurityConfig(
AuthenticatedVoter.IS_AUTHENTICATED_FULLY))); AuthenticatedVoter.IS_AUTHENTICATED_FULLY)));
assertTrue(voter.supports(new SecurityConfig( assertTrue(voter.supports(new SecurityConfig(
AuthenticatedVoter.IS_AUTHENTICATED_REMEMBERED))); 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; package org.springframework.security.access.vote;
import static org.junit.Assert.*; import static org.assertj.core.api.Assertions.*;
import org.junit.*; import org.junit.*;
import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.AccessDecisionVoter;
@ -39,7 +39,7 @@ public class ConsensusBasedTests {
TestingAuthenticationToken auth = makeTestToken(); TestingAuthenticationToken auth = makeTestToken();
ConsensusBased mgr = makeDecisionManager(); ConsensusBased mgr = makeDecisionManager();
mgr.setAllowIfEqualGrantedDeniedDecisions(false); mgr.setAllowIfEqualGrantedDeniedDecisions(false);
assertTrue(!mgr.isAllowIfEqualGrantedDeniedDecisions()); // check changed assertThat(!mgr.isAllowIfEqualGrantedDeniedDecisions()).isTrue(); // check changed
List<ConfigAttribute> config = SecurityConfig.createList("ROLE_1", List<ConfigAttribute> config = SecurityConfig.createList("ROLE_1",
"DENY_FOR_SURE"); "DENY_FOR_SURE");
@ -53,13 +53,13 @@ public class ConsensusBasedTests {
TestingAuthenticationToken auth = makeTestToken(); TestingAuthenticationToken auth = makeTestToken();
ConsensusBased mgr = makeDecisionManager(); ConsensusBased mgr = makeDecisionManager();
assertTrue(mgr.isAllowIfEqualGrantedDeniedDecisions()); // check default assertThat(mgr.isAllowIfEqualGrantedDeniedDecisions()).isTrue(); // check default
List<ConfigAttribute> config = SecurityConfig.createList("ROLE_1", List<ConfigAttribute> config = SecurityConfig.createList("ROLE_1",
"DENY_FOR_SURE"); "DENY_FOR_SURE");
mgr.decide(auth, new Object(), config); mgr.decide(auth, new Object(), config);
assertTrue(true);
} }
@Test @Test
@ -68,7 +68,7 @@ public class ConsensusBasedTests {
ConsensusBased mgr = makeDecisionManager(); ConsensusBased mgr = makeDecisionManager();
mgr.decide(auth, new Object(), SecurityConfig.createList("ROLE_2")); mgr.decide(auth, new Object(), SecurityConfig.createList("ROLE_2"));
assertTrue(true);
} }
@Test(expected = AccessDeniedException.class) @Test(expected = AccessDeniedException.class)
@ -85,7 +85,7 @@ public class ConsensusBasedTests {
TestingAuthenticationToken auth = makeTestToken(); TestingAuthenticationToken auth = makeTestToken();
ConsensusBased mgr = makeDecisionManager(); ConsensusBased mgr = makeDecisionManager();
assertTrue(!mgr.isAllowIfAllAbstainDecisions()); // check default assertThat(!mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
mgr.decide(auth, new Object(), SecurityConfig.createList("IGNORED_BY_ALL")); mgr.decide(auth, new Object(), SecurityConfig.createList("IGNORED_BY_ALL"));
} }
@ -95,7 +95,7 @@ public class ConsensusBasedTests {
TestingAuthenticationToken auth = makeTestToken(); TestingAuthenticationToken auth = makeTestToken();
ConsensusBased mgr = makeDecisionManager(); ConsensusBased mgr = makeDecisionManager();
mgr.setAllowIfAllAbstainDecisions(true); mgr.setAllowIfAllAbstainDecisions(true);
assertTrue(mgr.isAllowIfAllAbstainDecisions()); // check changed assertThat(mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check changed
mgr.decide(auth, new Object(), SecurityConfig.createList("IGNORED_BY_ALL")); mgr.decide(auth, new Object(), SecurityConfig.createList("IGNORED_BY_ALL"));
} }

View File

@ -1,6 +1,6 @@
package org.springframework.security.access.vote; 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.junit.Test;
import org.springframework.security.access.SecurityConfig; import org.springframework.security.access.SecurityConfig;
@ -20,7 +20,6 @@ public class RoleHierarchyVoterTests {
"password", "ROLE_A"); "password", "ROLE_A");
RoleHierarchyVoter voter = new RoleHierarchyVoter(roleHierarchyImpl); RoleHierarchyVoter voter = new RoleHierarchyVoter(roleHierarchyImpl);
assertEquals(RoleHierarchyVoter.ACCESS_GRANTED, assertThat(voter.vote(auth, new Object(), SecurityConfig.createList("ROLE_B"))).isEqualTo(RoleHierarchyVoter.ACCESS_GRANTED);
voter.vote(auth, new Object(), SecurityConfig.createList("ROLE_B")));
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -55,13 +55,13 @@ public class ReflectionSaltSourceTests {
ReflectionSaltSource saltSource = new ReflectionSaltSource(); ReflectionSaltSource saltSource = new ReflectionSaltSource();
saltSource.setUserPropertyToUse("getUsername"); saltSource.setUserPropertyToUse("getUsername");
assertEquals("scott", saltSource.getSalt(user)); assertThat(saltSource.getSalt(user)).isEqualTo("scott");
} }
@Test @Test
public void propertyNameAsPropertyToUseReturnsCorrectSaltValue() { public void propertyNameAsPropertyToUseReturnsCorrectSaltValue() {
ReflectionSaltSource saltSource = new ReflectionSaltSource(); ReflectionSaltSource saltSource = new ReflectionSaltSource();
saltSource.setUserPropertyToUse("password"); 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; 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; import org.springframework.security.authentication.dao.SystemWideSaltSource;
@ -57,21 +57,21 @@ public class SystemWideSaltSourceTests extends TestCase {
fail("Should have thrown IllegalArgumentException"); fail("Should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertEquals("A systemWideSalt must be set", expected.getMessage()); assertThat(expected.getMessage()).isEqualTo("A systemWideSalt must be set");
} }
} }
public void testGettersSetters() { public void testGettersSetters() {
SystemWideSaltSource saltSource = new SystemWideSaltSource(); SystemWideSaltSource saltSource = new SystemWideSaltSource();
saltSource.setSystemWideSalt("helloWorld"); saltSource.setSystemWideSalt("helloWorld");
assertEquals("helloWorld", saltSource.getSystemWideSalt()); assertThat(saltSource.getSystemWideSalt()).isEqualTo("helloWorld");
} }
public void testNormalOperation() throws Exception { public void testNormalOperation() throws Exception {
SystemWideSaltSource saltSource = new SystemWideSaltSource(); SystemWideSaltSource saltSource = new SystemWideSaltSource();
saltSource.setSystemWideSalt("helloWorld"); saltSource.setSystemWideSalt("helloWorld");
saltSource.afterPropertiesSet(); saltSource.afterPropertiesSet();
assertEquals("helloWorld", saltSource.getSalt(null)); assertThat(saltSource.getSalt(null)).isEqualTo("helloWorld");
} }
// SEC-2173 // SEC-2173

View File

@ -34,14 +34,14 @@ public class BasePasswordEncoderTests extends TestCase {
String merged = pwd.nowMergePasswordAndSalt("password", null, true); String merged = pwd.nowMergePasswordAndSalt("password", null, true);
String[] demerged = pwd.nowDemergePasswordAndSalt(merged); String[] demerged = pwd.nowDemergePasswordAndSalt(merged);
assertEquals("password", demerged[0]); assertThat(demerged[0]).isEqualTo("password");
assertEquals("", demerged[1]); assertThat(demerged[1]).isEqualTo("");
merged = pwd.nowMergePasswordAndSalt("password", "", true); merged = pwd.nowMergePasswordAndSalt("password", "", true);
demerged = pwd.nowDemergePasswordAndSalt(merged); demerged = pwd.nowDemergePasswordAndSalt(merged);
assertEquals("password", demerged[0]); assertThat(demerged[0]).isEqualTo("password");
assertEquals("", demerged[1]); assertThat(demerged[1]).isEqualTo("");
} }
public void testDemergeWithEmptyStringIsRejected() { public void testDemergeWithEmptyStringIsRejected() {
@ -52,7 +52,7 @@ public class BasePasswordEncoderTests extends TestCase {
fail("Should have thrown IllegalArgumentException"); fail("Should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { 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"); fail("Should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { 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(); MockPasswordEncoder pwd = new MockPasswordEncoder();
String merged = pwd.nowMergePasswordAndSalt("password", "foo", true); String merged = pwd.nowMergePasswordAndSalt("password", "foo", true);
assertEquals("password{foo}", merged); assertThat(merged).isEqualTo("password{foo}");
String[] demerged = pwd.nowDemergePasswordAndSalt(merged); String[] demerged = pwd.nowDemergePasswordAndSalt(merged);
assertEquals("password", demerged[0]); assertThat(demerged[0]).isEqualTo("password");
assertEquals("foo", demerged[1]); assertThat(demerged[1]).isEqualTo("foo");
} }
public void testMergeDemergeWithDelimitersInPassword() { public void testMergeDemergeWithDelimitersInPassword() {
MockPasswordEncoder pwd = new MockPasswordEncoder(); MockPasswordEncoder pwd = new MockPasswordEncoder();
String merged = pwd.nowMergePasswordAndSalt("p{ass{w{o}rd", "foo", true); 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); String[] demerged = pwd.nowDemergePasswordAndSalt(merged);
assertEquals("p{ass{w{o}rd", demerged[0]); assertThat(demerged[0]).isEqualTo("p{ass{w{o}rd");
assertEquals("foo", demerged[1]); assertThat(demerged[1]).isEqualTo("foo");
} }
public void testMergeDemergeWithNullAsPassword() { public void testMergeDemergeWithNullAsPassword() {
MockPasswordEncoder pwd = new MockPasswordEncoder(); MockPasswordEncoder pwd = new MockPasswordEncoder();
String merged = pwd.nowMergePasswordAndSalt(null, "foo", true); String merged = pwd.nowMergePasswordAndSalt(null, "foo", true);
assertEquals("{foo}", merged); assertThat(merged).isEqualTo("{foo}");
String[] demerged = pwd.nowDemergePasswordAndSalt(merged); String[] demerged = pwd.nowDemergePasswordAndSalt(merged);
assertEquals("", demerged[0]); assertThat(demerged[0]).isEqualTo("");
assertEquals("foo", demerged[1]); assertThat(demerged[1]).isEqualTo("foo");
} }
public void testStrictMergeRejectsDelimitersInSalt1() { public void testStrictMergeRejectsDelimitersInSalt1() {
@ -110,7 +110,7 @@ public class BasePasswordEncoderTests extends TestCase {
fail("Should have thrown IllegalArgumentException"); fail("Should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { 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"); fail("Should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { 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(); Md4PasswordEncoder md4 = new Md4PasswordEncoder();
md4.setEncodeHashAsBase64(true); md4.setEncodeHashAsBase64(true);
String encodedPassword = md4.encodePassword("ww_uni123", null); String encodedPassword = md4.encodePassword("ww_uni123", null);
assertEquals("8zobtq72iAt0W6KNqavGwg==", encodedPassword); assertThat(encodedPassword).isEqualTo("8zobtq72iAt0W6KNqavGwg==");
} }
public void testEncodeSaltedPassword() { public void testEncodeSaltedPassword() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder(); Md4PasswordEncoder md4 = new Md4PasswordEncoder();
md4.setEncodeHashAsBase64(true); md4.setEncodeHashAsBase64(true);
String encodedPassword = md4.encodePassword("ww_uni123", "Alan K Stewart"); String encodedPassword = md4.encodePassword("ww_uni123", "Alan K Stewart");
assertEquals("ZplT6P5Kv6Rlu6W4FIoYNA==", encodedPassword); assertThat(encodedPassword).isEqualTo("ZplT6P5Kv6Rlu6W4FIoYNA==");
} }
public void testEncodeNullPassword() { public void testEncodeNullPassword() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder(); Md4PasswordEncoder md4 = new Md4PasswordEncoder();
md4.setEncodeHashAsBase64(true); md4.setEncodeHashAsBase64(true);
String encodedPassword = md4.encodePassword(null, null); String encodedPassword = md4.encodePassword(null, null);
assertEquals("MdbP4NFq6TG3PFnX4MCJwA==", encodedPassword); assertThat(encodedPassword).isEqualTo("MdbP4NFq6TG3PFnX4MCJwA==");
} }
public void testEncodeEmptyPassword() { public void testEncodeEmptyPassword() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder(); Md4PasswordEncoder md4 = new Md4PasswordEncoder();
md4.setEncodeHashAsBase64(true); md4.setEncodeHashAsBase64(true);
String encodedPassword = md4.encodePassword("", null); String encodedPassword = md4.encodePassword("", null);
assertEquals("MdbP4NFq6TG3PFnX4MCJwA==", encodedPassword); assertThat(encodedPassword).isEqualTo("MdbP4NFq6TG3PFnX4MCJwA==");
} }
public void testNonAsciiPasswordHasCorrectHash() { public void testNonAsciiPasswordHasCorrectHash() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder(); Md4PasswordEncoder md4 = new Md4PasswordEncoder();
String encodedPassword = md4.encodePassword("\u4F60\u597d", null); String encodedPassword = md4.encodePassword("\u4F60\u597d", null);
assertEquals("a7f1196539fd1f85f754ffd185b16e6e", encodedPassword); assertThat(encodedPassword).isEqualTo("a7f1196539fd1f85f754ffd185b16e6e");
} }
public void testIsHexPasswordValid() { public void testIsHexPasswordValid() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder(); Md4PasswordEncoder md4 = new Md4PasswordEncoder();
assertTrue(md4.isPasswordValid("31d6cfe0d16ae931b73c59d7e0c089c0", "", null)); assertThat(md4.isPasswordValid("31d6cfe0d16ae931b73c59d7e0c089c0", "", null)).isTrue();
} }
public void testIsPasswordValid() { public void testIsPasswordValid() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder(); Md4PasswordEncoder md4 = new Md4PasswordEncoder();
md4.setEncodeHashAsBase64(true); md4.setEncodeHashAsBase64(true);
assertTrue(md4.isPasswordValid("8zobtq72iAt0W6KNqavGwg==", "ww_uni123", null)); assertThat(md4.isPasswordValid("8zobtq72iAt0W6KNqavGwg==", "ww_uni123", null)).isTrue();
} }
public void testIsSaltedPasswordValid() { public void testIsSaltedPasswordValid() {

View File

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

View File

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