Convert to assertj

Fixes gh-3175
This commit is contained in:
Billy Korando 2015-12-19 09:29:21 -06:00 committed by Rob Winch
parent bb600a473e
commit 71d4ce96ad
153 changed files with 2472 additions and 2202 deletions

View File

@ -1,22 +1,23 @@
package org.springframework.security.acls;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import org.junit.Test;
import org.springframework.security.acls.domain.AclFormattingUtils;
import org.springframework.security.acls.model.Permission;
import junit.framework.TestCase;
/**
* Tests for {@link AclFormattingUtils}.
*
* @author Andrei Stefan
*/
public class AclFormattingUtilsTests extends TestCase {
public class AclFormattingUtilsTests {
// ~ Methods
// ========================================================================================================
@Test
public final void testDemergePatternsParametersConstraints() throws Exception {
try {
AclFormattingUtils.demergePatterns(null, "SOME STRING");
@ -47,15 +48,20 @@ public class AclFormattingUtilsTests extends TestCase {
}
}
@Test
public final void testDemergePatterns() throws Exception {
String original = "...........................A...R";
String removeBits = "...............................R";
assertThat(AclFormattingUtils.demergePatterns(original, removeBits)).isEqualTo("...........................A....");
assertThat(AclFormattingUtils.demergePatterns(original, removeBits)).isEqualTo(
"...........................A....");
assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "......")).isEqualTo("ABCDEF");
assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL")).isEqualTo("......");
assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "......")).isEqualTo(
"ABCDEF");
assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL")).isEqualTo(
"......");
}
@Test
public final void testMergePatternsParametersConstraints() throws Exception {
try {
AclFormattingUtils.mergePatterns(null, "SOME STRING");
@ -85,22 +91,23 @@ public class AclFormattingUtilsTests extends TestCase {
}
}
@Test
public final void testMergePatterns() throws Exception {
String original = "...............................R";
String extraBits = "...........................A....";
assertThat(
AclFormattingUtils.mergePatterns(original, extraBits)).isEqualTo("...........................A...R");
assertThat(AclFormattingUtils.mergePatterns(original, extraBits)).isEqualTo(
"...........................A...R");
assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "......"))
.isEqualTo("ABCDEF");
assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL"))
.isEqualTo("GHIJKL");
assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "......")).isEqualTo(
"ABCDEF");
assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL")).isEqualTo(
"GHIJKL");
}
@Test
public final void testBinaryPrints() throws Exception {
assertThat(
AclFormattingUtils.printBinary(15))
.isEqualTo("............................****");
assertThat(AclFormattingUtils.printBinary(15)).isEqualTo(
"............................****");
try {
AclFormattingUtils.printBinary(15, Permission.RESERVED_ON);
@ -116,20 +123,19 @@ public class AclFormattingUtilsTests extends TestCase {
catch (IllegalArgumentException notExpected) {
}
assertThat(
AclFormattingUtils.printBinary(15, 'x'))
.isEqualTo("............................xxxx");
assertThat(AclFormattingUtils.printBinary(15, 'x')).isEqualTo(
"............................xxxx");
}
@Test
public void testPrintBinaryNegative() {
assertThat(
AclFormattingUtils.printBinary(0x80000000))
.isEqualTo("*...............................");
assertThat(AclFormattingUtils.printBinary(0x80000000)).isEqualTo(
"*...............................");
}
@Test
public void testPrintBinaryMinusOne() {
assertThat(
AclFormattingUtils.printBinary(0xffffffff))
.isEqualTo("********************************");
assertThat(AclFormattingUtils.printBinary(0xffffffff)).isEqualTo(
"********************************");
}
}

View File

@ -1,24 +1,22 @@
package org.springframework.security.acls.domain;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.*;
import org.springframework.security.acls.domain.ObjectIdentityImpl;
import org.springframework.security.acls.domain.ObjectIdentityRetrievalStrategyImpl;
import org.junit.Test;
import org.springframework.security.acls.model.ObjectIdentity;
import org.springframework.security.acls.model.ObjectIdentityRetrievalStrategy;
import junit.framework.TestCase;
/**
* Tests for {@link ObjectIdentityRetrievalStrategyImpl}
*
* @author Andrei Stefan
*/
public class ObjectIdentityRetrievalStrategyImplTests extends TestCase {
public class ObjectIdentityRetrievalStrategyImplTests {
// ~ Methods
// ========================================================================================================
@Test
public void testObjectIdentityCreation() throws Exception {
MockIdDomainObject domain = new MockIdDomainObject();
domain.setId(Integer.valueOf(1));
@ -34,6 +32,7 @@ public class ObjectIdentityRetrievalStrategyImplTests extends TestCase {
// ==================================================================================================
@SuppressWarnings("unused")
private class MockIdDomainObject {
private Object id;
public Object getId() {

View File

@ -1,8 +1,10 @@
package org.springframework.security.acls.sid;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.security.acls.domain.GrantedAuthoritySid;
import org.springframework.security.acls.domain.PrincipalSid;
import org.springframework.security.acls.model.Sid;
@ -11,11 +13,11 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
public class SidTests extends TestCase {
public class SidTests {
// ~ Methods
// ========================================================================================================
@Test
public void testPrincipalSidConstructorsRequiredFields() throws Exception {
// Check one String-argument constructor
try {
@ -60,6 +62,7 @@ public class SidTests extends TestCase {
// throws no exception
}
@Test
public void testGrantedAuthoritySidConstructorsRequiredFields() throws Exception {
// Check one String-argument constructor
try {
@ -116,6 +119,7 @@ public class SidTests extends TestCase {
}
}
@Test
public void testPrincipalSidEquals() throws Exception {
Authentication authentication = new TestingAuthenticationToken("johndoe",
"password");
@ -125,14 +129,15 @@ public class SidTests extends TestCase {
assertThat(principalSid.equals("DIFFERENT_TYPE_OBJECT")).isFalse();
assertThat(principalSid.equals(principalSid)).isTrue();
assertThat(principalSid.equals(new PrincipalSid(authentication))).isTrue();
assertTrue(principalSid.equals(new PrincipalSid(
new TestingAuthenticationToken("johndoe", null))));
assertFalse(principalSid.equals(new PrincipalSid(
new TestingAuthenticationToken("scott", null))));
assertThat(principalSid.equals(new PrincipalSid(
new TestingAuthenticationToken("johndoe", null)))).isTrue();
assertThat(principalSid.equals(new PrincipalSid(
new TestingAuthenticationToken("scott", null)))).isFalse();
assertThat(principalSid.equals(new PrincipalSid("johndoe"))).isTrue();
assertThat(principalSid.equals(new PrincipalSid("scott"))).isFalse();
}
@Test
public void testGrantedAuthoritySidEquals() throws Exception {
GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST");
Sid gaSid = new GrantedAuthoritySid(ga);
@ -141,39 +146,44 @@ public class SidTests extends TestCase {
assertThat(gaSid.equals("DIFFERENT_TYPE_OBJECT")).isFalse();
assertThat(gaSid.equals(gaSid)).isTrue();
assertThat(gaSid.equals(new GrantedAuthoritySid(ga))).isTrue();
assertTrue(gaSid.equals(new GrantedAuthoritySid(
new SimpleGrantedAuthority("ROLE_TEST"))));
assertFalse(gaSid.equals(new GrantedAuthoritySid(
new SimpleGrantedAuthority("ROLE_NOT_EQUAL"))));
assertThat(gaSid.equals(new GrantedAuthoritySid(
new SimpleGrantedAuthority("ROLE_TEST")))).isTrue();
assertThat(gaSid.equals(new GrantedAuthoritySid(
new SimpleGrantedAuthority("ROLE_NOT_EQUAL")))).isFalse();
assertThat(gaSid.equals(new GrantedAuthoritySid("ROLE_TEST"))).isTrue();
assertThat(gaSid.equals(new GrantedAuthoritySid("ROLE_NOT_EQUAL"))).isFalse();
}
@Test
public void testPrincipalSidHashCode() throws Exception {
Authentication authentication = new TestingAuthenticationToken("johndoe",
"password");
Sid principalSid = new PrincipalSid(authentication);
assertThat(principalSid.hashCode()).isSameAs("johndoe".hashCode());
assertThat(principalSid.hashCode()).isSameAs(new PrincipalSid("johndoe").hashCode());
assertThat(principalSid.hashCode()).isNotEqualTo(new PrincipalSid("scott").hashCode());
assertThat(principalSid.hashCode()).isEqualTo("johndoe".hashCode());
assertThat(principalSid.hashCode()).isEqualTo(
new PrincipalSid("johndoe").hashCode());
assertThat(principalSid.hashCode()).isNotEqualTo(
new PrincipalSid("scott").hashCode());
assertThat(principalSid.hashCode()).isNotEqualTo(new PrincipalSid(
new TestingAuthenticationToken("scott", "password")).hashCode());
}
@Test
public void testGrantedAuthoritySidHashCode() throws Exception {
GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST");
Sid gaSid = new GrantedAuthoritySid(ga);
assertThat(gaSid.hashCode()).isEqualTo("ROLE_TEST".hashCode());
assertThat(gaSid.hashCode()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST")
.hashCode());
assertThat(gaSid.hashCode()).isNotEqualTo(new GrantedAuthoritySid("ROLE_TEST_2")
.hashCode());
assertThat(gaSid.hashCode()).isEqualTo(
new GrantedAuthoritySid("ROLE_TEST").hashCode());
assertThat(gaSid.hashCode()).isNotEqualTo(
new GrantedAuthoritySid("ROLE_TEST_2").hashCode());
assertThat(gaSid.hashCode()).isNotEqualTo(new GrantedAuthoritySid(
new SimpleGrantedAuthority("ROLE_TEST_2")).hashCode());
}
@Test
public void testGetters() throws Exception {
Authentication authentication = new TestingAuthenticationToken("johndoe",
"password");

View File

@ -15,11 +15,14 @@
package org.springframework.security.cas.authentication;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.List;
import junit.framework.TestCase;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.AssertionImpl;
import org.junit.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
@ -27,14 +30,13 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.*;
/**
* Tests {@link CasAuthenticationToken}.
*
* @author Ben Alex
*/
public class CasAuthenticationTokenTests extends TestCase {
public class CasAuthenticationTokenTests {
private final List<GrantedAuthority> ROLES = AuthorityUtils.createAuthorityList(
"ROLE_ONE", "ROLE_TWO");
@ -46,10 +48,7 @@ public class CasAuthenticationTokenTests extends TestCase {
return new User(name, "password", true, true, true, true, ROLES);
}
public final void setUp() throws Exception {
super.setUp();
}
@Test
public void testConstructorRejectsNulls() {
final Assertion assertion = new AssertionImpl("test");
try {
@ -94,14 +93,15 @@ public class CasAuthenticationTokenTests extends TestCase {
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password",
AuthorityUtils.createAuthorityList("ROLE_1", null),
makeUserDetails(), assertion);
AuthorityUtils.createAuthorityList("ROLE_1", null), makeUserDetails(),
assertion);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testEqualsWhenEqual() {
final Assertion assertion = new AssertionImpl("test");
@ -114,6 +114,7 @@ public class CasAuthenticationTokenTests extends TestCase {
assertThat(token2).isEqualTo(token1);
}
@Test
public void testGetters() {
// Build the proxy list returned in the ticket from CAS
final Assertion assertion = new AssertionImpl("test");
@ -122,14 +123,16 @@ public class CasAuthenticationTokenTests extends TestCase {
assertThat(token.getKeyHash()).isEqualTo("key".hashCode());
assertThat(token.getPrincipal()).isEqualTo(makeUserDetails());
assertThat(token.getCredentials()).isEqualTo("Password");
assertThat(token.getAuthorities())
.contains(new SimpleGrantedAuthority("ROLE_ONE"));
assertThat(token.getAuthorities())
.contains(new SimpleGrantedAuthority("ROLE_TWO"));
assertThat(token.getAuthorities()).contains(
new SimpleGrantedAuthority("ROLE_ONE"));
assertThat(token.getAuthorities()).contains(
new SimpleGrantedAuthority("ROLE_TWO"));
assertThat(token.getAssertion()).isEqualTo(assertion);
assertThat(token.getUserDetails().getUsername()).isEqualTo(makeUserDetails().getUsername());
assertThat(token.getUserDetails().getUsername()).isEqualTo(
makeUserDetails().getUsername());
}
@Test
public void testNoArgConstructorDoesntExist() {
try {
CasAuthenticationToken.class.getDeclaredConstructor((Class[]) null);
@ -140,6 +143,7 @@ public class CasAuthenticationTokenTests extends TestCase {
}
}
@Test
public void testNotEqualsDueToAbstractParentEqualsCheck() {
final Assertion assertion = new AssertionImpl("test");
@ -153,6 +157,7 @@ public class CasAuthenticationTokenTests extends TestCase {
assertThat(!token1.equals(token2)).isTrue();
}
@Test
public void testNotEqualsDueToDifferentAuthenticationClass() {
final Assertion assertion = new AssertionImpl("test");
@ -164,6 +169,7 @@ public class CasAuthenticationTokenTests extends TestCase {
assertThat(!token1.equals(token2)).isTrue();
}
@Test
public void testNotEqualsDueToKey() {
final Assertion assertion = new AssertionImpl("test");
@ -176,6 +182,7 @@ public class CasAuthenticationTokenTests extends TestCase {
assertThat(!token1.equals(token2)).isTrue();
}
@Test
public void testNotEqualsDueToAssertion() {
final Assertion assertion = new AssertionImpl("test");
final Assertion assertion2 = new AssertionImpl("test");
@ -189,6 +196,7 @@ public class CasAuthenticationTokenTests extends TestCase {
assertThat(!token1.equals(token2)).isTrue();
}
@Test
public void testSetAuthenticated() {
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key",
@ -198,11 +206,13 @@ public class CasAuthenticationTokenTests extends TestCase {
assertThat(!token.isAuthenticated()).isTrue();
}
@Test
public void testToString() {
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key",
makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion);
String result = token.toString();
assertThat(result.lastIndexOf("Credentials (Service/Proxy Ticket):") != -1).isTrue();
assertThat(
result.lastIndexOf("Credentials (Service/Proxy Ticket):") != -1).isTrue();
}
}

View File

@ -15,26 +15,26 @@
package org.springframework.security.cas.web;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import junit.framework.TestCase;
import java.net.URLEncoder;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.web.CasAuthenticationEntryPoint;
import java.net.URLEncoder;
/**
* Tests {@link CasAuthenticationEntryPoint}.
*
* @author Ben Alex
*/
public class CasAuthenticationEntryPointTests extends TestCase {
public class CasAuthenticationEntryPointTests {
// ~ Methods
// ========================================================================================================
@Test
public void testDetectsMissingLoginFormUrl() throws Exception {
CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint();
ep.setServiceProperties(new ServiceProperties());
@ -48,6 +48,7 @@ public class CasAuthenticationEntryPointTests extends TestCase {
}
}
@Test
public void testDetectsMissingServiceProperties() throws Exception {
CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint();
ep.setLoginUrl("https://cas/login");
@ -57,10 +58,12 @@ public class CasAuthenticationEntryPointTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("serviceProperties must be specified");
assertThat(expected.getMessage()).isEqualTo(
"serviceProperties must be specified");
}
}
@Test
public void testGettersSetters() {
CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint();
ep.setLoginUrl("https://cas/login");
@ -70,6 +73,7 @@ public class CasAuthenticationEntryPointTests extends TestCase {
assertThat(ep.getServiceProperties() != null).isTrue();
}
@Test
public void testNormalOperationWithRenewFalse() throws Exception {
ServiceProperties sp = new ServiceProperties();
sp.setSendRenew(false);
@ -87,12 +91,12 @@ public class CasAuthenticationEntryPointTests extends TestCase {
ep.afterPropertiesSet();
ep.commence(request, response, null);
assertEquals(
"https://cas/login?service="
+ URLEncoder.encode("https://mycompany.com/bigWebApp/login/cas",
"UTF-8"), response.getRedirectedUrl());
assertThat("https://cas/login?service=" + URLEncoder.encode(
"https://mycompany.com/bigWebApp/login/cas", "UTF-8")).isEqualTo(
response.getRedirectedUrl());
}
@Test
public void testNormalOperationWithRenewTrue() throws Exception {
ServiceProperties sp = new ServiceProperties();
sp.setSendRenew(true);
@ -109,9 +113,8 @@ public class CasAuthenticationEntryPointTests extends TestCase {
ep.afterPropertiesSet();
ep.commence(request, response, null);
assertEquals(
"https://cas/login?service="
+ URLEncoder.encode("https://mycompany.com/bigWebApp/login/cas",
"UTF-8") + "&renew=true", response.getRedirectedUrl());
assertThat("https://cas/login?service="
+ URLEncoder.encode("https://mycompany.com/bigWebApp/login/cas", "UTF-8")
+ "&renew=true").isEqualTo(response.getRedirectedUrl());
}
}

View File

@ -1,8 +1,7 @@
package org.springframework.security.config.http;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
@ -23,9 +22,11 @@ import org.springframework.security.web.access.intercept.DefaultFilterInvocation
/**
* Tests for {@link FilterInvocationSecurityMetadataSourceParser}.
*
* @author Luke Taylor
*/
public class FilterSecurityMetadataSourceBeanDefinitionParserTests {
private AbstractXmlApplicationContext appContext;
@After
@ -45,10 +46,10 @@ public class FilterSecurityMetadataSourceBeanDefinitionParserTests {
setContext("<filter-security-metadata-source id='fids' use-expressions='false'>"
+ " <intercept-url pattern='/**' access='ROLE_A'/>"
+ "</filter-security-metadata-source>");
DefaultFilterInvocationSecurityMetadataSource fids = (DefaultFilterInvocationSecurityMetadataSource) appContext
.getBean("fids");
Collection<ConfigAttribute> cad = fids.getAttributes(createFilterInvocation(
"/anything", "GET"));
DefaultFilterInvocationSecurityMetadataSource fids = (DefaultFilterInvocationSecurityMetadataSource) appContext.getBean(
"fids");
Collection<ConfigAttribute> cad = fids.getAttributes(
createFilterInvocation("/anything", "GET"));
assertThat(cad).isNotNull();
assertThat(cad.contains(new SecurityConfig("ROLE_A"))).isTrue();
}
@ -59,11 +60,11 @@ public class FilterSecurityMetadataSourceBeanDefinitionParserTests {
+ " <intercept-url pattern='/**' access=\"hasRole('ROLE_A')\" />"
+ "</filter-security-metadata-source>");
ExpressionBasedFilterInvocationSecurityMetadataSource fids = (ExpressionBasedFilterInvocationSecurityMetadataSource) appContext
.getBean("fids");
ExpressionBasedFilterInvocationSecurityMetadataSource fids = (ExpressionBasedFilterInvocationSecurityMetadataSource) appContext.getBean(
"fids");
ConfigAttribute[] cad = fids.getAttributes(
createFilterInvocation("/anything", "GET")).toArray(
new ConfigAttribute[0]);
new ConfigAttribute[0]);
assertThat(cad.length).isEqualTo(1);
assertThat(cad[0].toString()).isEqualTo("hasRole('ROLE_A')");
}
@ -73,14 +74,15 @@ public class FilterSecurityMetadataSourceBeanDefinitionParserTests {
public void interceptUrlsSupportPropertyPlaceholders() {
System.setProperty("secure.url", "/secure");
System.setProperty("secure.role", "ROLE_A");
setContext("<b:bean class='org.springframework.beans.factory.config.PropertyPlaceholderConfigurer'/>"
+ "<filter-security-metadata-source id='fids' use-expressions='false'>"
+ " <intercept-url pattern='${secure.url}' access='${secure.role}'/>"
+ "</filter-security-metadata-source>");
DefaultFilterInvocationSecurityMetadataSource fids = (DefaultFilterInvocationSecurityMetadataSource) appContext
.getBean("fids");
Collection<ConfigAttribute> cad = fids.getAttributes(createFilterInvocation(
"/secure", "GET"));
setContext(
"<b:bean class='org.springframework.beans.factory.config.PropertyPlaceholderConfigurer'/>"
+ "<filter-security-metadata-source id='fids' use-expressions='false'>"
+ " <intercept-url pattern='${secure.url}' access='${secure.role}'/>"
+ "</filter-security-metadata-source>");
DefaultFilterInvocationSecurityMetadataSource fids = (DefaultFilterInvocationSecurityMetadataSource) appContext.getBean(
"fids");
Collection<ConfigAttribute> cad = fids.getAttributes(
createFilterInvocation("/secure", "GET"));
assertThat(cad).isNotNull();
assertThat(cad).hasSize(1);
assertThat(cad.contains(new SecurityConfig("ROLE_A"))).isTrue();

View File

@ -70,13 +70,13 @@ public class SecurityConfigTests {
assertThat(!security1.equals(security3)).isTrue();
MockConfigAttribute mock1 = new MockConfigAttribute("TEST");
assertThat(mock1).isEqualTo(security1);
assertThat(security1).isEqualTo(mock1);
MockConfigAttribute mock2 = new MockConfigAttribute("NOT_EQUAL");
assertThat(!security1.equals(mock2)).isTrue();
assertThat(security1).isNotEqualTo(mock2);
Integer int1 = Integer.valueOf(987);
assertThat(!security1.equals(int1)).isTrue();
assertThat(security1).isNotEqualTo(int1);
}
@Test

View File

@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.security.access.annotation;
import static org.assertj.core.api.Assertions.assertThat;
@ -22,7 +23,6 @@ import java.util.Collection;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.access.ConfigAttribute;
@ -33,8 +33,11 @@ import org.springframework.security.access.intercept.method.MockMethodInvocation
* @author Ben Alex
*/
public class Jsr250MethodSecurityMetadataSourceTests {
Jsr250MethodSecurityMetadataSource mds;
A a;
UserAllowedClass userAllowed;
@Before
@ -60,27 +63,28 @@ public class Jsr250MethodSecurityMetadataSourceTests {
public void permitAllMethodHasPermitAllAttribute() throws Exception {
ConfigAttribute[] accessAttributes = findAttributes("permitAllMethod");
assertThat(accessAttributes).hasSize(1);
assertThat(accessAttributes[0].toString()).isEqualTo("javax.annotation.security.PermitAll");
assertThat(accessAttributes[0].toString()).isEqualTo(
"javax.annotation.security.PermitAll");
}
@Test
public void noRoleMethodHasNoAttributes() throws Exception {
Collection<ConfigAttribute> accessAttributes = mds.findAttributes(a.getClass()
.getMethod("noRoleMethod"), null);
Collection<ConfigAttribute> accessAttributes = mds.findAttributes(
a.getClass().getMethod("noRoleMethod"), null);
assertThat(accessAttributes).isNull();
}
@Test
public void classRoleIsAppliedToNoRoleMethod() throws Exception {
Collection<ConfigAttribute> accessAttributes = mds.findAttributes(userAllowed
.getClass().getMethod("noRoleMethod"), null);
Collection<ConfigAttribute> accessAttributes = mds.findAttributes(
userAllowed.getClass().getMethod("noRoleMethod"), null);
assertThat(accessAttributes).isNull();
}
@Test
public void methodRoleOverridesClassRole() throws Exception {
Collection<ConfigAttribute> accessAttributes = mds.findAttributes(userAllowed
.getClass().getMethod("adminMethod"), null);
Collection<ConfigAttribute> accessAttributes = mds.findAttributes(
userAllowed.getClass().getMethod("adminMethod"), null);
assertThat(accessAttributes).hasSize(1);
assertThat(accessAttributes.toArray()[0].toString()).isEqualTo("ROLE_ADMIN");
}
@ -125,6 +129,7 @@ public class Jsr250MethodSecurityMetadataSourceTests {
* Class-level annotations only affect the class they annotate and their members, that
* is, its methods and fields. They never affect a member declared by a superclass,
* even if it is not hidden or overridden by the class in question.
*
* @throws Exception
*/
@Test
@ -162,7 +167,8 @@ public class Jsr250MethodSecurityMetadataSourceTests {
}
@Test
public void classLevelAnnotationsIgnoredByExplicitMemberAnnotation() throws Exception {
public void classLevelAnnotationsIgnoredByExplicitMemberAnnotation()
throws Exception {
Child target = new Child();
MockMethodInvocation mi = new MockMethodInvocation(target, target.getClass(),
"explicitMethod");
@ -175,6 +181,7 @@ public class Jsr250MethodSecurityMetadataSourceTests {
/**
* The interfaces implemented by a class never contribute annotations to the class
* itself or any of its members.
*
* @throws Exception
*/
@Test
@ -231,6 +238,7 @@ public class Jsr250MethodSecurityMetadataSourceTests {
@RolesAllowed("USER")
public static class UserAllowedClass {
public void noRoleMethod() {
}
@ -243,11 +251,13 @@ public class Jsr250MethodSecurityMetadataSourceTests {
@RolesAllowed("IPARENT")
interface IParent {
@RolesAllowed("INTERFACEMETHOD")
void interfaceMethod();
}
static class Parent implements IParent {
public void interfaceMethod() {
}
@ -264,6 +274,7 @@ public class Jsr250MethodSecurityMetadataSourceTests {
@RolesAllowed("DERIVED")
class Child extends Parent {
public void overriden() {
}

View File

@ -12,12 +12,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.access.annotation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.fail;
import java.lang.annotation.ElementType;
@ -78,7 +76,8 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
// should have 1 SecurityConfig
for (ConfigAttribute sc : attrs) {
assertThat(sc.getAttribute()).as("Found an incorrect role").isEqualTo("ROLE_ADMIN");
assertThat(sc.getAttribute()).as("Found an incorrect role").isEqualTo(
"ROLE_ADMIN");
}
Method superMethod = null;
@ -101,14 +100,15 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
assertThat(superAttrs).as("Did not find 1 attribute").hasSize(1);
// should have 1 SecurityConfig
for (ConfigAttribute sc : superAttrs) {
assertThat(sc.getAttribute()).as("Found an incorrect role").isEqualTo("ROLE_ADMIN");
assertThat(sc.getAttribute()).as("Found an incorrect role").isEqualTo(
"ROLE_ADMIN");
}
}
@Test
public void classLevelAttributesAreFound() {
Collection<ConfigAttribute> attrs = this.mds
.findAttributes(BusinessService.class);
Collection<ConfigAttribute> attrs = this.mds.findAttributes(
BusinessService.class);
assertThat(attrs).isNotNull();
@ -165,8 +165,8 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
public void customAnnotationAttributesAreFound() throws Exception {
SecuredAnnotationSecurityMetadataSource mds = new SecuredAnnotationSecurityMetadataSource(
new CustomSecurityAnnotationMetadataExtractor());
Collection<ConfigAttribute> attrs = mds
.findAttributes(CustomAnnotatedService.class);
Collection<ConfigAttribute> attrs = mds.findAttributes(
CustomAnnotatedService.class);
assertThat(attrs).hasSize(1);
assertThat(attrs.toArray()[0]).isEqualTo(SecurityEnum.ADMIN);
}
@ -219,19 +219,22 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
// Inner classes
class Department extends Entity {
public Department(String name) {
super(name);
}
}
interface DepartmentService extends BusinessService {
@Secured({ "ROLE_USER" })
Department someUserMethod3(Department dept);
}
@SuppressWarnings("serial")
class DepartmentServiceImpl extends BusinessServiceImpl<Department> implements
DepartmentService {
class DepartmentServiceImpl extends BusinessServiceImpl<Department>
implements DepartmentService {
@Secured({ "ROLE_ADMIN" })
public Department someUserMethod3(final Department dept) {
return super.someUserMethod3(dept);
@ -247,7 +250,7 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
class CustomAnnotatedServiceImpl implements CustomAnnotatedService {
}
enum SecurityEnum implements ConfigAttribute, GrantedAuthority {
enum SecurityEnum implements ConfigAttribute,GrantedAuthority {
ADMIN, USER;
public String getAttribute() {
@ -262,11 +265,13 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@interface CustomSecurityAnnotation {
SecurityEnum[] value();
SecurityEnum[]value();
}
class CustomSecurityAnnotationMetadataExtractor implements
AnnotationMetadataExtractor<CustomSecurityAnnotation> {
class CustomSecurityAnnotationMetadataExtractor
implements AnnotationMetadataExtractor<CustomSecurityAnnotation> {
public Collection<? extends ConfigAttribute> extractAttributes(
CustomSecurityAnnotation securityAnnotation) {
SecurityEnum[] values = securityAnnotation.value();
@ -283,26 +288,31 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
}
public static interface ReturnVoid {
public void doSomething(List<?> param);
}
@AnnotatedAnnotation
public static interface ReturnVoid2 {
public void doSomething(List<?> param);
}
@AnnotatedAnnotation
public static class AnnotatedAnnotationAtClassLevel implements ReturnVoid {
public void doSomething(List<?> param) {
}
}
public static class AnnotatedAnnotationAtInterfaceLevel implements ReturnVoid2 {
public void doSomething(List<?> param) {
}
}
public static class AnnotatedAnnotationAtMethodLevel implements ReturnVoid {
@AnnotatedAnnotation
public void doSomething(List<?> param) {
}

View File

@ -14,16 +14,13 @@
package org.springframework.security.access.hierarchicalroles;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.springframework.security.access.hierarchicalroles.CycleInRoleHierarchyException;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.junit.Test;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
@ -32,8 +29,9 @@ import org.springframework.security.core.authority.AuthorityUtils;
*
* @author Michael Mayr
*/
public class RoleHierarchyImplTests extends TestCase {
public class RoleHierarchyImplTests {
@Test
public void testRoleHierarchyWithNullOrEmptyAuthorities() {
List<GrantedAuthority> authorities0 = null;
List<GrantedAuthority> authorities1 = new ArrayList<GrantedAuthority>();
@ -41,93 +39,103 @@ public class RoleHierarchyImplTests extends TestCase {
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B");
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities0)).isNotNull();
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities0)).isEmpty();;
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities1)).isNotNull();
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(authorities1)).isEmpty();;
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(
authorities0)).isNotNull();
assertThat(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities0)).isEmpty();
;
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(
authorities1)).isNotNull();
assertThat(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1)).isEmpty();
;
}
@Test
public void testSimpleRoleHierarchy() {
List<GrantedAuthority> authorities0 = AuthorityUtils
.createAuthorityList("ROLE_0");
List<GrantedAuthority> authorities1 = AuthorityUtils
.createAuthorityList("ROLE_A");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_B");
List<GrantedAuthority> authorities0 = AuthorityUtils.createAuthorityList(
"ROLE_0");
List<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList(
"ROLE_A");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE_A",
"ROLE_B");
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B");
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities0),
authorities0));
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities0)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1),
authorities2));
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authorities2)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities2),
authorities2));
authorities2)).isTrue();
}
@Test
public void testTransitiveRoleHierarchies() {
List<GrantedAuthority> authorities1 = AuthorityUtils
.createAuthorityList("ROLE_A");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_B", "ROLE_C");
List<GrantedAuthority> authorities3 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_B", "ROLE_C", "ROLE_D");
List<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList(
"ROLE_A");
List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE_A",
"ROLE_B", "ROLE_C");
List<GrantedAuthority> authorities3 = AuthorityUtils.createAuthorityList("ROLE_A",
"ROLE_B", "ROLE_C", "ROLE_D");
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C");
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1),
authorities2));
authorities2)).isTrue();
roleHierarchyImpl
.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_D");
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.setHierarchy(
"ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_D");
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1),
authorities3));
authorities3)).isTrue();
}
@Test
public void testComplexRoleHierarchy() {
List<GrantedAuthority> authoritiesInput1 = AuthorityUtils
.createAuthorityList("ROLE_A");
List<GrantedAuthority> authoritiesInput1 = AuthorityUtils.createAuthorityList(
"ROLE_A");
List<GrantedAuthority> authoritiesOutput1 = AuthorityUtils.createAuthorityList(
"ROLE_A", "ROLE_B", "ROLE_C", "ROLE_D");
List<GrantedAuthority> authoritiesInput2 = AuthorityUtils
.createAuthorityList("ROLE_B");
List<GrantedAuthority> authoritiesInput2 = AuthorityUtils.createAuthorityList(
"ROLE_B");
List<GrantedAuthority> authoritiesOutput2 = AuthorityUtils.createAuthorityList(
"ROLE_B", "ROLE_D");
List<GrantedAuthority> authoritiesInput3 = AuthorityUtils
.createAuthorityList("ROLE_C");
List<GrantedAuthority> authoritiesInput3 = AuthorityUtils.createAuthorityList(
"ROLE_C");
List<GrantedAuthority> authoritiesOutput3 = AuthorityUtils.createAuthorityList(
"ROLE_C", "ROLE_D");
List<GrantedAuthority> authoritiesInput4 = AuthorityUtils
.createAuthorityList("ROLE_D");
List<GrantedAuthority> authoritiesOutput4 = AuthorityUtils
.createAuthorityList("ROLE_D");
List<GrantedAuthority> authoritiesInput4 = AuthorityUtils.createAuthorityList(
"ROLE_D");
List<GrantedAuthority> authoritiesOutput4 = AuthorityUtils.createAuthorityList(
"ROLE_D");
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
roleHierarchyImpl
.setHierarchy("ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D");
roleHierarchyImpl.setHierarchy(
"ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D");
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput1),
authoritiesOutput1));
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authoritiesOutput1)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput2),
authoritiesOutput2));
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authoritiesOutput2)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput3),
authoritiesOutput3));
assertTrue(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
authoritiesOutput3)).isTrue();
assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(
roleHierarchyImpl.getReachableGrantedAuthorities(authoritiesInput4),
authoritiesOutput4));
authoritiesOutput4)).isTrue();
}
@Test
public void testCyclesInRoleHierarchy() {
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
@ -146,28 +154,29 @@ public class RoleHierarchyImplTests extends TestCase {
}
try {
roleHierarchyImpl
.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_A");
roleHierarchyImpl.setHierarchy(
"ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_A");
fail("Cycle in role hierarchy was not detected!");
}
catch (CycleInRoleHierarchyException e) {
}
try {
roleHierarchyImpl
.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_E\nROLE_E > ROLE_D\nROLE_D > ROLE_B");
roleHierarchyImpl.setHierarchy(
"ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_E\nROLE_E > ROLE_D\nROLE_D > ROLE_B");
fail("Cycle in role hierarchy was not detected!");
}
catch (CycleInRoleHierarchyException e) {
}
}
@Test
public void testNoCyclesInRoleHierarchy() {
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
try {
roleHierarchyImpl
.setHierarchy("ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D");
roleHierarchyImpl.setHierarchy(
"ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D");
}
catch (CycleInRoleHierarchyException e) {
fail("A cycle in role hierarchy was incorrectly detected!");
@ -175,29 +184,30 @@ public class RoleHierarchyImplTests extends TestCase {
}
// SEC-863
@Test
public void testSimpleRoleHierarchyWithCustomGrantedAuthorityImplementation() {
List<GrantedAuthority> authorities0 = HierarchicalRolesTestHelper
.createAuthorityList("ROLE_0");
List<GrantedAuthority> authorities1 = HierarchicalRolesTestHelper
.createAuthorityList("ROLE_A");
List<GrantedAuthority> authorities2 = HierarchicalRolesTestHelper
.createAuthorityList("ROLE_A", "ROLE_B");
List<GrantedAuthority> authorities0 = HierarchicalRolesTestHelper.createAuthorityList(
"ROLE_0");
List<GrantedAuthority> authorities1 = HierarchicalRolesTestHelper.createAuthorityList(
"ROLE_A");
List<GrantedAuthority> authorities2 = HierarchicalRolesTestHelper.createAuthorityList(
"ROLE_A", "ROLE_B");
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B");
assertTrue(HierarchicalRolesTestHelper
.containTheSameGrantedAuthoritiesCompareByAuthorityString(
assertThat(
HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities0),
authorities0));
assertTrue(HierarchicalRolesTestHelper
.containTheSameGrantedAuthoritiesCompareByAuthorityString(
authorities0)).isTrue();
assertThat(
HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities1),
authorities2));
assertTrue(HierarchicalRolesTestHelper
.containTheSameGrantedAuthoritiesCompareByAuthorityString(
authorities2)).isTrue();
assertThat(
HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString(
roleHierarchyImpl.getReachableGrantedAuthorities(authorities2),
authorities2));
authorities2)).isTrue();
}
}

View File

@ -16,19 +16,18 @@
package org.springframework.security.access.intercept;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.Collection;
import java.util.List;
import java.util.Vector;
import junit.framework.TestCase;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.Test;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.AfterInvocationProvider;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.intercept.AfterInvocationProviderManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.util.SimpleMethodInvocation;
@ -38,11 +37,11 @@ import org.springframework.security.util.SimpleMethodInvocation;
* @author Ben Alex
*/
@SuppressWarnings("unchecked")
public class AfterInvocationProviderManagerTests extends TestCase {
public class AfterInvocationProviderManagerTests {
// ~ Methods
// ========================================================================================================
@Test
public void testCorrectOperation() throws Exception {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
List list = new Vector();
@ -56,16 +55,16 @@ public class AfterInvocationProviderManagerTests extends TestCase {
assertThat(manager.getProviders()).isEqualTo(list);
manager.afterPropertiesSet();
List<ConfigAttribute> attr1 = SecurityConfig
.createList(new String[] { "GIVE_ME_SWAP1" });
List<ConfigAttribute> attr2 = SecurityConfig
.createList(new String[] { "GIVE_ME_SWAP2" });
List<ConfigAttribute> attr3 = SecurityConfig
.createList(new String[] { "GIVE_ME_SWAP3" });
List<ConfigAttribute> attr2and3 = SecurityConfig.createList(new String[] {
"GIVE_ME_SWAP2", "GIVE_ME_SWAP3" });
List<ConfigAttribute> attr4 = SecurityConfig
.createList(new String[] { "NEVER_CAUSES_SWAP" });
List<ConfigAttribute> attr1 = SecurityConfig.createList(
new String[] { "GIVE_ME_SWAP1" });
List<ConfigAttribute> attr2 = SecurityConfig.createList(
new String[] { "GIVE_ME_SWAP2" });
List<ConfigAttribute> attr3 = SecurityConfig.createList(
new String[] { "GIVE_ME_SWAP3" });
List<ConfigAttribute> attr2and3 = SecurityConfig.createList(
new String[] { "GIVE_ME_SWAP2", "GIVE_ME_SWAP3" });
List<ConfigAttribute> attr4 = SecurityConfig.createList(
new String[] { "NEVER_CAUSES_SWAP" });
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr1,
"content-before-swapping")).isEqualTo("swap1");
@ -76,13 +75,14 @@ public class AfterInvocationProviderManagerTests extends TestCase {
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr3,
"content-before-swapping")).isEqualTo("swap3");
assertThat(manager.decide(null,
new SimpleMethodInvocation(), attr4, "content-before-swapping")).isEqualTo("content-before-swapping");
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr4,
"content-before-swapping")).isEqualTo("content-before-swapping");
assertThat(manager.decide(null, new SimpleMethodInvocation(),
attr2and3, "content-before-swapping")).isEqualTo("swap3");
assertThat(manager.decide(null, new SimpleMethodInvocation(), attr2and3,
"content-before-swapping")).isEqualTo("swap3");
}
@Test
public void testRejectsEmptyProvidersList() {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
List list = new Vector();
@ -92,10 +92,11 @@ public class AfterInvocationProviderManagerTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
assertThat(true).isTrue();
}
}
@Test
public void testRejectsNonAfterInvocationProviders() {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
List list = new Vector();
@ -110,10 +111,11 @@ public class AfterInvocationProviderManagerTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
assertThat(true).isTrue();
}
}
@Test
public void testRejectsNullProvidersList() throws Exception {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
@ -122,10 +124,11 @@ public class AfterInvocationProviderManagerTests extends TestCase {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
assertThat(true).isTrue();
}
}
@Test
public void testSupportsConfigAttributeIteration() throws Exception {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
List list = new Vector();
@ -138,10 +141,11 @@ public class AfterInvocationProviderManagerTests extends TestCase {
manager.setProviders(list);
manager.afterPropertiesSet();
assertFalse(manager.supports(new SecurityConfig("UNKNOWN_ATTRIB")));
assertTrue(manager.supports(new SecurityConfig("GIVE_ME_SWAP2")));
assertThat(manager.supports(new SecurityConfig("UNKNOWN_ATTRIB"))).isFalse();
assertThat(manager.supports(new SecurityConfig("GIVE_ME_SWAP2"))).isTrue();
}
@Test
public void testSupportsSecureObjectIteration() throws Exception {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
List list = new Vector();
@ -155,7 +159,7 @@ public class AfterInvocationProviderManagerTests extends TestCase {
manager.afterPropertiesSet();
// assertFalse(manager.supports(FilterInvocation.class));
assertTrue(manager.supports(MethodInvocation.class));
assertThat(manager.supports(MethodInvocation.class)).isTrue();
}
// ~ Inner Classes
@ -167,8 +171,11 @@ public class AfterInvocationProviderManagerTests extends TestCase {
* supports.
*/
private class MockAfterInvocationProvider implements AfterInvocationProvider {
private Class secureObject;
private ConfigAttribute configAttribute;
private Object forceReturnObject;
public MockAfterInvocationProvider(Object forceReturnObject, Class secureObject,
@ -180,7 +187,7 @@ public class AfterInvocationProviderManagerTests extends TestCase {
public Object decide(Authentication authentication, Object object,
Collection<ConfigAttribute> config, Object returnedObject)
throws AccessDeniedException {
throws AccessDeniedException {
if (config.contains(configAttribute)) {
return forceReturnObject;
}

View File

@ -17,34 +17,31 @@ package org.springframework.security.access.intercept;
import static org.assertj.core.api.Assertions.assertThat;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.intercept.NullRunAsManager;
/**
* Tests {@link NullRunAsManager}.
*
* @author Ben Alex
*/
public class NullRunAsManagerTests extends TestCase {
public class NullRunAsManagerTests {
// ~ Methods
// ========================================================================================================
public final void setUp() throws Exception {
super.setUp();
}
@Test
public void testAlwaysReturnsNull() {
NullRunAsManager runAs = new NullRunAsManager();
assertThat(runAs.buildRunAs(null, null, null)).isNull();
}
@Test
public void testAlwaysSupportsClass() {
NullRunAsManager runAs = new NullRunAsManager();
assertThat(runAs.supports(String.class)).isTrue();
}
@Test
public void testNeverSupportsAttribute() {
NullRunAsManager runAs = new NullRunAsManager();
assertThat(runAs.supports(new SecurityConfig("X"))).isFalse();

View File

@ -16,11 +16,11 @@
package org.springframework.security.access.intercept;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.Set;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
@ -31,17 +31,20 @@ import org.springframework.security.core.authority.AuthorityUtils;
*
* @author Ben Alex
*/
public class RunAsManagerImplTests extends TestCase {
public class RunAsManagerImplTests {
@Test
public void testAlwaysSupportsClass() {
RunAsManagerImpl runAs = new RunAsManagerImpl();
assertThat(runAs.supports(String.class)).isTrue();
}
@Test
public void testDoesNotReturnAdditionalAuthoritiesIfCalledWithoutARunAsSetting()
throws Exception {
UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken(
"Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE",
"ROLE_TWO"));
"Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
RunAsManagerImpl runAs = new RunAsManagerImpl();
runAs.setKey("my_password");
@ -51,6 +54,7 @@ public class RunAsManagerImplTests extends TestCase {
assertThat(resultingToken).isEqualTo(null);
}
@Test
public void testRespectsRolePrefix() throws Exception {
UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken(
"Test", "Password", AuthorityUtils.createAuthorityList("ONE", "TWO"));
@ -62,12 +66,12 @@ public class RunAsManagerImplTests extends TestCase {
Authentication result = runAs.buildRunAs(inputToken, new Object(),
SecurityConfig.createList("RUN_AS_SOMETHING"));
assertTrue("Should have returned a RunAsUserToken",
result instanceof RunAsUserToken);
assertThat(result instanceof RunAsUserToken).withFailMessage(
"Should have returned a RunAsUserToken").isTrue();
assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal());
assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials());
Set<String> authorities = AuthorityUtils.authorityListToSet(result
.getAuthorities());
Set<String> authorities = AuthorityUtils.authorityListToSet(
result.getAuthorities());
assertThat(authorities.contains("FOOBAR_RUN_AS_SOMETHING")).isTrue();
assertThat(authorities.contains("ONE")).isTrue();
@ -77,10 +81,11 @@ public class RunAsManagerImplTests extends TestCase {
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
}
@Test
public void testReturnsAdditionalGrantedAuthorities() throws Exception {
UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken(
"Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE",
"ROLE_TWO"));
"Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
RunAsManagerImpl runAs = new RunAsManagerImpl();
runAs.setKey("my_password");
@ -95,8 +100,8 @@ public class RunAsManagerImplTests extends TestCase {
assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal());
assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials());
Set<String> authorities = AuthorityUtils.authorityListToSet(result
.getAuthorities());
Set<String> authorities = AuthorityUtils.authorityListToSet(
result.getAuthorities());
assertThat(authorities.contains("ROLE_RUN_AS_SOMETHING")).isTrue();
assertThat(authorities.contains("ROLE_ONE")).isTrue();
assertThat(authorities.contains("ROLE_TWO")).isTrue();
@ -105,6 +110,7 @@ public class RunAsManagerImplTests extends TestCase {
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
}
@Test
public void testStartupDetectsMissingKey() throws Exception {
RunAsManagerImpl runAs = new RunAsManagerImpl();
@ -117,6 +123,7 @@ public class RunAsManagerImplTests extends TestCase {
}
}
@Test
public void testStartupSuccessfulWithKey() throws Exception {
RunAsManagerImpl runAs = new RunAsManagerImpl();
runAs.setKey("hello_world");
@ -124,6 +131,7 @@ public class RunAsManagerImplTests extends TestCase {
assertThat(runAs.getKey()).isEqualTo("hello_world");
}
@Test
public void testSupports() throws Exception {
RunAsManager runAs = new RunAsManagerImpl();
assertThat(runAs.supports(new SecurityConfig("RUN_AS_SOMETHING"))).isTrue();

View File

@ -15,7 +15,10 @@
package org.springframework.security.access.intercept;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import org.junit.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
@ -24,28 +27,31 @@ import org.springframework.security.core.authority.AuthorityUtils;
*
* @author Ben Alex
*/
public class RunAsUserTokenTests extends TestCase {
public class RunAsUserTokenTests {
@Test
public void testAuthenticationSetting() {
RunAsUserToken token = new RunAsUserToken("my_password", "Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"),
UsernamePasswordAuthenticationToken.class);
assertTrue(token.isAuthenticated());
assertThat(token.isAuthenticated()).isTrue();
token.setAuthenticated(false);
assertTrue(!token.isAuthenticated());
assertThat(!token.isAuthenticated()).isTrue();
}
@Test
public void testGetters() {
RunAsUserToken token = new RunAsUserToken("my_password", "Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"),
UsernamePasswordAuthenticationToken.class);
assertEquals("Test", token.getPrincipal());
assertEquals("Password", token.getCredentials());
assertEquals("my_password".hashCode(), token.getKeyHash());
assertEquals(UsernamePasswordAuthenticationToken.class,
assertThat("Test").isEqualTo(token.getPrincipal());
assertThat("Password").isEqualTo(token.getCredentials());
assertThat("my_password".hashCode()).isEqualTo(token.getKeyHash());
assertThat(UsernamePasswordAuthenticationToken.class).isEqualTo(
token.getOriginalAuthentication());
}
@Test
public void testNoArgConstructorDoesntExist() {
Class<RunAsUserToken> clazz = RunAsUserToken.class;
@ -54,23 +60,24 @@ public class RunAsUserTokenTests extends TestCase {
fail("Should have thrown NoSuchMethodException");
}
catch (NoSuchMethodException expected) {
assertTrue(true);
assertThat(true).isTrue();
}
}
@Test
public void testToString() {
RunAsUserToken token = new RunAsUserToken("my_password", "Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"),
UsernamePasswordAuthenticationToken.class);
assertTrue(token.toString().lastIndexOf(
"Original Class: "
+ UsernamePasswordAuthenticationToken.class.getName().toString()) != -1);
assertThat(token.toString().lastIndexOf("Original Class: "
+ UsernamePasswordAuthenticationToken.class.getName().toString()) != -1).isTrue();
}
// SEC-1792
@Test
public void testToStringNullOriginalAuthentication() {
RunAsUserToken token = new RunAsUserToken("my_password", "Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), null);
assertTrue(token.toString().lastIndexOf("Original Class: null") != -1);
assertThat(token.toString().lastIndexOf("Original Class: null") != -1).isTrue();
}
}

View File

@ -15,15 +15,13 @@
package org.springframework.security.access.intercept.aopalliance;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.reflect.Method;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.security.TargetObject;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.method.MethodSecurityMetadataSource;
@ -33,10 +31,11 @@ import org.springframework.security.access.method.MethodSecurityMetadataSource;
*
* @author Ben Alex
*/
public class MethodSecurityMetadataSourceAdvisorTests extends TestCase {
public class MethodSecurityMetadataSourceAdvisorTests {
// ~ Methods
// ========================================================================================================
@Test
public void testAdvisorReturnsFalseWhenMethodInvocationNotDefined() throws Exception {
Class<TargetObject> clazz = TargetObject.class;
Method method = clazz.getMethod("makeLowerCase", new Class[] { String.class });
@ -45,9 +44,11 @@ public class MethodSecurityMetadataSourceAdvisorTests extends TestCase {
when(mds.getAttributes(method, clazz)).thenReturn(null);
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor(
"", mds, "");
assertThat(advisor.getPointcut().getMethodMatcher().matches(method, clazz)).isFalse();
assertThat(advisor.getPointcut().getMethodMatcher().matches(method,
clazz)).isFalse();
}
@Test
public void testAdvisorReturnsTrueWhenMethodInvocationIsDefined() throws Exception {
Class<TargetObject> clazz = TargetObject.class;
Method method = clazz.getMethod("countLength", new Class[] { String.class });
@ -57,6 +58,7 @@ public class MethodSecurityMetadataSourceAdvisorTests extends TestCase {
SecurityConfig.createList("ROLE_A"));
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor(
"", mds, "");
assertThat(advisor.getPointcut().getMethodMatcher().matches(method, clazz)).isTrue();
assertThat(
advisor.getPointcut().getMethodMatcher().matches(method, clazz)).isTrue();
}
}

View File

@ -16,32 +16,29 @@
package org.springframework.security.access.vote;
import static org.assertj.core.api.Assertions.assertThat;
import junit.framework.TestCase;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.vote.AbstractAccessDecisionManager;
import org.springframework.security.access.vote.RoleVoter;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.fail;
import java.util.Collection;
import java.util.List;
import java.util.Vector;
import org.junit.Test;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.Authentication;
/**
* Tests {@link AbstractAccessDecisionManager}.
*
* @author Ben Alex
*/
@SuppressWarnings("unchecked")
public class AbstractAccessDecisionManagerTests extends TestCase {
public class AbstractAccessDecisionManagerTests {
// ~ Methods
// ========================================================================================================
@Test
public void testAllowIfAccessDecisionManagerDefaults() {
List list = new Vector();
DenyAgainVoter denyVoter = new DenyAgainVoter();
@ -52,6 +49,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
assertThat(mock.isAllowIfAllAbstainDecisions()).isTrue(); // changed
}
@Test
public void testDelegatesSupportsClassRequests() throws Exception {
List list = new Vector();
list.add(new DenyVoter());
@ -63,6 +61,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
assertThat(!mock.supports(Integer.class)).isTrue();
}
@Test
public void testDelegatesSupportsRequests() throws Exception {
List list = new Vector();
DenyVoter voter = new DenyVoter();
@ -79,6 +78,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
assertThat(!mock.supports(badAttr)).isTrue();
}
@Test
public void testProperlyStoresListOfVoters() throws Exception {
List list = new Vector();
DenyVoter voter = new DenyVoter();
@ -89,6 +89,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
assertThat(mock.getDecisionVoters().size()).isEqualTo(list.size());
}
@Test
public void testRejectsEmptyList() throws Exception {
List list = new Vector();
@ -101,6 +102,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
}
}
@Test
public void testRejectsNullVotersList() throws Exception {
try {
new MockDecisionManagerImpl(null);
@ -111,11 +113,13 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
}
}
@Test
public void testRoleVoterAlwaysReturnsTrueToSupports() {
RoleVoter rv = new RoleVoter();
assertThat(rv.supports(String.class)).isTrue();
}
@Test
public void testWillNotStartIfDecisionVotersNotSet() throws Exception {
try {
new MockDecisionManagerImpl(null);
@ -130,6 +134,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
// ==================================================================================================
private class MockDecisionManagerImpl extends AbstractAccessDecisionManager {
protected MockDecisionManagerImpl(
List<AccessDecisionVoter<? extends Object>> decisionVoters) {
super(decisionVoters);
@ -141,6 +146,7 @@ public class AbstractAccessDecisionManagerTests extends TestCase {
}
private class MockStringOnlyVoter implements AccessDecisionVoter<Object> {
public boolean supports(Class<?> clazz) {
return String.class.isAssignableFrom(clazz);
}

View File

@ -16,15 +16,14 @@
package org.springframework.security.access.vote;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.List;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.vote.AuthenticatedVoter;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@ -36,7 +35,7 @@ import org.springframework.security.core.authority.AuthorityUtils;
*
* @author Ben Alex
*/
public class AuthenticatedVoterTests extends TestCase {
public class AuthenticatedVoterTests {
private Authentication createAnonymous() {
return new AnonymousAuthenticationToken("ignored", "ignored",
@ -53,42 +52,46 @@ public class AuthenticatedVoterTests extends TestCase {
AuthorityUtils.createAuthorityList("ignored"));
}
@Test
public void testAnonymousWorks() {
AuthenticatedVoter voter = new AuthenticatedVoter();
List<ConfigAttribute> def = SecurityConfig
.createList(AuthenticatedVoter.IS_AUTHENTICATED_ANONYMOUSLY);
assertEquals(AccessDecisionVoter.ACCESS_GRANTED,
List<ConfigAttribute> def = SecurityConfig.createList(
AuthenticatedVoter.IS_AUTHENTICATED_ANONYMOUSLY);
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(
voter.vote(createAnonymous(), null, def));
assertEquals(AccessDecisionVoter.ACCESS_GRANTED,
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(
voter.vote(createRememberMe(), null, def));
assertEquals(AccessDecisionVoter.ACCESS_GRANTED,
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(
voter.vote(createFullyAuthenticated(), null, def));
}
@Test
public void testFullyWorks() {
AuthenticatedVoter voter = new AuthenticatedVoter();
List<ConfigAttribute> def = SecurityConfig
.createList(AuthenticatedVoter.IS_AUTHENTICATED_FULLY);
assertEquals(AccessDecisionVoter.ACCESS_DENIED,
List<ConfigAttribute> def = SecurityConfig.createList(
AuthenticatedVoter.IS_AUTHENTICATED_FULLY);
assertThat(AccessDecisionVoter.ACCESS_DENIED).isEqualTo(
voter.vote(createAnonymous(), null, def));
assertEquals(AccessDecisionVoter.ACCESS_DENIED,
assertThat(AccessDecisionVoter.ACCESS_DENIED).isEqualTo(
voter.vote(createRememberMe(), null, def));
assertEquals(AccessDecisionVoter.ACCESS_GRANTED,
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(
voter.vote(createFullyAuthenticated(), null, def));
}
@Test
public void testRememberMeWorks() {
AuthenticatedVoter voter = new AuthenticatedVoter();
List<ConfigAttribute> def = SecurityConfig
.createList(AuthenticatedVoter.IS_AUTHENTICATED_REMEMBERED);
assertEquals(AccessDecisionVoter.ACCESS_DENIED,
List<ConfigAttribute> def = SecurityConfig.createList(
AuthenticatedVoter.IS_AUTHENTICATED_REMEMBERED);
assertThat(AccessDecisionVoter.ACCESS_DENIED).isEqualTo(
voter.vote(createAnonymous(), null, def));
assertEquals(AccessDecisionVoter.ACCESS_GRANTED,
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(
voter.vote(createRememberMe(), null, def));
assertEquals(AccessDecisionVoter.ACCESS_GRANTED,
assertThat(AccessDecisionVoter.ACCESS_GRANTED).isEqualTo(
voter.vote(createFullyAuthenticated(), null, def));
}
@Test
public void testSetterRejectsNull() {
AuthenticatedVoter voter = new AuthenticatedVoter();
@ -101,15 +104,16 @@ public class AuthenticatedVoterTests extends TestCase {
}
}
@Test
public void testSupports() {
AuthenticatedVoter voter = new AuthenticatedVoter();
assertThat(voter.supports(String.class)).isTrue();
assertTrue(voter.supports(new SecurityConfig(
AuthenticatedVoter.IS_AUTHENTICATED_ANONYMOUSLY)));
assertTrue(voter.supports(new SecurityConfig(
AuthenticatedVoter.IS_AUTHENTICATED_FULLY)));
assertTrue(voter.supports(new SecurityConfig(
AuthenticatedVoter.IS_AUTHENTICATED_REMEMBERED)));
assertThat(voter.supports(new SecurityConfig(
AuthenticatedVoter.IS_AUTHENTICATED_ANONYMOUSLY))).isTrue();
assertThat(voter.supports(
new SecurityConfig(AuthenticatedVoter.IS_AUTHENTICATED_FULLY))).isTrue();
assertThat(voter.supports(new SecurityConfig(
AuthenticatedVoter.IS_AUTHENTICATED_REMEMBERED))).isTrue();
assertThat(voter.supports(new SecurityConfig("FOO"))).isFalse();
}
}

View File

@ -16,18 +16,16 @@
package org.springframework.security.access.vote;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.List;
import java.util.Vector;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.vote.RoleVoter;
import org.springframework.security.access.vote.UnanimousBased;
import org.springframework.security.authentication.TestingAuthenticationToken;
/**
@ -35,7 +33,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
*
* @author Ben Alex
*/
public class UnanimousBasedTests extends TestCase {
public class UnanimousBasedTests {
// ~ Methods
// ========================================================================================================
@ -73,13 +71,14 @@ public class UnanimousBasedTests extends TestCase {
"FOOBAR_2");
}
@Test
public void testOneAffirmativeVoteOneDenyVoteOneAbstainVoteDeniesAccess()
throws Exception {
TestingAuthenticationToken auth = makeTestToken();
UnanimousBased mgr = makeDecisionManager();
List<ConfigAttribute> config = SecurityConfig.createList(new String[] { "ROLE_1",
"DENY_FOR_SURE" });
List<ConfigAttribute> config = SecurityConfig.createList(
new String[] { "ROLE_1", "DENY_FOR_SURE" });
try {
mgr.decide(auth, new Object(), config);
@ -89,6 +88,7 @@ public class UnanimousBasedTests extends TestCase {
}
}
@Test
public void testOneAffirmativeVoteTwoAbstainVotesGrantsAccess() throws Exception {
TestingAuthenticationToken auth = makeTestToken();
UnanimousBased mgr = makeDecisionManager();
@ -98,6 +98,7 @@ public class UnanimousBasedTests extends TestCase {
mgr.decide(auth, new Object(), config);
}
@Test
public void testOneDenyVoteTwoAbstainVotesDeniesAccess() throws Exception {
TestingAuthenticationToken auth = makeTestToken();
UnanimousBased mgr = makeDecisionManager();
@ -112,16 +113,18 @@ public class UnanimousBasedTests extends TestCase {
}
}
@Test
public void testRoleVoterPrefixObserved() throws Exception {
TestingAuthenticationToken auth = makeTestTokenWithFooBarPrefix();
UnanimousBased mgr = makeDecisionManagerWithFooBarPrefix();
List<ConfigAttribute> config = SecurityConfig.createList(new String[] {
"FOOBAR_1", "FOOBAR_2" });
List<ConfigAttribute> config = SecurityConfig.createList(
new String[] { "FOOBAR_1", "FOOBAR_2" });
mgr.decide(auth, new Object(), config);
}
@Test
public void testThreeAbstainVotesDeniesAccessWithDefault() throws Exception {
TestingAuthenticationToken auth = makeTestToken();
UnanimousBased mgr = makeDecisionManager();
@ -138,6 +141,7 @@ public class UnanimousBasedTests extends TestCase {
}
}
@Test
public void testThreeAbstainVotesGrantsAccessWithoutDefault() throws Exception {
TestingAuthenticationToken auth = makeTestToken();
UnanimousBased mgr = makeDecisionManager();
@ -149,12 +153,13 @@ public class UnanimousBasedTests extends TestCase {
mgr.decide(auth, new Object(), config);
}
@Test
public void testTwoAffirmativeVotesTwoAbstainVotesGrantsAccess() throws Exception {
TestingAuthenticationToken auth = makeTestToken();
UnanimousBased mgr = makeDecisionManager();
List<ConfigAttribute> config = SecurityConfig.createList(new String[] { "ROLE_1",
"ROLE_2" });
List<ConfigAttribute> config = SecurityConfig.createList(
new String[] { "ROLE_1", "ROLE_2" });
mgr.decide(auth, new Object(), config);
}

View File

@ -17,12 +17,7 @@ package org.springframework.security.authentication;
import static org.assertj.core.api.Assertions.assertThat;
import junit.framework.TestCase;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.junit.Test;
import org.springframework.security.core.authority.AuthorityUtils;
/**
@ -31,38 +26,42 @@ import org.springframework.security.core.authority.AuthorityUtils;
*
* @author Ben Alex
*/
public class AuthenticationTrustResolverImplTests extends TestCase {
public class AuthenticationTrustResolverImplTests {
// ~ Methods
// ========================================================================================================
@Test
public void testCorrectOperationIsAnonymous() {
AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl();
assertTrue(trustResolver.isAnonymous(new AnonymousAuthenticationToken("ignored",
"ignored", AuthorityUtils.createAuthorityList("ignored"))));
assertFalse(trustResolver.isAnonymous(new TestingAuthenticationToken("ignored",
"ignored", AuthorityUtils.createAuthorityList("ignored"))));
assertThat(trustResolver.isAnonymous(new AnonymousAuthenticationToken("ignored",
"ignored", AuthorityUtils.createAuthorityList("ignored")))).isTrue();
assertThat(trustResolver.isAnonymous(new TestingAuthenticationToken("ignored",
"ignored", AuthorityUtils.createAuthorityList("ignored")))).isFalse();
}
@Test
public void testCorrectOperationIsRememberMe() {
AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl();
assertTrue(trustResolver.isRememberMe(new RememberMeAuthenticationToken(
"ignored", "ignored", AuthorityUtils.createAuthorityList("ignored"))));
assertFalse(trustResolver.isAnonymous(new TestingAuthenticationToken("ignored",
"ignored", AuthorityUtils.createAuthorityList("ignored"))));
assertThat(trustResolver.isRememberMe(new RememberMeAuthenticationToken("ignored",
"ignored", AuthorityUtils.createAuthorityList("ignored")))).isTrue();
assertThat(trustResolver.isAnonymous(new TestingAuthenticationToken("ignored",
"ignored", AuthorityUtils.createAuthorityList("ignored")))).isFalse();
}
@Test
public void testGettersSetters() {
AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl();
assertEquals(AnonymousAuthenticationToken.class,
assertThat(AnonymousAuthenticationToken.class).isEqualTo(
trustResolver.getAnonymousClass());
trustResolver.setAnonymousClass(TestingAuthenticationToken.class);
assertThat(trustResolver.getAnonymousClass()).isEqualTo(TestingAuthenticationToken.class);
assertThat(trustResolver.getAnonymousClass()).isEqualTo(
TestingAuthenticationToken.class);
assertEquals(RememberMeAuthenticationToken.class,
assertThat(RememberMeAuthenticationToken.class).isEqualTo(
trustResolver.getRememberMeClass());
trustResolver.setRememberMeClass(TestingAuthenticationToken.class);
assertThat(trustResolver.getRememberMeClass()).isEqualTo(TestingAuthenticationToken.class);
assertThat(trustResolver.getRememberMeClass()).isEqualTo(
TestingAuthenticationToken.class);
}
}

View File

@ -17,10 +17,7 @@ package org.springframework.security.authentication;
import static org.assertj.core.api.Assertions.assertThat;
import junit.framework.TestCase;
import org.springframework.security.authentication.TestingAuthenticationProvider;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.junit.Test;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
@ -29,8 +26,9 @@ import org.springframework.security.core.authority.AuthorityUtils;
*
* @author Ben Alex
*/
public class TestingAuthenticationProviderTests extends TestCase {
public class TestingAuthenticationProviderTests {
@Test
public void testAuthenticates() {
TestingAuthenticationProvider provider = new TestingAuthenticationProvider();
TestingAuthenticationToken token = new TestingAuthenticationToken("Test",
@ -42,9 +40,12 @@ public class TestingAuthenticationProviderTests extends TestCase {
TestingAuthenticationToken castResult = (TestingAuthenticationToken) result;
assertThat(castResult.getPrincipal()).isEqualTo("Test");
assertThat(castResult.getCredentials()).isEqualTo("Password");
assertThat(AuthorityUtils.authorityListToSet(castResult.getAuthorities())).contains("ROLE_ONE","ROLE_TWO");
assertThat(
AuthorityUtils.authorityListToSet(castResult.getAuthorities())).contains(
"ROLE_ONE", "ROLE_TWO");
}
@Test
public void testSupports() {
TestingAuthenticationProvider provider = new TestingAuthenticationProvider();
assertThat(provider.supports(TestingAuthenticationToken.class)).isTrue();

View File

@ -16,11 +16,9 @@
package org.springframework.security.authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.fail;
import org.junit.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
/**
@ -69,8 +67,8 @@ public class UsernamePasswordAuthenticationTokenTests {
@Test
public void gettersReturnCorrectData() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE",
"ROLE_TWO"));
"Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
assertThat(token.getPrincipal()).isEqualTo("Test");
assertThat(token.getCredentials()).isEqualTo("Password");
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities()).contains(

View File

@ -16,11 +16,11 @@
package org.springframework.security.authentication.anonymous;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.List;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
@ -31,14 +31,14 @@ import org.springframework.security.core.authority.AuthorityUtils;
*
* @author Ben Alex
*/
public class AnonymousAuthenticationTokenTests extends TestCase {
public class AnonymousAuthenticationTokenTests {
private final static List<GrantedAuthority> ROLES_12 = AuthorityUtils
.createAuthorityList("ROLE_ONE", "ROLE_TWO");
private final static List<GrantedAuthority> ROLES_12 = AuthorityUtils.createAuthorityList(
"ROLE_ONE", "ROLE_TWO");
// ~ Methods
// ========================================================================================================
@Test
public void testConstructorRejectsNulls() {
try {
new AnonymousAuthenticationToken(null, "Test", ROLES_12);
@ -55,20 +55,23 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
}
try {
new AnonymousAuthenticationToken("key", "Test", (List<GrantedAuthority>) null);
new AnonymousAuthenticationToken("key", "Test",
(List<GrantedAuthority>) null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new AnonymousAuthenticationToken("key", "Test", AuthorityUtils.NO_AUTHORITIES);
new AnonymousAuthenticationToken("key", "Test",
AuthorityUtils.NO_AUTHORITIES);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testEqualsWhenEqual() {
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key",
"Test", ROLES_12);
@ -78,6 +81,7 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
assertThat(token2).isEqualTo(token1);
}
@Test
public void testGetters() {
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key",
"Test", ROLES_12);
@ -86,10 +90,11 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
assertThat(token.getPrincipal()).isEqualTo("Test");
assertThat(token.getCredentials()).isEqualTo("");
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains(
"ROLE_ONE","ROLE_TWO");
"ROLE_ONE", "ROLE_TWO");
assertThat(token.isAuthenticated()).isTrue();
}
@Test
public void testNoArgConstructorDoesntExist() {
Class<?> clazz = AnonymousAuthenticationToken.class;
@ -101,6 +106,7 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
}
}
@Test
public void testNotEqualsDueToAbstractParentEqualsCheck() {
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key",
"Test", ROLES_12);
@ -110,6 +116,7 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
assertThat(token1.equals(token2)).isFalse();
}
@Test
public void testNotEqualsDueToDifferentAuthenticationClass() {
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key",
"Test", ROLES_12);
@ -119,6 +126,7 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
assertThat(token1.equals(token2)).isFalse();
}
@Test
public void testNotEqualsDueToKey() {
AnonymousAuthenticationToken token1 = new AnonymousAuthenticationToken("key",
"Test", ROLES_12);
@ -129,6 +137,7 @@ public class AnonymousAuthenticationTokenTests extends TestCase {
assertThat(token1.equals(token2)).isFalse();
}
@Test
public void testSetAuthenticatedIgnored() {
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key",
"Test", ROLES_12);

View File

@ -16,7 +16,7 @@
package org.springframework.security.authentication.dao;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;
@ -28,8 +28,7 @@ import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.AuthenticationServiceException;
@ -59,13 +58,14 @@ import org.springframework.security.crypto.password.PasswordEncoder;
* @author Ben Alex
* @author Rob Winch
*/
public class DaoAuthenticationProviderTests extends TestCase {
private static final List<GrantedAuthority> ROLES_12 = AuthorityUtils
.createAuthorityList("ROLE_ONE", "ROLE_TWO");
public class DaoAuthenticationProviderTests {
private static final List<GrantedAuthority> ROLES_12 = AuthorityUtils.createAuthorityList(
"ROLE_ONE", "ROLE_TWO");
// ~ Methods
// ========================================================================================================
@Test
public void testAuthenticateFailsForIncorrectPasswordCase() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "KOala");
@ -83,6 +83,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
@Test
public void testReceivedBadCredentialsWhenCredentialsNotProvided() {
// Test related to SEC-434
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
@ -100,12 +101,14 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
@Test
public void testAuthenticateFailsIfAccountExpired() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"peter", "opal");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(new MockAuthenticationDaoUserPeterAccountExpired());
provider.setUserDetailsService(
new MockAuthenticationDaoUserPeterAccountExpired());
provider.setUserCache(new MockUserCache());
try {
@ -117,6 +120,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
@Test
public void testAuthenticateFailsIfAccountLocked() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"peter", "opal");
@ -134,12 +138,14 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
@Test
public void testAuthenticateFailsIfCredentialsExpired() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"peter", "opal");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(new MockAuthenticationDaoUserPeterCredentialsExpired());
provider.setUserDetailsService(
new MockAuthenticationDaoUserPeterCredentialsExpired());
provider.setUserCache(new MockUserCache());
try {
@ -163,6 +169,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
@Test
public void testAuthenticateFailsIfUserDisabled() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"peter", "opal");
@ -180,6 +187,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
@Test
public void testAuthenticateFailsWhenAuthenticationDaoHasBackendFailure() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "koala");
@ -196,6 +204,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
@Test
public void testAuthenticateFailsWithEmptyUsername() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
null, "koala");
@ -213,6 +222,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
@Test
public void testAuthenticateFailsWithInvalidPassword() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "INVALID_PASSWORD");
@ -230,6 +240,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
@Test
public void testAuthenticateFailsWithInvalidUsernameAndHideUserNotFoundExceptionFalse() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"INVALID_USER", "koala");
@ -249,6 +260,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
@Test
public void testAuthenticateFailsWithInvalidUsernameAndHideUserNotFoundExceptionsWithDefaultOfTrue() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"INVALID_USER", "koala");
@ -267,6 +279,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
@Test
public void testAuthenticateFailsWithMixedCaseUsernameIfDefaultChanged() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"RoD", "koala");
@ -284,6 +297,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
@Test
public void testAuthenticates() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "koala");
@ -302,11 +316,13 @@ public class DaoAuthenticationProviderTests extends TestCase {
UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result;
assertThat(castResult.getPrincipal().getClass()).isEqualTo(User.class);
assertThat(castResult.getCredentials()).isEqualTo("koala");
assertThat(AuthorityUtils.authorityListToSet(castResult.getAuthorities()))
.contains("ROLE_ONE","ROLE_TWO");
assertThat(
AuthorityUtils.authorityListToSet(castResult.getAuthorities())).contains(
"ROLE_ONE", "ROLE_TWO");
assertThat(castResult.getDetails()).isEqualTo("192.168.0.1");
}
@Test
public void testAuthenticatesASecondTime() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "koala");
@ -331,6 +347,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
assertThat(result2.getCredentials()).isEqualTo(result.getCredentials());
}
@Test
public void testAuthenticatesWhenASaltIsUsed() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "koala");
@ -353,10 +370,11 @@ public class DaoAuthenticationProviderTests extends TestCase {
// We expect original credentials user submitted to be returned
assertThat(result.getCredentials()).isEqualTo("koala");
assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities()))
.contains("ROLE_ONE","ROLE_TWO");
assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities())).contains(
"ROLE_ONE", "ROLE_TWO");
}
@Test
public void testAuthenticatesWithForcePrincipalAsString() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "koala");
@ -377,6 +395,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
assertThat(castResult.getPrincipal()).isEqualTo("rod");
}
@Test
public void testDetectsNullBeingReturnedFromAuthenticationDao() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "koala");
@ -389,28 +408,33 @@ public class DaoAuthenticationProviderTests extends TestCase {
fail("Should have thrown AuthenticationServiceException");
}
catch (AuthenticationServiceException expected) {
assertEquals(
"UserDetailsService returned null, which is an interface contract violation",
expected.getMessage());
assertThat(
"UserDetailsService returned null, which is an interface contract violation").isEqualTo(
expected.getMessage());
}
}
@Test
public void testGettersSetters() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(new ShaPasswordEncoder());
assertThat(provider.getPasswordEncoder().getClass()).isEqualTo(ShaPasswordEncoder.class);
assertThat(provider.getPasswordEncoder().getClass()).isEqualTo(
ShaPasswordEncoder.class);
provider.setSaltSource(new SystemWideSaltSource());
assertThat(provider.getSaltSource().getClass()).isEqualTo(SystemWideSaltSource.class);
assertThat(provider.getSaltSource().getClass()).isEqualTo(
SystemWideSaltSource.class);
provider.setUserCache(new EhCacheBasedUserCache());
assertThat(provider.getUserCache().getClass()).isEqualTo(EhCacheBasedUserCache.class);
assertThat(provider.getUserCache().getClass()).isEqualTo(
EhCacheBasedUserCache.class);
assertThat(provider.isForcePrincipalAsString()).isFalse();
provider.setForcePrincipalAsString(true);
assertThat(provider.isForcePrincipalAsString()).isTrue();
}
@Test
public void testGoesBackToAuthenticationDaoToObtainLatestPasswordIfCachedPasswordSeemsIncorrect() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"rod", "koala");
@ -436,9 +460,11 @@ public class DaoAuthenticationProviderTests extends TestCase {
// To get this far, the new password was accepted
// Check the cache was updated
assertThat(cache.getUserFromCache("rod").getPassword()).isEqualTo("easternLongNeckTurtle");
assertThat(cache.getUserFromCache("rod").getPassword()).isEqualTo(
"easternLongNeckTurtle");
}
@Test
public void testStartupFailsIfNoAuthenticationDao() throws Exception {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
@ -451,6 +477,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
@Test
public void testStartupFailsIfNoUserCacheSet() throws Exception {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(new MockAuthenticationDaoUserrod());
@ -466,6 +493,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
@Test
public void testStartupSuccess() throws Exception {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
UserDetailsService userDetailsService = new MockAuthenticationDaoUserrod();
@ -476,6 +504,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
@Test
public void testSupports() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
assertThat(provider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
@ -483,6 +512,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
// SEC-2056
@Test
public void testUserNotFoundEncodesPassword() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"missing", "koala");
@ -504,6 +534,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
verify(encoder).matches(isA(String.class), isA(String.class));
}
@Test
public void testUserNotFoundBCryptPasswordEncoder() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"missing", "koala");
@ -512,8 +543,8 @@ public class DaoAuthenticationProviderTests extends TestCase {
provider.setHideUserNotFoundExceptions(false);
provider.setPasswordEncoder(encoder);
MockAuthenticationDaoUserrod userDetailsService = new MockAuthenticationDaoUserrod();
userDetailsService.password = encoder.encode((CharSequence) token
.getCredentials());
userDetailsService.password = encoder.encode(
(CharSequence) token.getCredentials());
provider.setUserDetailsService(userDetailsService);
try {
provider.authenticate(token);
@ -523,6 +554,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
@Test
public void testUserNotFoundDefaultEncoder() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"missing", null);
@ -552,8 +584,8 @@ public class DaoAuthenticationProviderTests extends TestCase {
provider.setHideUserNotFoundExceptions(false);
provider.setPasswordEncoder(encoder);
MockAuthenticationDaoUserrod userDetailsService = new MockAuthenticationDaoUserrod();
userDetailsService.password = encoder.encode((CharSequence) foundUser
.getCredentials());
userDetailsService.password = encoder.encode(
(CharSequence) foundUser.getCredentials());
provider.setUserDetailsService(userDetailsService);
int sampleSize = 100;
@ -579,9 +611,10 @@ public class DaoAuthenticationProviderTests extends TestCase {
double userFoundAvg = avg(userFoundTimes);
double userNotFoundAvg = avg(userNotFoundTimes);
assertTrue("User not found average " + userNotFoundAvg
+ " should be within 3ms of user found average " + userFoundAvg,
Math.abs(userNotFoundAvg - userFoundAvg) <= 3);
assertThat(Math.abs(userNotFoundAvg - userFoundAvg) <= 3).withFailMessage(
"User not found average " + userNotFoundAvg
+ " should be within 3ms of user found average "
+ userFoundAvg).isTrue();
}
private double avg(List<Long> counts) {
@ -592,6 +625,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
return sum / counts.size();
}
@Test
public void testUserNotFoundNullCredentials() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
"missing", null);
@ -614,12 +648,15 @@ public class DaoAuthenticationProviderTests extends TestCase {
// ==================================================================================================
private class MockAuthenticationDaoReturnsNull implements UserDetailsService {
public UserDetails loadUserByUsername(String username) {
return null;
}
}
private class MockAuthenticationDaoSimulateBackendError implements UserDetailsService {
private class MockAuthenticationDaoSimulateBackendError
implements UserDetailsService {
public UserDetails loadUserByUsername(String username) {
throw new DataRetrievalFailureException(
"This mock simulator is designed to fail");
@ -627,6 +664,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
private class MockAuthenticationDaoUserrod implements UserDetailsService {
private String password = "koala";
public UserDetails loadUserByUsername(String username) {
@ -644,10 +682,11 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
private class MockAuthenticationDaoUserrodWithSalt implements UserDetailsService {
public UserDetails loadUserByUsername(String username) {
if ("rod".equals(username)) {
return new User("rod", "koala{SYSTEM_SALT_VALUE}", true, true, true,
true, ROLES_12);
return new User("rod", "koala{SYSTEM_SALT_VALUE}", true, true, true, true,
ROLES_12);
}
else {
throw new UsernameNotFoundException("Could not find: " + username);
@ -656,6 +695,7 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
private class MockAuthenticationDaoUserPeter implements UserDetailsService {
public UserDetails loadUserByUsername(String username) {
if ("peter".equals(username)) {
return new User("peter", "opal", false, true, true, true, ROLES_12);
@ -666,8 +706,9 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
private class MockAuthenticationDaoUserPeterAccountExpired implements
UserDetailsService {
private class MockAuthenticationDaoUserPeterAccountExpired
implements UserDetailsService {
public UserDetails loadUserByUsername(String username) {
if ("peter".equals(username)) {
return new User("peter", "opal", true, false, true, true, ROLES_12);
@ -678,8 +719,9 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
private class MockAuthenticationDaoUserPeterAccountLocked implements
UserDetailsService {
private class MockAuthenticationDaoUserPeterAccountLocked
implements UserDetailsService {
public UserDetails loadUserByUsername(String username) {
if ("peter".equals(username)) {
return new User("peter", "opal", true, true, true, false, ROLES_12);
@ -690,8 +732,9 @@ public class DaoAuthenticationProviderTests extends TestCase {
}
}
private class MockAuthenticationDaoUserPeterCredentialsExpired implements
UserDetailsService {
private class MockAuthenticationDaoUserPeterCredentialsExpired
implements UserDetailsService {
public UserDetails loadUserByUsername(String username) {
if ("peter".equals(username)) {
return new User("peter", "opal", true, true, false, true, ROLES_12);

View File

@ -15,7 +15,7 @@
package org.springframework.security.authentication.dao.salt;
import static junit.framework.Assert.assertEquals;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.security.authentication.AuthenticationServiceException;

View File

@ -16,17 +16,17 @@
package org.springframework.security.authentication.dao.salt;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import org.junit.Test;
import org.springframework.security.authentication.dao.SystemWideSaltSource;
import junit.framework.TestCase;
/**
* Tests {@link SystemWideSaltSource}.
*
* @author Ben Alex
*/
public class SystemWideSaltSourceTests extends TestCase {
public class SystemWideSaltSourceTests {
// ~ Constructors
// ===================================================================================================
@ -34,21 +34,9 @@ public class SystemWideSaltSourceTests extends TestCase {
super();
}
public SystemWideSaltSourceTests(String arg0) {
super(arg0);
}
// ~ Methods
// ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(SystemWideSaltSourceTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
@Test
public void testDetectsMissingSystemWideSalt() throws Exception {
SystemWideSaltSource saltSource = new SystemWideSaltSource();
@ -61,12 +49,14 @@ public class SystemWideSaltSourceTests extends TestCase {
}
}
@Test
public void testGettersSetters() {
SystemWideSaltSource saltSource = new SystemWideSaltSource();
saltSource.setSystemWideSalt("helloWorld");
assertThat(saltSource.getSystemWideSalt()).isEqualTo("helloWorld");
}
@Test
public void testNormalOperation() throws Exception {
SystemWideSaltSource saltSource = new SystemWideSaltSource();
saltSource.setSystemWideSalt("helloWorld");
@ -75,6 +65,7 @@ public class SystemWideSaltSourceTests extends TestCase {
}
// SEC-2173
@Test
public void testToString() {
String systemWideSalt = "helloWorld";
SystemWideSaltSource saltSource = new SystemWideSaltSource();

View File

@ -15,7 +15,10 @@
package org.springframework.security.authentication.encoding;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
/**
* <p>
@ -24,10 +27,11 @@ import junit.framework.TestCase;
*
* @author Ben Alex
*/
public class BasePasswordEncoderTests extends TestCase {
public class BasePasswordEncoderTests {
// ~ Methods
// ========================================================================================================
@Test
public void testDemergeHandlesEmptyAndNullSalts() {
MockPasswordEncoder pwd = new MockPasswordEncoder();
@ -43,7 +47,7 @@ public class BasePasswordEncoderTests extends TestCase {
assertThat(demerged[0]).isEqualTo("password");
assertThat(demerged[1]).isEqualTo("");
}
@Test
public void testDemergeWithEmptyStringIsRejected() {
MockPasswordEncoder pwd = new MockPasswordEncoder();
@ -55,7 +59,7 @@ public class BasePasswordEncoderTests extends TestCase {
assertThat(expected.getMessage()).isEqualTo("Cannot pass a null or empty String");
}
}
@Test
public void testDemergeWithNullIsRejected() {
MockPasswordEncoder pwd = new MockPasswordEncoder();
@ -67,7 +71,7 @@ public class BasePasswordEncoderTests extends TestCase {
assertThat(expected.getMessage()).isEqualTo("Cannot pass a null or empty String");
}
}
@Test
public void testMergeDemerge() {
MockPasswordEncoder pwd = new MockPasswordEncoder();
@ -78,7 +82,7 @@ public class BasePasswordEncoderTests extends TestCase {
assertThat(demerged[0]).isEqualTo("password");
assertThat(demerged[1]).isEqualTo("foo");
}
@Test
public void testMergeDemergeWithDelimitersInPassword() {
MockPasswordEncoder pwd = new MockPasswordEncoder();
@ -90,7 +94,7 @@ public class BasePasswordEncoderTests extends TestCase {
assertThat(demerged[0]).isEqualTo("p{ass{w{o}rd");
assertThat(demerged[1]).isEqualTo("foo");
}
@Test
public void testMergeDemergeWithNullAsPassword() {
MockPasswordEncoder pwd = new MockPasswordEncoder();
@ -101,7 +105,7 @@ public class BasePasswordEncoderTests extends TestCase {
assertThat(demerged[0]).isEqualTo("");
assertThat(demerged[1]).isEqualTo("foo");
}
@Test
public void testStrictMergeRejectsDelimitersInSalt1() {
MockPasswordEncoder pwd = new MockPasswordEncoder();
@ -113,7 +117,7 @@ public class BasePasswordEncoderTests extends TestCase {
assertThat(expected.getMessage()).isEqualTo("Cannot use { or } in salt.toString()");
}
}
@Test
public void testStrictMergeRejectsDelimitersInSalt2() {
MockPasswordEncoder pwd = new MockPasswordEncoder();
@ -147,3 +151,4 @@ public class BasePasswordEncoderTests extends TestCase {
}
}
}

View File

@ -12,14 +12,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.authentication.encoding;
import org.springframework.security.authentication.encoding.Md4PasswordEncoder;
import static org.assertj.core.api.Assertions.assertThat;
import junit.framework.TestCase;
import org.junit.Test;
public class Md4PasswordEncoderTests extends TestCase {
public class Md4PasswordEncoderTests {
@Test
public void testEncodeUnsaltedPassword() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder();
md4.setEncodeHashAsBase64(true);
@ -27,6 +29,7 @@ public class Md4PasswordEncoderTests extends TestCase {
assertThat(encodedPassword).isEqualTo("8zobtq72iAt0W6KNqavGwg==");
}
@Test
public void testEncodeSaltedPassword() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder();
md4.setEncodeHashAsBase64(true);
@ -34,6 +37,7 @@ public class Md4PasswordEncoderTests extends TestCase {
assertThat(encodedPassword).isEqualTo("ZplT6P5Kv6Rlu6W4FIoYNA==");
}
@Test
public void testEncodeNullPassword() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder();
md4.setEncodeHashAsBase64(true);
@ -41,6 +45,7 @@ public class Md4PasswordEncoderTests extends TestCase {
assertThat(encodedPassword).isEqualTo("MdbP4NFq6TG3PFnX4MCJwA==");
}
@Test
public void testEncodeEmptyPassword() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder();
md4.setEncodeHashAsBase64(true);
@ -48,27 +53,33 @@ public class Md4PasswordEncoderTests extends TestCase {
assertThat(encodedPassword).isEqualTo("MdbP4NFq6TG3PFnX4MCJwA==");
}
@Test
public void testNonAsciiPasswordHasCorrectHash() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder();
String encodedPassword = md4.encodePassword("\u4F60\u597d", null);
assertThat(encodedPassword).isEqualTo("a7f1196539fd1f85f754ffd185b16e6e");
}
@Test
public void testIsHexPasswordValid() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder();
assertThat(md4.isPasswordValid("31d6cfe0d16ae931b73c59d7e0c089c0", "", null)).isTrue();
assertThat(md4.isPasswordValid("31d6cfe0d16ae931b73c59d7e0c089c0", "",
null)).isTrue();
}
@Test
public void testIsPasswordValid() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder();
md4.setEncodeHashAsBase64(true);
assertThat(md4.isPasswordValid("8zobtq72iAt0W6KNqavGwg==", "ww_uni123", null)).isTrue();
assertThat(md4.isPasswordValid("8zobtq72iAt0W6KNqavGwg==", "ww_uni123",
null)).isTrue();
}
@Test
public void testIsSaltedPasswordValid() {
Md4PasswordEncoder md4 = new Md4PasswordEncoder();
md4.setEncodeHashAsBase64(true);
assertTrue(md4.isPasswordValid("ZplT6P5Kv6Rlu6W4FIoYNA==", "ww_uni123",
"Alan K Stewart"));
assertThat(md4.isPasswordValid("ZplT6P5Kv6Rlu6W4FIoYNA==", "ww_uni123",
"Alan K Stewart")).isTrue();
}
}

View File

@ -74,7 +74,6 @@ public class Md5PasswordEncoderTests {
pe.setIterations(2);
// Calculate value using:
// echo -n password{salt} | openssl md5 -binary | openssl md5
assertEquals("eb753fb0c370582b4ee01b30f304b9fc",
pe.encodePassword("password", "salt"));
assertThat(pe.encodePassword("password", "salt")).isEqualTo("eb753fb0c370582b4ee01b30f304b9fc");
}
}

View File

@ -15,9 +15,9 @@
package org.springframework.security.authentication.encoding;
import org.springframework.security.authentication.encoding.PlaintextPasswordEncoder;
import static org.assertj.core.api.Assertions.assertThat;
import junit.framework.TestCase;
import org.junit.Test;
/**
* <p>
@ -27,10 +27,11 @@ import junit.framework.TestCase;
* @author colin sampaleanu
* @author Ben Alex
*/
public class PlaintextPasswordEncoderTests extends TestCase {
public class PlaintextPasswordEncoderTests {
// ~ Methods
// ========================================================================================================
@Test
public void testBasicFunctionality() {
PlaintextPasswordEncoder pe = new PlaintextPasswordEncoder();
@ -59,6 +60,7 @@ public class PlaintextPasswordEncoderTests extends TestCase {
assertThat(pe.isPasswordValid(encoded, badRaw, salt)).isFalse();
}
@Test
public void testMergeDemerge() {
PlaintextPasswordEncoder pwd = new PlaintextPasswordEncoder();

View File

@ -15,9 +15,10 @@
package org.springframework.security.authentication.encoding;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import static org.assertj.core.api.Assertions.*;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
/**
* <p>
@ -28,10 +29,11 @@ import junit.framework.TestCase;
* @author Ben Alex
* @author Ray Krueger
*/
public class ShaPasswordEncoderTests extends TestCase {
public class ShaPasswordEncoderTests {
// ~ Methods
// ========================================================================================================
@Test
public void testBasicFunctionality() {
ShaPasswordEncoder pe = new ShaPasswordEncoder();
String raw = "abc123";
@ -43,7 +45,7 @@ public class ShaPasswordEncoderTests extends TestCase {
assertThat(encoded).isEqualTo("b2f50ffcbd3407fe9415c062d55f54731f340d32");
}
@Test
public void testBase64() throws Exception {
ShaPasswordEncoder pe = new ShaPasswordEncoder();
pe.setEncodeHashAsBase64(true);
@ -55,17 +57,15 @@ public class ShaPasswordEncoderTests extends TestCase {
assertThat(pe.isPasswordValid(encoded, badRaw, salt)).isFalse();
assertThat(encoded.length() != 40).isTrue();
}
@Test
public void test256() throws Exception {
ShaPasswordEncoder pe = new ShaPasswordEncoder(256);
String encoded = pe.encodePassword("abc123", null);
assertEquals("6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090",
encoded);
assertThat(encoded).isEqualTo("6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090");
String encodedWithSalt = pe.encodePassword("abc123", "THIS_IS_A_SALT");
assertEquals("4b79b7de23eb23b78cc5ede227d532b8a51f89b2ec166f808af76b0dbedc47d7",
encodedWithSalt);
assertThat(encodedWithSalt).isEqualTo("4b79b7de23eb23b78cc5ede227d532b8a51f89b2ec166f808af76b0dbedc47d7");
}
@Test
public void testInvalidStrength() throws Exception {
try {
new ShaPasswordEncoder(666);

View File

@ -15,14 +15,12 @@
package org.springframework.security.authentication.event;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import org.junit.Test;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.AbstractAuthenticationEvent;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.authentication.event.AuthenticationFailureDisabledEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
@ -31,7 +29,7 @@ import org.springframework.security.core.AuthenticationException;
*
* @author Ben Alex
*/
public class AuthenticationEventTests extends TestCase {
public class AuthenticationEventTests {
// ~ Methods
// ========================================================================================================
@ -43,20 +41,14 @@ public class AuthenticationEventTests extends TestCase {
return authentication;
}
public static void main(String[] args) {
junit.textui.TestRunner.run(AuthenticationEventTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
@Test
public void testAbstractAuthenticationEvent() {
Authentication auth = getAuthentication();
AbstractAuthenticationEvent event = new AuthenticationSuccessEvent(auth);
assertThat(event.getAuthentication()).isEqualTo(auth);
}
@Test
public void testAbstractAuthenticationFailureEvent() {
Authentication auth = getAuthentication();
AuthenticationException exception = new DisabledException("TEST");
@ -66,6 +58,7 @@ public class AuthenticationEventTests extends TestCase {
assertThat(event.getException()).isEqualTo(exception);
}
@Test
public void testRejectsNullAuthentication() {
AuthenticationException exception = new DisabledException("TEST");
@ -78,6 +71,7 @@ public class AuthenticationEventTests extends TestCase {
}
}
@Test
public void testRejectsNullAuthenticationException() {
try {
new AuthenticationFailureDisabledEvent(getAuthentication(), null);

View File

@ -15,12 +15,9 @@
package org.springframework.security.authentication.event;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.AuthenticationFailureDisabledEvent;
import org.springframework.security.authentication.event.LoggerListener;
import org.springframework.security.core.Authentication;
/**
@ -28,7 +25,7 @@ import org.springframework.security.core.Authentication;
*
* @author Ben Alex
*/
public class LoggerListenerTests extends TestCase {
public class LoggerListenerTests {
// ~ Methods
// ========================================================================================================
@ -40,14 +37,7 @@ public class LoggerListenerTests extends TestCase {
return authentication;
}
public static void main(String[] args) {
junit.textui.TestRunner.run(LoggerListenerTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
@Test
public void testLogsEvents() {
AuthenticationFailureDisabledEvent event = new AuthenticationFailureDisabledEvent(
getAuthentication(), new LockedException("TEST"));

View File

@ -94,8 +94,7 @@ public class DefaultJaasAuthenticationProviderTests {
@Test
public void authenticateUnsupportedAuthentication() {
assertEquals(null,
provider.authenticate(new TestingAuthenticationToken("user", "password")));
assertThat(provider.authenticate(new TestingAuthenticationToken("user", "password"))).isNull();
}
@Test

View File

@ -40,10 +40,8 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.session.SessionDestroyedEvent;
/**
@ -82,8 +80,7 @@ public class JaasAuthenticationProviderTests {
}
assertThat(eventCheck.failedEvent).as("Failure event not fired").isNotNull();
assertNotNull("Failure event exception was null",
eventCheck.failedEvent.getException());
assertThat(eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null").isNotNull();
assertThat(eventCheck.successEvent).as("Success event was fired").isNull();
}
@ -98,8 +95,7 @@ public class JaasAuthenticationProviderTests {
}
assertThat(eventCheck.failedEvent).as("Failure event not fired").isNotNull();
assertNotNull("Failure event exception was null",
eventCheck.failedEvent.getException());
assertThat(eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null").isNotNull();
assertThat(eventCheck.successEvent).as("Success event was fired").isNull();
}
@ -178,8 +174,7 @@ public class JaasAuthenticationProviderTests {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage().isTrue()
.startsWith("loginContextName must be set on"));
assertThat(expected.getMessage()).startsWith("loginContextName must be set on");
}
myJaasProvider.setLoginContextName("");
@ -189,8 +184,7 @@ public class JaasAuthenticationProviderTests {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage().isTrue()
.startsWith("loginContextName must be set on"));
assertThat(expected.getMessage().startsWith("loginContextName must be set on"));
}
}
@ -211,20 +205,15 @@ public class JaasAuthenticationProviderTests {
Collection<? extends GrantedAuthority> list = auth.getAuthorities();
Set<String> set = AuthorityUtils.authorityListToSet(list);
assertFalse("GrantedAuthorities should not contain ROLE_1",
set.contains("ROLE_ONE"));
assertTrue("GrantedAuthorities should contain ROLE_TEST1",
set.contains("ROLE_TEST1"));
assertTrue("GrantedAuthorities should contain ROLE_TEST2",
set.contains("ROLE_TEST2"));
assertThat(set.contains("ROLE_ONE")).withFailMessage("GrantedAuthorities should not contain ROLE_ONE").isFalse();
assertThat(set.contains("ROLE_TEST1")).withFailMessage("GrantedAuthorities should contain ROLE_TEST1").isTrue();
assertThat(set.contains("ROLE_TEST2")).withFailMessage("GrantedAuthorities should contain ROLE_TEST2").isTrue();
boolean foundit = false;
for (GrantedAuthority a : list) {
if (a instanceof JaasGrantedAuthority) {
JaasGrantedAuthority grant = (JaasGrantedAuthority) a;
assertNotNull("Principal was null on JaasGrantedAuthority",
grant.getPrincipal());
assertThat(grant.getPrincipal()).withFailMessage("Principal was null on JaasGrantedAuthority").isNotNull();
foundit = true;
}
}
@ -232,8 +221,7 @@ public class JaasAuthenticationProviderTests {
assertThat(foundit).as("Could not find a JaasGrantedAuthority").isTrue();
assertThat(eventCheck.successEvent).as("Success event should be fired").isNotNull();
assertEquals("Auth objects should be equal", auth,
eventCheck.successEvent.getAuthentication());
assertThat(eventCheck.successEvent.getAuthentication()).withFailMessage("Auth objects should be equal").isEqualTo(auth);
assertThat(eventCheck.failedEvent).as("Failure event should not be fired").isNull();
}
@ -289,14 +277,14 @@ public class JaasAuthenticationProviderTests {
assertThat(jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
Authentication auth = jaasProvider.authenticate(token);
assertTrue("Only ROLE_TEST1 and ROLE_TEST2 should have been returned", auth
.getAuthorities().size() == 2);
assertThat(auth
.getAuthorities()).withFailMessage("Only ROLE_TEST1 and ROLE_TEST2 should have been returned").hasSize(2);
}
@Test
public void testUnsupportedAuthenticationObjectReturnsNull() {
assertNull(jaasProvider.authenticate(new TestingAuthenticationToken("foo", "bar",
AuthorityUtils.NO_AUTHORITIES)));
assertThat(jaasProvider.authenticate(new TestingAuthenticationToken("foo", "bar",
AuthorityUtils.NO_AUTHORITIES))).isNull();
}
// ~ Inner Classes

View File

@ -1,6 +1,6 @@
package org.springframework.security.authentication.jaas;
import junit.framework.Assert;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
@ -54,7 +54,7 @@ public class Sec760Tests {
"ROLE_TWO"));
Authentication auth = p1.authenticate(token);
Assert.assertThat(auth).isNotNull();
assertThat(auth).isNotNull();
}
@Test

View File

@ -15,8 +15,11 @@
package org.springframework.security.authentication.jaas;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.jaas.SecurityContextLoginModule;
import org.springframework.security.core.context.SecurityContextHolder;
@ -34,30 +37,33 @@ import javax.security.auth.login.LoginException;
*
* @author Ray Krueger
*/
public class SecurityContextLoginModuleTests extends TestCase {
public class SecurityContextLoginModuleTests {
// ~ Instance fields
// ================================================================================================
private SecurityContextLoginModule module = null;
private Subject subject = new Subject(false, new HashSet<Principal>(),
new HashSet<Object>(), new HashSet<Object>());
private UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
"principal", "credentials");
private Subject subject = new Subject(false, new HashSet<Principal>(), new HashSet<Object>(),
new HashSet<Object>());
private UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("principal",
"credentials");
// ~ Methods
// ========================================================================================================
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
module = new SecurityContextLoginModule();
module.initialize(subject, null, null, null);
SecurityContextHolder.clearContext();
}
protected void tearDown() throws Exception {
@After
public void tearDown() throws Exception {
SecurityContextHolder.clearContext();
module = null;
}
@Test
public void testAbort() throws Exception {
assertThat(module.abort()).as("Should return false, no auth is set").isFalse();
SecurityContextHolder.getContext().setAuthentication(auth);
@ -65,45 +71,46 @@ public class SecurityContextLoginModuleTests extends TestCase {
module.commit();
assertThat(module.abort()).isTrue();
}
@Test
public void testLoginException() throws Exception {
try {
module.login();
fail("LoginException expected, there is no Authentication in the SecurityContext");
}
catch (LoginException e) {
} catch (LoginException e) {
}
}
@Test
public void testLoginSuccess() throws Exception {
SecurityContextHolder.getContext().setAuthentication(auth);
assertThat(module.login()).as("Login should succeed, there is an authentication set").isTrue();
assertTrue("The authentication is not null, this should return true",
module.commit());
assertTrue("Principals should contain the authentication", subject
.getPrincipals().contains(auth));
assertThat(module.commit()).withFailMessage("The authentication is not null, this should return true").isTrue();
assertThat(subject.getPrincipals().contains(auth))
.withFailMessage("Principals should contain the authentication").isTrue();
}
@Test
public void testLogout() throws Exception {
SecurityContextHolder.getContext().setAuthentication(auth);
module.login();
assertThat(module.logout()).as("Should return true as it succeeds").isTrue();
assertThat(module.getAuthentication()).as("Authentication should be null").isEqualTo(null);
assertFalse("Principals should not contain the authentication after logout",
subject.getPrincipals().contains(auth));
assertThat(subject.getPrincipals().contains(auth)).withFailMessage("Principals should not contain the authentication after logout").isFalse();
}
@Test
public void testNullAuthenticationInSecurityContext() throws Exception {
try {
SecurityContextHolder.getContext().setAuthentication(null);
module.login();
fail("LoginException expected, the authentication is null in the SecurityContext");
}
catch (Exception e) {
} catch (Exception e) {
}
}
@Test
public void testNullAuthenticationInSecurityContextIgnored() throws Exception {
module = new SecurityContextLoginModule();
@ -114,7 +121,8 @@ public class SecurityContextLoginModuleTests extends TestCase {
SecurityContextHolder.getContext().setAuthentication(null);
assertThat(module.login()).as("Should return false and ask to be ignored").isFalse();
}
@Test
public void testNullLogout() throws Exception {
assertThat(module.logout()).isFalse();
}

View File

@ -15,9 +15,7 @@
*/
package org.springframework.security.authentication.jaas.memory;
import static org.junit.Assert.assertArrayEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
import java.lang.reflect.Method;
import java.util.Collections;
@ -54,8 +52,7 @@ public class InMemoryConfigurationTests {
@Test
public void constructorNullDefault() {
assertThat(new InMemoryConfiguration((AppConfigurationEntry[]) null).isNull()
.getAppConfigurationEntry("name"));
assertThat(new InMemoryConfiguration((AppConfigurationEntry[]) null).getAppConfigurationEntry("name")).isNull();
}
@Test(expected = IllegalArgumentException.class)
@ -65,16 +62,16 @@ public class InMemoryConfigurationTests {
@Test
public void constructorEmptyMap() {
assertNull(new InMemoryConfiguration(
assertThat(new InMemoryConfiguration(
Collections.<String, AppConfigurationEntry[]> emptyMap())
.getAppConfigurationEntry("name"));
.getAppConfigurationEntry("name")).isNull();
}
@Test
public void constructorEmptyMapNullDefault() {
assertNull(new InMemoryConfiguration(
assertThat(new InMemoryConfiguration(
Collections.<String, AppConfigurationEntry[]> emptyMap(), null)
.getAppConfigurationEntry("name"));
.getAppConfigurationEntry("name")).isNull();
}
@Test(expected = IllegalArgumentException.class)
@ -92,10 +89,8 @@ public class InMemoryConfigurationTests {
public void mappedNonnullDefault() {
InMemoryConfiguration configuration = new InMemoryConfiguration(mappedEntries,
defaultEntries);
assertArrayEquals(defaultEntries,
configuration.getAppConfigurationEntry("missing"));
assertArrayEquals(mappedEntries.get("name"),
configuration.getAppConfigurationEntry("name"));
assertThat(defaultEntries).isEqualTo(configuration.getAppConfigurationEntry("missing"));
assertThat(mappedEntries.get("name")).isEqualTo(configuration.getAppConfigurationEntry("name"));
}
@Test

View File

@ -15,13 +15,13 @@
package org.springframework.security.authentication.rcp;
import static org.assertj.core.api.Assertions.*;
import java.util.Collection;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
@ -30,10 +30,11 @@ import org.springframework.security.core.authority.AuthorityUtils;
*
* @author Ben Alex
*/
public class RemoteAuthenticationProviderTests extends TestCase {
public class RemoteAuthenticationProviderTests {
// ~ Methods
// ========================================================================================================
@Test
public void testExceptionsGetPassedBackToCaller() {
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false));
@ -47,13 +48,15 @@ public class RemoteAuthenticationProviderTests extends TestCase {
}
}
@Test
public void testGettersSetters() {
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(true));
assertThat(provider.getRemoteAuthenticationManager()).isNotNull();
}
@Test
public void testStartupChecksAuthenticationManagerSet() throws Exception {
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
@ -70,6 +73,7 @@ public class RemoteAuthenticationProviderTests extends TestCase {
}
@Test
public void testSuccessfulAuthenticationCreatesObject() {
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(true));
@ -78,10 +82,10 @@ public class RemoteAuthenticationProviderTests extends TestCase {
.authenticate(new UsernamePasswordAuthenticationToken("rod", "password"));
assertThat(result.getPrincipal()).isEqualTo("rod");
assertThat(result.getCredentials()).isEqualTo("password");
assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities()).isTrue().contains(
"foo"));
assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities()).contains("foo"));
}
@Test
public void testNullCredentialsDoesNotCauseNullPointerException() {
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false));
@ -95,6 +99,7 @@ public class RemoteAuthenticationProviderTests extends TestCase {
}
@Test
public void testSupports() {
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
assertThat(provider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();

View File

@ -15,8 +15,9 @@
package org.springframework.security.authentication.rememberme;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.RememberMeAuthenticationProvider;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
@ -29,10 +30,10 @@ import org.springframework.security.core.authority.AuthorityUtils;
*
* @author Ben Alex
*/
public class RememberMeAuthenticationProviderTests extends TestCase {
public class RememberMeAuthenticationProviderTests {
// ~ Methods
// ========================================================================================================
@Test
public void testDetectsAnInvalidKey() throws Exception {
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider(
"qwerty");
@ -48,7 +49,8 @@ public class RememberMeAuthenticationProviderTests extends TestCase {
catch (BadCredentialsException expected) {
}
}
@Test
public void testDetectsMissingKey() throws Exception {
try {
new RememberMeAuthenticationProvider(null);
@ -58,7 +60,8 @@ public class RememberMeAuthenticationProviderTests extends TestCase {
}
}
@Test
public void testGettersSetters() throws Exception {
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider(
"qwerty");
@ -66,6 +69,7 @@ public class RememberMeAuthenticationProviderTests extends TestCase {
assertThat(aap.getKey()).isEqualTo("qwerty");
}
@Test
public void testIgnoresClassesItDoesNotSupport() throws Exception {
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider(
"qwerty");
@ -78,6 +82,7 @@ public class RememberMeAuthenticationProviderTests extends TestCase {
assertThat(aap.authenticate(token)).isNull();
}
@Test
public void testNormalOperation() throws Exception {
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider(
"qwerty");
@ -90,6 +95,7 @@ public class RememberMeAuthenticationProviderTests extends TestCase {
assertThat(token).isEqualTo(result);
}
@Test
public void testSupports() {
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider(
"qwerty");

View File

@ -15,11 +15,13 @@
package org.springframework.security.authentication.rememberme;
import static org.assertj.core.api.Assertions.*;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
@ -30,13 +32,13 @@ import org.springframework.security.core.authority.AuthorityUtils;
*
* @author Ben Alex
*/
public class RememberMeAuthenticationTokenTests extends TestCase {
public class RememberMeAuthenticationTokenTests {
private static final List<GrantedAuthority> ROLES_12 = AuthorityUtils
.createAuthorityList("ROLE_ONE", "ROLE_TWO");
// ~ Methods
// ========================================================================================================
@Test
public void testConstructorRejectsNulls() {
try {
new RememberMeAuthenticationToken(null, "Test", ROLES_12);
@ -65,6 +67,7 @@ public class RememberMeAuthenticationTokenTests extends TestCase {
}
}
@Test
public void testEqualsWhenEqual() {
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key",
"Test", ROLES_12);
@ -74,6 +77,7 @@ public class RememberMeAuthenticationTokenTests extends TestCase {
assertThat(token2).isEqualTo(token1);
}
@Test
public void testGetters() {
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("key",
"Test", ROLES_12);
@ -81,13 +85,14 @@ public class RememberMeAuthenticationTokenTests extends TestCase {
assertThat(token.getKeyHash()).isEqualTo("key".hashCode());
assertThat(token.getPrincipal()).isEqualTo("Test");
assertThat(token.getCredentials()).isEqualTo("");
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities()).isTrue().contains(
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities()).contains(
"ROLE_ONE"));
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities()).isTrue().contains(
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities()).contains(
"ROLE_TWO"));
assertThat(token.isAuthenticated()).isTrue();
}
@Test
public void testNotEqualsDueToAbstractParentEqualsCheck() {
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key",
"Test", ROLES_12);
@ -97,6 +102,7 @@ public class RememberMeAuthenticationTokenTests extends TestCase {
assertThat(token1.equals(token2)).isFalse();
}
@Test
public void testNotEqualsDueToDifferentAuthenticationClass() {
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key",
"Test", ROLES_12);
@ -106,6 +112,7 @@ public class RememberMeAuthenticationTokenTests extends TestCase {
assertThat(token1.equals(token2)).isFalse();
}
@Test
public void testNotEqualsDueToKey() {
RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key",
"Test", ROLES_12);
@ -115,6 +122,7 @@ public class RememberMeAuthenticationTokenTests extends TestCase {
assertThat(token1.equals(token2)).isFalse();
}
@Test
public void testSetAuthenticatedIgnored() {
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("key",
"Test", ROLES_12);

View File

@ -15,28 +15,30 @@
package org.springframework.security.core;
import junit.framework.TestCase;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.core.SpringSecurityMessageSource;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Locale;
import org.junit.Test;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.MessageSourceAccessor;
/**
* Tests {@link org.springframework.security.core.SpringSecurityMessageSource}.
*/
public class SpringSecurityMessageSourceTests extends TestCase {
public class SpringSecurityMessageSourceTests {
// ~ Methods
// ========================================================================================================
@Test
public void testOperation() {
SpringSecurityMessageSource msgs = new SpringSecurityMessageSource();
assertEquals("\u4E0D\u5141\u8BB8\u8BBF\u95EE", msgs.getMessage(
"AbstractAccessDecisionManager.accessDenied", null,
Locale.SIMPLIFIED_CHINESE));
assertThat("\u4E0D\u5141\u8BB8\u8BBF\u95EE").isEqualTo(
msgs.getMessage("AbstractAccessDecisionManager.accessDenied", null,
Locale.SIMPLIFIED_CHINESE));
}
@Test
public void testReplacableLookup() {
// Change Locale to English
Locale before = LocaleContextHolder.getLocale();
@ -44,15 +46,16 @@ public class SpringSecurityMessageSourceTests extends TestCase {
// Cause a message to be generated
MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
assertEquals("Le jeton nonce est compromis FOOBAR", messages.getMessage(
"DigestAuthenticationFilter.nonceCompromised", new Object[] { "FOOBAR" },
"ERROR - FAILED TO LOOKUP"));
assertThat("Le jeton nonce est compromis FOOBAR").isEqualTo(
messages.getMessage("DigestAuthenticationFilter.nonceCompromised",
new Object[] { "FOOBAR" }, "ERROR - FAILED TO LOOKUP"));
// Revert to original Locale
LocaleContextHolder.setLocale(before);
}
// SEC-3013
@Test
public void germanSystemLocaleWithEnglishLocaleContextHolder() {
Locale beforeSystem = Locale.getDefault();
Locale.setDefault(Locale.GERMAN);
@ -61,8 +64,8 @@ public class SpringSecurityMessageSourceTests extends TestCase {
LocaleContextHolder.setLocale(Locale.US);
MessageSourceAccessor msgs = SpringSecurityMessageSource.getAccessor();
assertEquals("Access is denied", msgs.getMessage(
"AbstractAccessDecisionManager.accessDenied", "Ooops"));
assertThat("Access is denied").isEqualTo(
msgs.getMessage("AbstractAccessDecisionManager.accessDenied", "Ooops"));
// Revert to original Locale
Locale.setDefault(beforeSystem);

View File

@ -1,6 +1,6 @@
package org.springframework.security.core.authority;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.*;
import java.util.List;
import java.util.Set;

View File

@ -1,6 +1,6 @@
package org.springframework.security.core.authority.mapping;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.security.core.GrantedAuthority;
@ -192,8 +192,7 @@ public class MapBasedAttributes2GrantedAuthoritiesMapperTests {
resultColl.add(auth.getAuthority());
}
Collection expectedColl = Arrays.asList(expectedGas);
assertTrue("Role collections should match; result: " + resultColl
+ ", expected: " + expectedColl, expectedColl.containsAll(resultColl)
&& resultColl.containsAll(expectedColl));
assertThat(resultColl.containsAll(expectedColl)).withFailMessage("Role collections should match; result: " + resultColl
+ ", expected: " + expectedColl).isTrue();
}
}

View File

@ -1,10 +1,11 @@
package org.springframework.security.core.authority.mapping;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Set;
import junit.framework.TestCase;
import org.springframework.security.core.authority.mapping.SimpleMappableAttributesRetriever;
import org.junit.Test;
import org.springframework.util.StringUtils;
/**
@ -12,15 +13,18 @@ import org.springframework.util.StringUtils;
* @author TSARDD
* @since 18-okt-2007
*/
public class SimpleMappableRolesRetrieverTests extends TestCase {
public class SimpleMappableRolesRetrieverTests {
@Test
public final void testGetSetMappableRoles() {
Set<String> roles = StringUtils.commaDelimitedListToSet("Role1,Role2");
SimpleMappableAttributesRetriever r = new SimpleMappableAttributesRetriever();
r.setMappableAttributes(roles);
Set<String> result = r.getMappableAttributes();
assertTrue("Role collections do not match; result: " + result + ", expected: "
+ roles, roles.containsAll(result) && result.containsAll(roles));
assertThat(
roles.containsAll(result) && result.containsAll(roles)).withFailMessage(
"Role collections do not match; result: " + result
+ ", expected: " + roles).isTrue();
}
}

View File

@ -1,6 +1,8 @@
package org.springframework.security.core.authority.mapping;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.security.core.GrantedAuthority;
import java.util.*;
@ -10,8 +12,9 @@ import java.util.*;
* @author TSARDD
* @since 18-okt-2007
*/
public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase {
public class SimpleRoles2GrantedAuthoritiesMapperTests {
@Test
public final void testAfterPropertiesSetConvertToUpperAndLowerCase() {
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
mapper.setConvertAttributeToLowerCase(true);
@ -27,6 +30,7 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase {
}
}
@Test
public final void testAfterPropertiesSet() {
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
try {
@ -37,6 +41,7 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase {
}
}
@Test
public final void testGetGrantedAuthoritiesNoConversion() {
String[] roles = { "Role1", "Role2" };
String[] expectedGas = { "Role1", "Role2" };
@ -44,6 +49,7 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase {
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public final void testGetGrantedAuthoritiesToUpperCase() {
String[] roles = { "Role1", "Role2" };
String[] expectedGas = { "ROLE1", "ROLE2" };
@ -52,6 +58,7 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase {
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public final void testGetGrantedAuthoritiesToLowerCase() {
String[] roles = { "Role1", "Role2" };
String[] expectedGas = { "role1", "role2" };
@ -60,6 +67,7 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase {
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public final void testGetGrantedAuthoritiesAddPrefixIfAlreadyExisting() {
String[] roles = { "Role1", "Role2", "ROLE_Role3" };
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_ROLE_Role3" };
@ -69,6 +77,7 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase {
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public final void testGetGrantedAuthoritiesDontAddPrefixIfAlreadyExisting1() {
String[] roles = { "Role1", "Role2", "ROLE_Role3" };
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_Role3" };
@ -78,6 +87,7 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase {
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public final void testGetGrantedAuthoritiesDontAddPrefixIfAlreadyExisting2() {
String[] roles = { "Role1", "Role2", "role_Role3" };
String[] expectedGas = { "ROLE_Role1", "ROLE_Role2", "ROLE_role_Role3" };
@ -87,6 +97,7 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase {
testGetGrantedAuthorities(mapper, roles, expectedGas);
}
@Test
public final void testGetGrantedAuthoritiesCombination1() {
String[] roles = { "Role1", "Role2", "role_Role3" };
String[] expectedGas = { "ROLE_ROLE1", "ROLE_ROLE2", "ROLE_ROLE3" };
@ -107,9 +118,9 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests extends TestCase {
resultColl.add(result.get(i).getAuthority());
}
Collection<String> expectedColl = Arrays.asList(expectedGas);
assertTrue("Role collections do not match; result: " + resultColl
+ ", expected: " + expectedColl, expectedColl.containsAll(resultColl)
&& resultColl.containsAll(expectedColl));
assertThat(expectedColl.containsAll(resultColl)
&& resultColl.containsAll(expectedColl)).withFailMessage("Role collections do not match; result: " + resultColl
+ ", expected: " + expectedColl).isTrue();
}
private SimpleAttributes2GrantedAuthoritiesMapper getDefaultMapper() {

View File

@ -15,8 +15,10 @@
package org.springframework.security.core.context;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextImpl;
@ -25,16 +27,17 @@ import org.springframework.security.core.context.SecurityContextImpl;
*
* @author Ben Alex
*/
public class SecurityContextHolderTests extends TestCase {
public class SecurityContextHolderTests {
// ~ Methods
// ========================================================================================================
@Before
public final void setUp() throws Exception {
SecurityContextHolder
.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
}
@Test
public void testContextHolderGetterSetterClearer() {
SecurityContext sc = new SecurityContextImpl();
sc.setAuthentication(new UsernamePasswordAuthenticationToken("Foobar", "pass"));
@ -45,11 +48,13 @@ public class SecurityContextHolderTests extends TestCase {
SecurityContextHolder.clearContext();
}
@Test
public void testNeverReturnsNull() {
assertThat(SecurityContextHolder.getContext()).isNotNull();
SecurityContextHolder.clearContext();
}
@Test
public void testRejectsNulls() {
try {
SecurityContextHolder.setContext(null);

View File

@ -15,18 +15,18 @@
package org.springframework.security.core.context;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextImpl;
/**
* Tests {@link SecurityContextImpl}.
*
* @author Ben Alex
*/
public class SecurityContextImplTests extends TestCase {
public class SecurityContextImplTests {
// ~ Constructors
// ===================================================================================================
@ -34,19 +34,16 @@ public class SecurityContextImplTests extends TestCase {
super();
}
public SecurityContextImplTests(String arg0) {
super(arg0);
}
// ~ Methods
// ========================================================================================================
@Test
public void testEmptyObjectsAreEquals() {
SecurityContextImpl obj1 = new SecurityContextImpl();
SecurityContextImpl obj2 = new SecurityContextImpl();
assertThat(obj1.equals(obj2)).isTrue();
}
@Test
public void testSecurityContextCorrectOperation() {
SecurityContext context = new SecurityContextImpl();
Authentication auth = new UsernamePasswordAuthenticationToken("rod", "koala");

View File

@ -15,21 +15,22 @@
package org.springframework.security.core.session;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Date;
import org.springframework.security.core.session.SessionInformation;
import org.junit.Test;
/**
* Tests {@link SessionInformation}.
*
* @author Ben Alex
*/
public class SessionInformationTests extends TestCase {
public class SessionInformationTests {
// ~ Methods
// ========================================================================================================
@Test
public void testObject() throws Exception {
Object principal = "Some principal object";
String sessionId = "1234567890";

View File

@ -95,10 +95,8 @@ public class SessionRegistryImplTests {
// Retrieve existing session by session ID
Date currentDateTime = sessionRegistry.getSessionInformation(sessionId)
.getLastRequest();
assertThat(sessionRegistry.getSessionInformation(sessionId).isEqualTo(principal)
.getPrincipal());
assertThat(sessionRegistry.getSessionInformation(sessionId).isEqualTo(sessionId)
.getSessionId());
assertThat(sessionRegistry.getSessionInformation(sessionId).getPrincipal()).isEqualTo(principal);
assertThat(sessionRegistry.getSessionInformation(sessionId).getSessionId()).isEqualTo(sessionId);
assertThat(sessionRegistry.getSessionInformation(sessionId).getLastRequest()).isNotNull();
// Retrieve existing session by principal
@ -115,8 +113,7 @@ public class SessionRegistryImplTests {
assertThat(retrieved.after(currentDateTime)).isTrue();
// Check it retrieves correctly when looked up via principal
assertThat(sessionRegistry.getAllSessions(principal).isCloseTo(retrieved, within(false).get(0))
.getLastRequest());
assertThat(sessionRegistry.getAllSessions(principal, false).get(0).getLastRequest()).isCloseTo(retrieved, 2000L);
// Clear session information
sessionRegistry.removeSessionInformation(sessionId);

View File

@ -2,7 +2,7 @@ package org.springframework.security.core.token;
import java.util.Date;
import junit.framework.Assert;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.security.core.token.DefaultToken;
@ -22,7 +22,7 @@ public class DefaultTokenTests {
DefaultToken t1 = new DefaultToken(key, created, extendedInformation);
DefaultToken t2 = new DefaultToken(key, created, extendedInformation);
Assert.assertThat(t2).isEqualTo(t1);
assertThat(t2).isEqualTo(t1);
}
@Test(expected = IllegalArgumentException.class)
@ -39,6 +39,6 @@ public class DefaultTokenTests {
DefaultToken t1 = new DefaultToken(key, created, "length1");
DefaultToken t2 = new DefaultToken(key, created, "longerLength2");
Assert.assertThat(t1.equals(t2)).isFalse();
assertThat(t1).isNotEqualTo(t2);
}
}

View File

@ -1,10 +1,10 @@
package org.springframework.security.core.token;
import static org.assertj.core.api.Assertions.*;
import java.security.SecureRandom;
import java.util.Date;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.security.core.token.DefaultToken;
import org.springframework.security.core.token.KeyBasedPersistenceTokenService;
@ -40,7 +40,7 @@ public class KeyBasedPersistenceTokenServiceTests {
KeyBasedPersistenceTokenService service = getService();
Token token = service.allocateToken("Hello world");
Token result = service.verifyToken(token.getKey());
Assert.assertThat(result).isEqualTo(token);
assertThat(result).isEqualTo(token);
}
@Test
@ -48,7 +48,7 @@ public class KeyBasedPersistenceTokenServiceTests {
KeyBasedPersistenceTokenService service = getService();
Token token = service.allocateToken("Hello:world:::");
Token result = service.verifyToken(token.getKey());
Assert.assertThat(result).isEqualTo(token);
assertThat(result).isEqualTo(token);
}
@Test
@ -57,7 +57,7 @@ public class KeyBasedPersistenceTokenServiceTests {
service.setPseudoRandomNumberBytes(0);
Token token = service.allocateToken("Hello:world:::");
Token result = service.verifyToken(token.getKey());
Assert.assertThat(result).isEqualTo(token);
assertThat(result).isEqualTo(token);
}
@Test
@ -65,7 +65,7 @@ public class KeyBasedPersistenceTokenServiceTests {
KeyBasedPersistenceTokenService service = getService();
Token token = service.allocateToken("");
Token result = service.verifyToken(token.getKey());
Assert.assertThat(result).isEqualTo(token);
assertThat(result).isEqualTo(token);
}
@Test(expected = IllegalArgumentException.class)

View File

@ -1,5 +1,7 @@
package org.springframework.security.core.token;
import static org.assertj.core.api.Assertions.*;
import java.security.SecureRandom;
import org.junit.Test;
@ -7,8 +9,6 @@ import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.core.token.SecureRandomFactoryBean;
import junit.framework.Assert;
/**
* Tests {@link SecureRandomFactoryBean}.
*
@ -19,22 +19,22 @@ public class SecureRandomFactoryBeanTests {
@Test
public void testObjectType() {
SecureRandomFactoryBean factory = new SecureRandomFactoryBean();
Assert.assertThat(factory.getObjectType()).isEqualTo(SecureRandom.class);
assertThat(factory.getObjectType()).isEqualTo(SecureRandom.class);
}
@Test
public void testIsSingleton() {
SecureRandomFactoryBean factory = new SecureRandomFactoryBean();
Assert.assertThat(factory.isSingleton()).isFalse();
assertThat(factory.isSingleton()).isFalse();
}
@Test
public void testCreatesUsingDefaults() throws Exception {
SecureRandomFactoryBean factory = new SecureRandomFactoryBean();
Object result = factory.getObject();
Assert.assertThat(result instanceof SecureRandom).isTrue();
assertThat(result).isInstanceOf(SecureRandom.class);
int rnd = ((SecureRandom) result).nextInt();
Assert.assertThat(rnd != 0).isTrue();
assertThat(rnd).isNotEqualTo(0);
}
@Test
@ -42,12 +42,12 @@ public class SecureRandomFactoryBeanTests {
SecureRandomFactoryBean factory = new SecureRandomFactoryBean();
Resource resource = new ClassPathResource(
"org/springframework/security/core/token/SecureRandomFactoryBeanTests.class");
Assert.assertThat(resource).isNotNull();
assertThat(resource).isNotNull();
factory.setSeed(resource);
Object result = factory.getObject();
Assert.assertThat(result instanceof SecureRandom).isTrue();
assertThat(result).isInstanceOf(SecureRandom.class);
int rnd = ((SecureRandom) result).nextInt();
Assert.assertThat(rnd != 0).isTrue();
assertThat(rnd).isNotEqualTo(0);
}
}

View File

@ -1,7 +1,8 @@
package org.springframework.security.core.userdetails;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
@ -11,8 +12,9 @@ import org.springframework.security.core.authority.AuthorityUtils;
* @since 18-okt-2007
*/
@SuppressWarnings("unchecked")
public class UserDetailsByNameServiceWrapperTests extends TestCase {
public class UserDetailsByNameServiceWrapperTests {
@Test
public final void testAfterPropertiesSet() {
UserDetailsByNameServiceWrapper svc = new UserDetailsByNameServiceWrapper();
try {
@ -26,6 +28,7 @@ public class UserDetailsByNameServiceWrapperTests extends TestCase {
}
}
@Test
public final void testGetUserDetails() throws Exception {
UserDetailsByNameServiceWrapper svc = new UserDetailsByNameServiceWrapper();
final User user = new User("dummy", "dummy", true, true, true, true,

View File

@ -44,10 +44,10 @@ public class UserTests {
public void equalsReturnsTrueIfUsernamesAreTheSame() {
User user1 = new User("rod", "koala", true, true, true, true, ROLE_12);
assertThat(user1.equals(null)).isFalse();
assertThat(user1.equals("A STRING")).isFalse();
assertThat(user1.equals(user1)).isTrue();
assertTrue(user1.equals(new User("rod", "notthesame", true, true, true, true,
assertThat(user1).isNotNull();
assertThat(user1).isNotEqualTo("A STRING");
assertThat(user1).isEqualTo(user1);
assertThat(user1).isEqualTo((new User("rod", "notthesame", true, true, true, true,
ROLE_12)));
}
@ -57,12 +57,12 @@ public class UserTests {
Set<UserDetails> users = new HashSet<UserDetails>();
users.add(user1);
assertTrue(users.contains(new User("rod", "koala", true, true, true, true,
ROLE_12)));
assertTrue(users.contains(new User("rod", "anotherpass", false, false, false,
false, AuthorityUtils.createAuthorityList("ROLE_X"))));
assertFalse(users.contains(new User("bod", "koala", true, true, true, true,
ROLE_12)));
assertThat(users).contains(new User("rod", "koala", true, true, true, true,
ROLE_12));
assertThat(users).contains(new User("rod", "anotherpass", false, false, false,
false, AuthorityUtils.createAuthorityList("ROLE_X")));
assertThat(users).doesNotContain(new User("bod", "koala", true, true, true, true,
ROLE_12));
}
@Test
@ -123,10 +123,10 @@ public class UserTests {
assertThat(user.getUsername()).isEqualTo("rod");
assertThat(user.getPassword()).isEqualTo("koala");
assertThat(user.isEnabled()).isTrue();
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains(
"ROLE_ONE"));
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains(
"ROLE_TWO"));
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities())).contains(
"ROLE_ONE");
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities())).contains(
"ROLE_TWO");
assertThat(user.toString().indexOf("rod") != -1).isTrue();
}

View File

@ -70,8 +70,7 @@ public class EhCacheBasedUserCacheTests {
// Check it gets stored in the cache
cache.putUserInCache(getUser());
assertEquals(getUser().getPassword(),
cache.getUserFromCache(getUser().getUsername()).getPassword());
assertThat(getUser().getPassword()).isEqualTo(cache.getUserFromCache(getUser().getUsername()).getPassword());
// Check it gets removed from the cache
cache.removeUserFromCache(getUser());

View File

@ -15,18 +15,18 @@
package org.springframework.security.core.userdetails.cache;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.cache.NullUserCache;
/**
* Tests {@link NullUserCache}.
*
* @author Ben Alex
*/
public class NullUserCacheTests extends TestCase {
public class NullUserCacheTests {
// ~ Methods
// ========================================================================================================
@ -36,6 +36,7 @@ public class NullUserCacheTests extends TestCase {
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
}
@Test
public void testCacheOperation() throws Exception {
NullUserCache cache = new NullUserCache();
cache.putUserInCache(getUser());

View File

@ -66,8 +66,7 @@ public class SpringCacheBasedUserCacheTests {
// Check it gets stored in the cache
cache.putUserInCache(getUser());
assertEquals(getUser().getPassword(),
cache.getUserFromCache(getUser().getUsername()).getPassword());
assertThat(getUser().getPassword()).isEqualTo(cache.getUserFromCache(getUser().getUsername()).getPassword());
// Check it gets removed from the cache
cache.removeUserFromCache(getUser());

View File

@ -15,7 +15,9 @@
package org.springframework.security.core.userdetails.jdbc;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.security.PopulatedDatabase;
import org.springframework.security.core.authority.AuthorityUtils;
@ -27,7 +29,7 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
*
* @author Ben Alex
*/
public class JdbcDaoImplTests extends TestCase {
public class JdbcDaoImplTests {
// ~ Methods
// ========================================================================================================
@ -49,6 +51,7 @@ public class JdbcDaoImplTests extends TestCase {
return dao;
}
@Test
public void testCheckDaoAccessUserSuccess() throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao();
UserDetails user = dao.loadUserByUsername("rod");
@ -56,26 +59,29 @@ public class JdbcDaoImplTests extends TestCase {
assertThat(user.getPassword()).isEqualTo("koala");
assertThat(user.isEnabled()).isTrue();
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains(
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ROLE_TELLER"));
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains(
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ROLE_SUPERVISOR"));
}
@Test
public void testCheckDaoOnlyReturnsGrantedAuthoritiesGrantedToUser() throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao();
UserDetails user = dao.loadUserByUsername("scott");
assertThat(user.getAuthorities()).hasSize(1);
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains(
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ROLE_TELLER"));
}
@Test
public void testCheckDaoReturnsCorrectDisabledProperty() throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao();
UserDetails user = dao.loadUserByUsername("peter");
assertThat(!user.isEnabled()).isTrue();
assertThat(user.isEnabled()).isFalse();
}
@Test
public void testGettersSetters() {
JdbcDaoImpl dao = new JdbcDaoImpl();
dao.setAuthoritiesByUsernameQuery("SELECT * FROM FOO");
@ -85,6 +91,7 @@ public class JdbcDaoImplTests extends TestCase {
assertThat(dao.getUsersByUsernameQuery()).isEqualTo("SELECT USERS FROM FOO");
}
@Test
public void testLookupFailsIfUserHasNoGrantedAuthorities() throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao();
@ -96,6 +103,7 @@ public class JdbcDaoImplTests extends TestCase {
}
}
@Test
public void testLookupFailsWithWrongUsername() throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao();
@ -108,12 +116,14 @@ public class JdbcDaoImplTests extends TestCase {
}
}
@Test
public void testLookupSuccessWithMixedCase() throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao();
assertThat(dao.loadUserByUsername("rod").getPassword()).isEqualTo("koala");
assertThat(dao.loadUserByUsername("ScOTt").getPassword()).isEqualTo("wombat");
}
@Test
public void testRolePrefixWorks() throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDaoWithRolePrefix();
assertThat(dao.getRolePrefix()).isEqualTo("ARBITRARY_PREFIX_");
@ -122,12 +132,13 @@ public class JdbcDaoImplTests extends TestCase {
assertThat(user.getUsername()).isEqualTo("rod");
assertThat(user.getAuthorities()).hasSize(2);
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains(
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ARBITRARY_PREFIX_ROLE_TELLER"));
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains(
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ARBITRARY_PREFIX_ROLE_SUPERVISOR"));
}
@Test
public void testGroupAuthoritiesAreLoadedCorrectly() throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao();
dao.setEnableAuthorities(false);
@ -137,6 +148,7 @@ public class JdbcDaoImplTests extends TestCase {
assertThat(jerry.getAuthorities()).hasSize(3);
}
@Test
public void testDuplicateGroupAuthoritiesAreRemoved() throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao();
dao.setEnableAuthorities(false);
@ -146,6 +158,7 @@ public class JdbcDaoImplTests extends TestCase {
assertThat(tom.getAuthorities()).hasSize(3);
}
@Test
public void testStartupFailsIfDataSourceNotSet() throws Exception {
JdbcDaoImpl dao = new JdbcDaoImpl();
@ -158,6 +171,7 @@ public class JdbcDaoImplTests extends TestCase {
}
}
@Test
public void testStartupFailsIfUserMapSetToNull() throws Exception {
JdbcDaoImpl dao = new JdbcDaoImpl();

View File

@ -15,18 +15,18 @@
package org.springframework.security.core.userdetails.memory;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.assertThat;
import org.springframework.security.core.userdetails.memory.UserAttribute;
import org.springframework.security.core.userdetails.memory.UserAttributeEditor;
import org.junit.Test;
/**
* Tests {@link UserAttributeEditor} and associated {@link UserAttribute}.
*
* @author Ben Alex
*/
public class UserAttributeEditorTests extends TestCase {
public class UserAttributeEditorTests {
@Test
public void testCorrectOperationWithTrailingSpaces() {
UserAttributeEditor editor = new UserAttributeEditor();
editor.setAsText("password ,ROLE_ONE,ROLE_TWO ");
@ -38,6 +38,7 @@ public class UserAttributeEditorTests extends TestCase {
assertThat(user.getAuthorities().get(1).getAuthority()).isEqualTo("ROLE_TWO");
}
@Test
public void testCorrectOperationWithoutEnabledDisabledKeyword() {
UserAttributeEditor editor = new UserAttributeEditor();
editor.setAsText("password,ROLE_ONE,ROLE_TWO");
@ -51,6 +52,7 @@ public class UserAttributeEditorTests extends TestCase {
assertThat(user.getAuthorities().get(1).getAuthority()).isEqualTo("ROLE_TWO");
}
@Test
public void testDisabledKeyword() {
UserAttributeEditor editor = new UserAttributeEditor();
editor.setAsText("password,disabled,ROLE_ONE,ROLE_TWO");
@ -64,6 +66,7 @@ public class UserAttributeEditorTests extends TestCase {
assertThat(user.getAuthorities().get(1).getAuthority()).isEqualTo("ROLE_TWO");
}
@Test
public void testEmptyStringReturnsNull() {
UserAttributeEditor editor = new UserAttributeEditor();
editor.setAsText("");
@ -72,6 +75,7 @@ public class UserAttributeEditorTests extends TestCase {
assertThat(user == null).isTrue();
}
@Test
public void testEnabledKeyword() {
UserAttributeEditor editor = new UserAttributeEditor();
editor.setAsText("password,ROLE_ONE,enabled,ROLE_TWO");
@ -85,6 +89,7 @@ public class UserAttributeEditorTests extends TestCase {
assertThat(user.getAuthorities().get(1).getAuthority()).isEqualTo("ROLE_TWO");
}
@Test
public void testMalformedStringReturnsNull() {
UserAttributeEditor editor = new UserAttributeEditor();
editor.setAsText("MALFORMED_STRING");
@ -93,6 +98,7 @@ public class UserAttributeEditorTests extends TestCase {
assertThat(user == null).isTrue();
}
@Test
public void testNoPasswordOrRolesReturnsNull() {
UserAttributeEditor editor = new UserAttributeEditor();
editor.setAsText("disabled");
@ -101,6 +107,7 @@ public class UserAttributeEditorTests extends TestCase {
assertThat(user == null).isTrue();
}
@Test
public void testNoRolesReturnsNull() {
UserAttributeEditor editor = new UserAttributeEditor();
editor.setAsText("password,enabled");
@ -109,6 +116,7 @@ public class UserAttributeEditorTests extends TestCase {
assertThat(user == null).isTrue();
}
@Test
public void testNullReturnsNull() {
UserAttributeEditor editor = new UserAttributeEditor();
editor.setAsText(null);

View File

@ -193,8 +193,7 @@ public class JdbcUserDetailsManagerTests {
// Check password hasn't changed.
UserDetails newJoe = manager.loadUserByUsername("joe");
assertThat(newJoe.getPassword()).isEqualTo("password");
assertThat(SecurityContextHolder.getContext().getAuthentication().isEqualTo("password")
.getCredentials());
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("password");
assertThat(cache.getUserMap().containsKey("joe")).isTrue();
}
@ -248,37 +247,31 @@ public class JdbcUserDetailsManagerTests {
public void renameGroupIsSuccessful() throws Exception {
manager.renameGroup("GROUP_0", "GROUP_X");
assertEquals(
0,
(int) template.queryForObject("select id from groups where group_name = 'GROUP_X'",
Integer.class));
assertThat(template.queryForObject("select id from groups where group_name = 'GROUP_X'",
Integer.class)).isEqualTo(0);
}
@Test
public void addingGroupUserSetsCorrectData() throws Exception {
manager.addUserToGroup("tom", "GROUP_0");
assertEquals(
2,
assertThat(
template.queryForList(
"select username from group_members where group_id = 0").size());
"select username from group_members where group_id = 0")).hasSize(2);
}
@Test
public void removeUserFromGroupDeletesGroupMemberRow() throws Exception {
manager.removeUserFromGroup("jerry", "GROUP_1");
assertEquals(
1,
template.queryForList(
"select group_id from group_members where username = 'jerry'")
.size());
assertThat(
template.queryForList(
"select group_id from group_members where username = 'jerry'")).hasSize(1);
}
@Test
public void findGroupAuthoritiesReturnsCorrectAuthorities() throws Exception {
assertEquals(AuthorityUtils.createAuthorityList("ROLE_A"),
manager.findGroupAuthorities("GROUP_0"));
assertThat(AuthorityUtils.createAuthorityList("ROLE_A")).isEqualTo(manager.findGroupAuthorities("GROUP_0"));
}
@Test
@ -295,18 +288,14 @@ public class JdbcUserDetailsManagerTests {
public void deleteGroupAuthorityRemovesCorrectRows() throws Exception {
GrantedAuthority auth = new SimpleGrantedAuthority("ROLE_A");
manager.removeGroupAuthority("GROUP_0", auth);
assertEquals(
0,
assertThat(
template.queryForList(
"select authority from group_authorities where group_id = 0")
.size());
"select authority from group_authorities where group_id = 0")).isEmpty();
manager.removeGroupAuthority("GROUP_2", auth);
assertEquals(
2,
assertThat(
template.queryForList(
"select authority from group_authorities where group_id = 2")
.size());
"select authority from group_authorities where group_id = 2")).hasSize(2);
}
// SEC-1156

View File

@ -15,8 +15,7 @@
*/
package org.springframework.security.crypto.bcrypt;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;

View File

@ -209,9 +209,9 @@ public class BCryptTests {
@Test
public void testBase64EncodeSimpleByteArrays() {
assertThat(1)).as("..").isEqualTo(encode_base64(new byte[] { 0 });
assertThat(0 }).as("...").isCloseTo(encode_base64(new byte[] { 0, within(2)));
assertThat(0 }).as("....").isCloseTo(encode_base64(new byte[] { 0, 0, within(3)));
assertThat(encode_base64(new byte[] { 0 }, 1)).isEqualTo("..");
assertThat(encode_base64(new byte[] { 0, 0 }, 2)).isEqualTo("...");
assertThat(encode_base64(new byte[] { 0, 0 , 0 }, 3)).isEqualTo("....");
}
@Test
@ -222,16 +222,16 @@ public class BCryptTests {
@Test
public void decodingStopsWithFirstInvalidCharacter() {
assertThat(1).length).isEqualTo(1, BCrypt.decode_base64("....");
assertThat(1).length).isEqualTo(0, BCrypt.decode_base64(" ....");
assertThat(BCrypt.decode_base64("....", 1).length).isEqualTo(1);
assertThat(BCrypt.decode_base64(" ....", 1).length).isEqualTo(0);
}
@Test
public void decodingOnlyProvidesAvailableBytes() {
assertThat(1).length).isEqualTo(0, BCrypt.decode_base64("");
assertThat(3).length).isEqualTo(3, BCrypt.decode_base64("......");
assertThat(4).length).isEqualTo(4, BCrypt.decode_base64("......");
assertThat(5).length).isEqualTo(4, BCrypt.decode_base64("......");
assertThat(BCrypt.decode_base64("", 1).length).isEqualTo(0);
assertThat(BCrypt.decode_base64("......", 3).length).isEqualTo(3);
assertThat(BCrypt.decode_base64("......", 4).length).isEqualTo(4);
assertThat(BCrypt.decode_base64("......", 5).length).isEqualTo(4);
}
/**
@ -288,8 +288,8 @@ public class BCryptTests {
@Test
public void hashpwWorksWithOldRevision() {
assertEquals("$2$05$......................bvpG2UfzdyW/S0ny/4YyEZrmczoJfVm",
BCrypt.hashpw("password", "$2$05$......................"));
assertThat(BCrypt.hashpw("password", "$2$05$......................")).isEqualTo(
"$2$05$......................bvpG2UfzdyW/S0ny/4YyEZrmczoJfVm");
}
@Test

View File

@ -13,15 +13,15 @@ public class Base64Tests {
public void isBase64ReturnsTrueForValidBase64() {
new Base64(); // unused
assertThat(Base64.isBase64(new byte[] { (byte) 'A', (byte) 'B', (byte).isTrue() 'C',
(byte) 'D' }));
assertThat(Base64.isBase64(new byte[] { (byte) 'A', (byte) 'B', (byte) 'C',
(byte) 'D' })).isTrue();
}
@Test
public void isBase64ReturnsFalseForInvalidBase64() throws Exception {
// Include invalid '`' character
assertThat(Base64.isBase64(new byte[] { (byte) 'A', (byte) 'B', (byte).isFalse() 'C',
(byte) '`' }));
assertThat(Base64.isBase64(new byte[] { (byte) 'A', (byte) 'B', (byte) 'C',
(byte) '`' })).isFalse();
}
@Test(expected = NullPointerException.class)

View File

@ -1,9 +1,7 @@
package org.springframework.security.crypto.encrypt;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.security.GeneralSecurityException;
@ -23,8 +21,8 @@ public class EncryptorsTests {
assertThat(result).isNotNull();
assertThat(new String(result).equals("text")).isFalse();
assertThat(new String(encryptor.decrypt(result))).isEqualTo("text");
assertThat(new String(result).isFalse().equals(new String(encryptor.encrypt("text"
.getBytes()))));
assertThat(new String(result)).isNotEqualTo(
new String(encryptor.encrypt("text".getBytes())));
}
@Test
@ -34,8 +32,8 @@ public class EncryptorsTests {
assertThat(result).isNotNull();
assertThat(new String(result).equals("text")).isFalse();
assertThat(new String(encryptor.decrypt(result))).isEqualTo("text");
assertThat(new String(result).isFalse().equals(new String(encryptor.encrypt("text"
.getBytes()))));
assertThat(new String(result)).isNotEqualTo(
new String(encryptor.encrypt("text".getBytes())));
}
@Test
@ -62,8 +60,8 @@ public class EncryptorsTests {
@Test
public void queryableText() {
TextEncryptor encryptor = Encryptors
.queryableText("password", "5c0744940b5c369b");
TextEncryptor encryptor = Encryptors.queryableText("password",
"5c0744940b5c369b");
String result = encryptor.encrypt("text");
assertThat(result).isNotNull();
assertThat(result.equals("text")).isFalse();
@ -82,7 +80,8 @@ public class EncryptorsTests {
try {
Cipher.getInstance("AES/GCM/NoPadding");
return true;
} catch (GeneralSecurityException e) {
}
catch (GeneralSecurityException e) {
return false;
}
}

View File

@ -1,10 +1,6 @@
package org.springframework.security.crypto.password;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import java.security.MessageDigest;
import java.util.Arrays;
import org.junit.Test;
import org.springframework.security.crypto.codec.Hex;
@ -18,8 +14,7 @@ public class DigesterTests {
Digester digester = new Digester("SHA-1", 3);
byte[] result = digester.digest(Utf8.encode("text"));
// echo -n text | openssl sha1 -binary | openssl sha1 -binary | openssl sha1
assertEquals("3cfa28da425eca5b894f0af2b158adf7001e000f",
new String(Hex.encode(result)));
assertThat(new String(Hex.encode(result))).isEqualTo("3cfa28da425eca5b894f0af2b158adf7001e000f");
}
}

View File

@ -1,7 +1,6 @@
package org.springframework.security.crypto.password;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
@ -12,7 +11,7 @@ public class StandardPasswordEncoderTests {
@Test
public void matches() {
String result = encoder.encode("password");
assertThat(result.equals("password")).isFalse();
assertThat(result).isNotEqualTo("password");
assertThat(encoder.matches("password", result)).isTrue();
}

View File

@ -1,7 +1,7 @@
package org.springframework.security.crypto.util;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
@ -13,7 +13,7 @@ public class EncodingUtilsTests {
@Test
public void hexEncode() {
byte[] bytes = new byte[] { (byte) 0x01, (byte) 0xFF, (byte) 65, (byte) 66,
(byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 };
(byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 };
String result = new String(Hex.encode(bytes));
assertThat(result).isEqualTo("01ff414243c0c1c2");
}
@ -21,7 +21,7 @@ public class EncodingUtilsTests {
@Test
public void hexDecode() {
byte[] bytes = new byte[] { (byte) 0x01, (byte) 0xFF, (byte) 65, (byte) 66,
(byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 };
(byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 };
byte[] result = Hex.decode("01ff414243c0c1c2");
assertThat(Arrays.equals(bytes, result)).isTrue();
}
@ -29,17 +29,18 @@ public class EncodingUtilsTests {
@Test
public void concatenate() {
byte[] bytes = new byte[] { (byte) 0x01, (byte) 0xFF, (byte) 65, (byte) 66,
(byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 };
(byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 };
byte[] one = new byte[] { (byte) 0x01 };
byte[] two = new byte[] { (byte) 0xFF, (byte) 65, (byte) 66 };
byte[] three = new byte[] { (byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 };
assertThat(Arrays.equals(bytes, EncodingUtils.concatenate(one, two, three))).isTrue();
assertThat(Arrays.equals(bytes,
EncodingUtils.concatenate(one, two, three))).isTrue();
}
@Test
public void subArray() {
byte[] bytes = new byte[] { (byte) 0x01, (byte) 0xFF, (byte) 65, (byte) 66,
(byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 };
(byte) 67, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2 };
byte[] two = new byte[] { (byte) 0xFF, (byte) 65, (byte) 66 };
byte[] subArray = EncodingUtils.subArray(bytes, 1, 4);
assertThat(subArray.length).isEqualTo(3);

View File

@ -1,6 +1,7 @@
package org.springframework.security.performance;
import static junit.framework.Assert.fail;
import static org.assertj.core.api.Assertions.fail;
import org.junit.Before;
import org.junit.Test;
@ -21,6 +22,7 @@ import org.springframework.util.StopWatch;
@ContextConfiguration(locations = { "/protect-pointcut-performance-app-context.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class ProtectPointcutPerformanceTests implements ApplicationContextAware {
ApplicationContext ctx;
@Before
@ -35,8 +37,8 @@ public class ProtectPointcutPerformanceTests implements ApplicationContextAware
sw.start();
for (int i = 0; i < 1000; i++) {
try {
SessionRegistry reg = (SessionRegistry) ctx
.getBean("sessionRegistryPrototype");
SessionRegistry reg = (SessionRegistry) ctx.getBean(
"sessionRegistryPrototype");
reg.getAllPrincipals();
fail("Expected AuthenticationCredentialsNotFoundException");
}

View File

@ -39,8 +39,8 @@ public class DefaultSpringSecurityContextSourceTests extends AbstractLdapIntegra
ctxSrc.setUserDn("manager");
ctxSrc.setPassword("password");
ctxSrc.afterPropertiesSet();
assertThat(ctxSrc.getAuthenticatedEnvForTest("manager", "password").isTrue().containsKey(
AbstractContextSource.SUN_LDAP_POOLING_FLAG));
assertThat(ctxSrc.getAuthenticatedEnvForTest("manager", "password")).containsKey(
AbstractContextSource.SUN_LDAP_POOLING_FLAG);
}
@Test
@ -51,8 +51,8 @@ public class DefaultSpringSecurityContextSourceTests extends AbstractLdapIntegra
ctxSrc.setUserDn("manager");
ctxSrc.setPassword("password");
ctxSrc.afterPropertiesSet();
assertThat(ctxSrc.getAuthenticatedEnvForTest("user", "password").isFalse().containsKey(
AbstractContextSource.SUN_LDAP_POOLING_FLAG));
assertThat(ctxSrc.getAuthenticatedEnvForTest("user", "password")).doesNotContainKey(
AbstractContextSource.SUN_LDAP_POOLING_FLAG);
}
// SEC-1145. Confirms that there is no issue here with pooling.

View File

@ -56,14 +56,14 @@ public class SpringSecurityLdapTemplateITests extends AbstractLdapIntegrationTes
@Test
public void compareOfCorrectByteValueSucceeds() {
assertTrue(template.compare("uid=bob,ou=people", "userPassword",
Utf8.encode("bobspassword")));
assertThat(template.compare("uid=bob,ou=people", "userPassword",
Utf8.encode("bobspassword"))).isTrue();
}
@Test
public void compareOfWrongByteValueFails() {
assertFalse(template.compare("uid=bob,ou=people", "userPassword",
Utf8.encode("wrongvalue")));
assertThat(template.compare("uid=bob,ou=people", "userPassword",
Utf8.encode("wrongvalue"))).isFalse();
}
@Test

View File

@ -59,14 +59,13 @@ public class PasswordComparisonAuthenticatorTests extends AbstractLdapIntegratio
public void testAllAttributesAreRetrievedByDefault() {
DirContextAdapter user = (DirContextAdapter) authenticator.authenticate(bob);
// System.out.println(user.getAttributes().toString());
assertThat(user.getAttributes()).as("User should have 5 attributes").hasSize(5);
assertThat(user.getAttributes().size()).withFailMessage("User should have 5 attributes").isEqualTo(5);
}
@Test
public void testFailedSearchGivesUserNotFoundException() throws Exception {
authenticator = new PasswordComparisonAuthenticator(getContextSource());
assertTrue("User DN matches shouldn't be available",
authenticator.getUserDns("Bob").isEmpty());
assertThat(authenticator.getUserDns("Bob")).withFailMessage("User DN matches shouldn't be available").isEmpty();
authenticator.setUserSearch(new MockUserSearch(null));
authenticator.afterPropertiesSet();
@ -99,8 +98,8 @@ public class PasswordComparisonAuthenticatorTests extends AbstractLdapIntegratio
authenticator.setUserAttributes(new String[] { "uid", "userPassword" });
DirContextAdapter user = (DirContextAdapter) authenticator.authenticate(bob);
assertThat(userPassword).isEqualTo("Should have retrieved 2 attribute (uid)", 2, user
.getAttributes().size());
assertThat(user
.getAttributes().size()).withFailMessage("Should have retrieved 2 attribute (uid)").isEqualTo(2);
}
@Test
@ -141,8 +140,7 @@ public class PasswordComparisonAuthenticatorTests extends AbstractLdapIntegratio
public void testWithUserSearch() {
authenticator = new PasswordComparisonAuthenticator(getContextSource());
authenticator.setPasswordEncoder(new PlaintextPasswordEncoder());
assertTrue("User DN matches shouldn't be available",
authenticator.getUserDns("Bob").isEmpty());
assertThat(authenticator.getUserDns("Bob")).withFailMessage("User DN matches shouldn't be available").isEmpty();
DirContextAdapter ctx = new DirContextAdapter(new DistinguishedName(
"uid=Bob,ou=people"));

View File

@ -13,9 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.ldap.server;
import static junit.framework.Assert.fail;
import static org.assertj.core.api.Assertions.fail;
import java.io.IOException;
import java.net.ServerSocket;

View File

@ -12,16 +12,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.ldap.userdetails;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.fail;
import java.util.List;
import org.junit.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@ -32,19 +33,17 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.ldap.AbstractLdapIntegrationTests;
import org.springframework.security.ldap.DefaultLdapUsernameToDnMapper;
import org.springframework.security.ldap.SpringSecurityLdapTemplate;
import org.springframework.security.ldap.userdetails.InetOrgPerson;
import org.springframework.security.ldap.userdetails.InetOrgPersonContextMapper;
import org.springframework.security.ldap.userdetails.LdapUserDetails;
import org.springframework.security.ldap.userdetails.LdapUserDetailsManager;
import org.springframework.security.ldap.userdetails.PersonContextMapper;
/**
* @author Luke Taylor
*/
public class LdapUserDetailsManagerTests extends AbstractLdapIntegrationTests {
private static final List<GrantedAuthority> TEST_AUTHORITIES = AuthorityUtils
.createAuthorityList("ROLE_CLOWNS", "ROLE_ACROBATS");
private static final List<GrantedAuthority> TEST_AUTHORITIES = AuthorityUtils.createAuthorityList(
"ROLE_CLOWNS", "ROLE_ACROBATS");
private LdapUserDetailsManager mgr;
private SpringSecurityLdapTemplate template;
@Before
@ -173,8 +172,9 @@ public class LdapUserDetailsManagerTests extends AbstractLdapIntegrationTests {
}
// Check that no authorities are left
assertThat("don").isEqualTo(0, mgr.getUserAuthorities(mgr.usernameMapper.buildDn("don"))
.size());
assertThat(
mgr.getUserAuthorities(mgr.usernameMapper.buildDn("don"), "don")).hasSize(
0);
}
@Test
@ -195,8 +195,8 @@ public class LdapUserDetailsManagerTests extends AbstractLdapIntegrationTests {
mgr.changePassword("yossarianspassword", "yossariansnewpassword");
assertTrue(template.compare("uid=johnyossarian,ou=test people", "userPassword",
"yossariansnewpassword"));
assertThat(template.compare("uid=johnyossarian,ou=test people", "userPassword",
"yossariansnewpassword")).isTrue();
}
@Test(expected = BadCredentialsException.class)

View File

@ -72,8 +72,8 @@ public class NestedLdapAuthoritiesPopulatorTests extends AbstractLdapIntegration
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx,
"scaladude");
assertThat(authorities).hasSize(5);
assertEquals(Arrays.asList(javaDevelopers, scalaDevelopers,
circularJavaDevelopers, jDevelopers, groovyDevelopers), authorities);
assertThat(Arrays.asList(javaDevelopers, scalaDevelopers,
circularJavaDevelopers, jDevelopers, groovyDevelopers)).isEqualTo(authorities);
}
@Test
@ -83,8 +83,7 @@ public class NestedLdapAuthoritiesPopulatorTests extends AbstractLdapIntegration
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx,
"javadude");
assertThat(authorities).hasSize(3);
assertThat(circularJavaDevelopers).isCloseTo(Arrays.asList(javaDevelopers, within(jDevelopers)),
authorities);
assertThat(authorities).contains(javaDevelopers);
}
@Test
@ -105,8 +104,8 @@ public class NestedLdapAuthoritiesPopulatorTests extends AbstractLdapIntegration
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx,
"groovydude");
assertThat(authorities).hasSize(4);
assertEquals(Arrays.asList(javaDevelopers, circularJavaDevelopers, jDevelopers,
groovyDevelopers), authorities);
assertThat(authorities).isEqualTo(Arrays.asList(javaDevelopers, circularJavaDevelopers, jDevelopers,
groovyDevelopers));
}
@Test
@ -118,8 +117,8 @@ public class NestedLdapAuthoritiesPopulatorTests extends AbstractLdapIntegration
Collection<GrantedAuthority> authorities = populator.getGrantedAuthorities(ctx,
"closuredude");
assertThat(authorities).hasSize(5);
assertEquals(Arrays.asList(closureDevelopers, javaDevelopers,
circularJavaDevelopers, jDevelopers, groovyDevelopers), authorities);
assertThat(authorities).isEqualTo(Arrays.asList(closureDevelopers, javaDevelopers,
circularJavaDevelopers, jDevelopers, groovyDevelopers));
LdapAuthority[] ldapAuthorities = authorities.toArray(new LdapAuthority[0]);
assertThat(ldapAuthorities.length).isEqualTo(5);
@ -127,17 +126,14 @@ public class NestedLdapAuthoritiesPopulatorTests extends AbstractLdapIntegration
assertThat(ldapAuthorities[0].getAttributes().containsKey("member")).isTrue();
assertThat(ldapAuthorities[0].getAttributes().get("member")).isNotNull();
assertThat(ldapAuthorities[0].getAttributes().get("member")).hasSize(1);
assertEquals("uid=closuredude,ou=people,dc=springframework,dc=org",
ldapAuthorities[0].getFirstAttributeValue("member"));
assertThat(ldapAuthorities[0].getFirstAttributeValue("member")).isEqualTo("uid=closuredude,ou=people,dc=springframework,dc=org");
// java group
assertThat(ldapAuthorities[1].getAttributes().containsKey("member")).isTrue();
assertThat(ldapAuthorities[1].getAttributes().get("member")).isNotNull();
assertThat(ldapAuthorities[1].getAttributes().get("member")).hasSize(3);
assertEquals(groovyDevelopers.getDn(),
ldapAuthorities[1].getFirstAttributeValue("member"));
assertThat(scalaDevelopers.getDn().isEqualTo(new String[] { groovyDevelopers.getDn()),
"uid=javadude,ou=people,dc=springframework,dc=org" }, ldapAuthorities[1]
assertThat(groovyDevelopers.getDn()).isEqualTo(ldapAuthorities[1].getFirstAttributeValue("member"));
assertThat(scalaDevelopers.getDn()).isEqualTo(ldapAuthorities[2]
.getAttributes().get("member"));
// test non existent attribute

View File

@ -48,7 +48,7 @@ public class LdapUtilsTests {
when(mockCtx.getNameInNamespace()).thenReturn("dc=springframework,dc=org");
assertThat(dc=org").as("").isCloseTo(LdapUtils.getRelativeName("dc=springframework, within(mockCtx)));
assertThat(LdapUtils.getRelativeName("dc=springframework,dc=org",mockCtx)).isEqualTo("");
}
@Test
@ -56,8 +56,7 @@ public class LdapUtilsTests {
final DirContext mockCtx = mock(DirContext.class);
when(mockCtx.getNameInNamespace()).thenReturn("");
assertEquals("cn=jane,dc=springframework,dc=org",
LdapUtils.getRelativeName("cn=jane,dc=springframework,dc=org", mockCtx));
assertThat(LdapUtils.getRelativeName("cn=jane,dc=springframework,dc=org", mockCtx)).isEqualTo("cn=jane,dc=springframework,dc=org");
}
@Test
@ -65,8 +64,8 @@ public class LdapUtilsTests {
final DirContext mockCtx = mock(DirContext.class);
when(mockCtx.getNameInNamespace()).thenReturn("dc=springsecurity,dc = org");
assertEquals("cn=jane smith", LdapUtils.getRelativeName(
"cn=jane smith, dc = springsecurity , dc=org", mockCtx));
assertThat(LdapUtils.getRelativeName(
"cn=jane smith, dc = springsecurity , dc=org", mockCtx)).isEqualTo("cn=jane smith");
}
@Test
@ -75,23 +74,19 @@ public class LdapUtilsTests {
assertThat(LdapUtils.parseRootDnFromUrl("ldap://monkeymachine:11389")).isEqualTo("");
assertThat(LdapUtils.parseRootDnFromUrl("ldap://monkeymachine/")).isEqualTo("");
assertThat(LdapUtils.parseRootDnFromUrl("ldap://monkeymachine.co.uk/")).isEqualTo("");
assertEquals(
"dc=springframework,dc=org",
assertThat(
LdapUtils
.parseRootDnFromUrl("ldaps://monkeymachine.co.uk/dc=springframework,dc=org"));
assertEquals("dc=springframework,dc=org",
LdapUtils.parseRootDnFromUrl("ldap:///dc=springframework,dc=org"));
assertEquals(
"dc=springframework,dc=org",
.parseRootDnFromUrl("ldaps://monkeymachine.co.uk/dc=springframework,dc=org")).isEqualTo("dc=springframework,dc=org");
assertThat(
LdapUtils.parseRootDnFromUrl("ldap:///dc=springframework,dc=org")).isEqualTo("dc=springframework,dc=org");
assertThat(
LdapUtils
.parseRootDnFromUrl("ldap://monkeymachine/dc=springframework,dc=org"));
assertEquals(
"dc=springframework,dc=org/ou=blah",
.parseRootDnFromUrl("ldap://monkeymachine/dc=springframework,dc=org")).isEqualTo("dc=springframework,dc=org");
assertThat(
LdapUtils
.parseRootDnFromUrl("ldap://monkeymachine.co.uk/dc=springframework,dc=org/ou=blah"));
assertEquals(
"dc=springframework,dc=org/ou=blah",
.parseRootDnFromUrl("ldap://monkeymachine.co.uk/dc=springframework,dc=org/ou=blah")).isEqualTo("dc=springframework,dc=org/ou=blah");
assertThat(
LdapUtils
.parseRootDnFromUrl("ldap://monkeymachine.co.uk:389/dc=springframework,dc=org/ou=blah"));
.parseRootDnFromUrl("ldap://monkeymachine.co.uk:389/dc=springframework,dc=org/ou=blah")).isEqualTo("dc=springframework,dc=org/ou=blah");
}
}

View File

@ -136,9 +136,9 @@ public class LdapAuthenticationProviderTests {
assertThat(user.getUsername()).isEqualTo("ben");
assertThat(populator.getRequestedUsername()).isEqualTo("ben");
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains(
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ROLE_FROM_ENTRY"));
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains(
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ROLE_FROM_POPULATOR"));
}
@ -167,7 +167,7 @@ public class LdapAuthenticationProviderTests {
UserDetails user = (UserDetails) ldapProvider.authenticate(authRequest)
.getPrincipal();
assertThat(user.getAuthorities()).hasSize(1);
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains(
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ROLE_FROM_ENTRY"));
}

View File

@ -42,16 +42,16 @@ public class LdapShaPasswordEncoderTests {
@Test
public void invalidPasswordFails() {
assertFalse(sha.isPasswordValid("{SHA}ddSFGmjXYPbZC+NXR2kCzBRjqiE=",
"wrongpassword", null));
assertThat(sha.isPasswordValid("{SHA}ddSFGmjXYPbZC+NXR2kCzBRjqiE=",
"wrongpassword", null)).isFalse();
}
@Test
public void invalidSaltedPasswordFails() {
assertFalse(sha.isPasswordValid("{SSHA}25ro4PKC8jhQZ26jVsozhX/xaP0suHgX",
"wrongpassword", null));
assertFalse(sha.isPasswordValid("{SSHA}PQy2j+6n5ytA+YlAKkM8Fh4p6u2JxfVd",
"wrongpassword", null));
assertThat(sha.isPasswordValid("{SSHA}25ro4PKC8jhQZ26jVsozhX/xaP0suHgX",
"wrongpassword", null)).isFalse();
assertThat(sha.isPasswordValid("{SSHA}PQy2j+6n5ytA+YlAKkM8Fh4p6u2JxfVd",
"wrongpassword", null)).isFalse();
}
@Test(expected = IllegalArgumentException.class)
@ -65,15 +65,15 @@ public class LdapShaPasswordEncoderTests {
@Test
public void validPasswordSucceeds() {
sha.setForceLowerCasePrefix(false);
assertTrue(sha.isPasswordValid("{SHA}ddSFGmjXYPbZC+NXR2kCzBRjqiE=",
"boabspasswurd", null));
assertTrue(sha.isPasswordValid("{sha}ddSFGmjXYPbZC+NXR2kCzBRjqiE=",
"boabspasswurd", null));
assertThat(sha.isPasswordValid("{SHA}ddSFGmjXYPbZC+NXR2kCzBRjqiE=",
"boabspasswurd", null)).isTrue();
assertThat(sha.isPasswordValid("{sha}ddSFGmjXYPbZC+NXR2kCzBRjqiE=",
"boabspasswurd", null)).isTrue();
sha.setForceLowerCasePrefix(true);
assertTrue(sha.isPasswordValid("{SHA}ddSFGmjXYPbZC+NXR2kCzBRjqiE=",
"boabspasswurd", null));
assertTrue(sha.isPasswordValid("{sha}ddSFGmjXYPbZC+NXR2kCzBRjqiE=",
"boabspasswurd", null));
assertThat(sha.isPasswordValid("{SHA}ddSFGmjXYPbZC+NXR2kCzBRjqiE=",
"boabspasswurd", null)).isTrue();
assertThat(sha.isPasswordValid("{sha}ddSFGmjXYPbZC+NXR2kCzBRjqiE=",
"boabspasswurd", null)).isTrue();
}
/**
@ -82,40 +82,40 @@ public class LdapShaPasswordEncoderTests {
@Test
public void validSaltedPasswordSucceeds() {
sha.setForceLowerCasePrefix(false);
assertTrue(sha.isPasswordValid("{SSHA}25ro4PKC8jhQZ26jVsozhX/xaP0suHgX",
"boabspasswurd", null));
assertTrue(sha.isPasswordValid("{ssha}PQy2j+6n5ytA+YlAKkM8Fh4p6u2JxfVd",
"boabspasswurd", null));
assertThat(sha.isPasswordValid("{SSHA}25ro4PKC8jhQZ26jVsozhX/xaP0suHgX",
"boabspasswurd", null)).isTrue();
assertThat(sha.isPasswordValid("{ssha}PQy2j+6n5ytA+YlAKkM8Fh4p6u2JxfVd",
"boabspasswurd", null)).isTrue();
sha.setForceLowerCasePrefix(true);
assertTrue(sha.isPasswordValid("{SSHA}25ro4PKC8jhQZ26jVsozhX/xaP0suHgX",
"boabspasswurd", null));
assertTrue(sha.isPasswordValid("{ssha}PQy2j+6n5ytA+YlAKkM8Fh4p6u2JxfVd",
"boabspasswurd", null));
assertThat(sha.isPasswordValid("{SSHA}25ro4PKC8jhQZ26jVsozhX/xaP0suHgX",
"boabspasswurd", null)).isTrue();
assertThat(sha.isPasswordValid("{ssha}PQy2j+6n5ytA+YlAKkM8Fh4p6u2JxfVd",
"boabspasswurd", null)).isTrue();
}
@Test
// SEC-1031
public void fullLengthOfHashIsUsedInComparison() throws Exception {
// Change the first hash character from '2' to '3'
assertFalse(sha.isPasswordValid("{SSHA}35ro4PKC8jhQZ26jVsozhX/xaP0suHgX",
"boabspasswurd", null));
assertThat(sha.isPasswordValid("{SSHA}35ro4PKC8jhQZ26jVsozhX/xaP0suHgX",
"boabspasswurd", null)).isFalse();
// Change the last hash character from 'X' to 'Y'
assertFalse(sha.isPasswordValid("{SSHA}25ro4PKC8jhQZ26jVsozhX/xaP0suHgY",
"boabspasswurd", null));
assertThat(sha.isPasswordValid("{SSHA}25ro4PKC8jhQZ26jVsozhX/xaP0suHgY",
"boabspasswurd", null)).isFalse();
}
@Test
public void correctPrefixCaseIsUsed() {
sha.setForceLowerCasePrefix(false);
assertEquals("{SHA}ddSFGmjXYPbZC+NXR2kCzBRjqiE=",
assertThat("{SHA}ddSFGmjXYPbZC+NXR2kCzBRjqiE=").isEqualTo(
sha.encodePassword("boabspasswurd", null));
assertThat(sha.encodePassword("somepassword", "salt".getBytes()).isTrue().startsWith(
assertThat(sha.encodePassword("somepassword", "salt".getBytes()).startsWith(
"{SSHA}"));
sha.setForceLowerCasePrefix(true);
assertEquals("{sha}ddSFGmjXYPbZC+NXR2kCzBRjqiE=",
assertThat("{sha}ddSFGmjXYPbZC+NXR2kCzBRjqiE=").isEqualTo(
sha.encodePassword("boabspasswurd", null));
assertThat(sha.encodePassword("somepassword", "salt".getBytes()).isTrue().startsWith(
assertThat(sha.encodePassword("somepassword", "salt".getBytes()).startsWith(
"{ssha}"));
}

View File

@ -46,8 +46,6 @@ import javax.naming.directory.SearchResult;
import java.util.Hashtable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.*;
import static org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider.ContextFactory;
@ -327,7 +325,7 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
try {
provider.authenticate(joe);
fail();
fail("BadCredentialsException should had been thrown");
}
catch (BadCredentialsException expected) {
}

View File

@ -1,26 +1,17 @@
package org.springframework.security.ldap.ppolicy;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.ldap.authentication.BindAuthenticator;
import org.springframework.security.ldap.authentication.LdapAuthenticationProvider;
import org.springframework.security.ldap.userdetails.LdapUserDetailsImpl;
/**
* Test cases which run against an OpenLDAP server.
* <p>
* Run the script in the module root to start the server and import the data before
* running.
*
* @author Luke Taylor
* @since 3.0
*/
public class OpenLDAPIntegrationTestSuite {
PasswordPolicyAwareContextSource cs;
/*
* @Before public void createContextSource() throws Exception { cs = new

View File

@ -1,6 +1,6 @@
package org.springframework.security.ldap.ppolicy;
import static org.junit.Assert.assertNotNull;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.*;

View File

@ -32,7 +32,6 @@ public class PasswordPolicyControlFactoryTests {
PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL);
Control result = ctrlFactory.getControlInstance(control);
assertThat(result).isNotNull();
assertTrue(Arrays.equals(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL,
result.getEncodedValue()));
assertThat(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL).isEqualTo(result.getEncodedValue());
}
}

View File

@ -10,7 +10,6 @@ import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
/**
* @author Filip Hanik
@ -33,10 +32,8 @@ public class LdapAuthorityTests {
public void testGetDn() throws Exception {
assertThat(authority.getDn()).isEqualTo(DN);
assertThat(authority.getAttributeValues(SpringSecurityLdapTemplate.DN_KEY)).isNotNull();
assertThat(authority.getAttributeValues(SpringSecurityLdapTemplate.DN_KEY).isEqualTo(1)
.size());
assertEquals(DN,
authority.getFirstAttributeValue(SpringSecurityLdapTemplate.DN_KEY));
assertThat(authority.getAttributeValues(SpringSecurityLdapTemplate.DN_KEY)).hasSize(1);
assertThat(authority.getFirstAttributeValue(SpringSecurityLdapTemplate.DN_KEY)).isEqualTo(DN);
}
@Test

View File

@ -15,11 +15,12 @@
package org.springframework.security.ldap.userdetails;
import static org.assertj.core.api.Assertions.assertThat;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DistinguishedName;
import org.springframework.security.core.authority.AuthorityUtils;
@ -29,8 +30,9 @@ import org.springframework.security.core.authority.AuthorityUtils;
*
* @author Luke Taylor
*/
public class LdapUserDetailsMapperTests extends TestCase {
public class LdapUserDetailsMapperTests {
@Test
public void testMultipleRoleAttributeValuesAreMappedToAuthorities() throws Exception {
LdapUserDetailsMapper mapper = new LdapUserDetailsMapper();
mapper.setConvertToUpperCase(false);
@ -52,6 +54,7 @@ public class LdapUserDetailsMapperTests extends TestCase {
/**
* SEC-303. Non-retrieved role attribute causes NullPointerException
*/
@Test
public void testNonRetrievedRoleAttributeIsIgnored() throws Exception {
LdapUserDetailsMapper mapper = new LdapUserDetailsMapper();
@ -60,18 +63,19 @@ public class LdapUserDetailsMapperTests extends TestCase {
BasicAttributes attrs = new BasicAttributes();
attrs.put(new BasicAttribute("userRole", "x"));
DirContextAdapter ctx = new DirContextAdapter(attrs, new DistinguishedName(
"cn=someName"));
DirContextAdapter ctx = new DirContextAdapter(attrs,
new DistinguishedName("cn=someName"));
ctx.setAttributeValue("uid", "ani");
LdapUserDetailsImpl user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx,
"ani", AuthorityUtils.NO_AUTHORITIES);
assertThat(user.getAuthorities()).hasSize(1);
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).isTrue().contains(
assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities()).contains(
"ROLE_X"));
}
@Test
public void testPasswordAttributeIsMappedCorrectly() throws Exception {
LdapUserDetailsMapper mapper = new LdapUserDetailsMapper();
@ -79,12 +83,12 @@ public class LdapUserDetailsMapperTests extends TestCase {
BasicAttributes attrs = new BasicAttributes();
attrs.put(new BasicAttribute("myappsPassword", "mypassword".getBytes()));
DirContextAdapter ctx = new DirContextAdapter(attrs, new DistinguishedName(
"cn=someName"));
DirContextAdapter ctx = new DirContextAdapter(attrs,
new DistinguishedName("cn=someName"));
ctx.setAttributeValue("uid", "ani");
LdapUserDetails user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx,
"ani", AuthorityUtils.NO_AUTHORITIES);
LdapUserDetails user = (LdapUserDetailsImpl) mapper.mapUserFromContext(ctx, "ani",
AuthorityUtils.NO_AUTHORITIES);
assertThat(user.getPassword()).isEqualTo("mypassword");
}

View File

@ -250,8 +250,8 @@ public class SecurityContextChannelInterceptorTests {
AnonymousAuthenticationToken anonymous = (AnonymousAuthenticationToken) currentAuthentication;
assertThat(anonymous.getName()).isEqualTo(expectedAnonymous.getName());
assertThat(anonymous.getAuthorities()).containsOnly(
expectedAnonymous.getAuthorities().toArray());
assertThat(anonymous.getAuthorities()).containsOnlyElementsOf(
expectedAnonymous.getAuthorities());
assertThat(anonymous.getKeyHash()).isEqualTo(expectedAnonymous.getKeyHash());
}
}

View File

@ -47,12 +47,10 @@ public class OpenID4JavaConsumerTests {
MockHttpServletRequest request = new MockHttpServletRequest();
consumer.beginConsumption(request, "", "", "");
assertEquals(
attributes,
request.getSession().getAttribute(
"SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST"));
assertSame(di,
request.getSession().getAttribute(DiscoveryInformation.class.getName()));
assertThat(request.getSession().getAttribute(
"SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST")).isEqualTo(attributes);
assertThat(
request.getSession().getAttribute(DiscoveryInformation.class.getName())).isEqualTo(di);
// Check with empty attribute fetch list
consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory());
@ -82,14 +80,14 @@ public class OpenID4JavaConsumerTests {
try {
consumer.beginConsumption(new MockHttpServletRequest(), "", "", "");
fail();
fail("OpenIDConsumerException was not thrown");
}
catch (OpenIDConsumerException expected) {
}
try {
consumer.beginConsumption(new MockHttpServletRequest(), "", "", "");
fail();
fail("OpenIDConsumerException was not thrown");
}
catch (OpenIDConsumerException expected) {
}
@ -134,21 +132,21 @@ public class OpenID4JavaConsumerTests {
try {
consumer.endConsumption(request);
fail();
fail("OpenIDConsumerException was not thrown");
}
catch (OpenIDConsumerException expected) {
}
try {
consumer.endConsumption(request);
fail();
fail("OpenIDConsumerException was not thrown");
}
catch (OpenIDConsumerException expected) {
}
try {
consumer.endConsumption(request);
fail();
fail("OpenIDConsumerException was not thrown");
}
catch (OpenIDConsumerException expected) {
}

View File

@ -88,8 +88,8 @@ public class OpenIDAuthenticationFilterTests {
URI returnTo = new URI(filter.buildReturnToUrl(req));
String query = returnTo.getRawQuery();
assertThat(count(query).isCloseTo(1, within('=')));
assertThat(count(query).isCloseTo(0, within('&')));
assertThat(count(query, '=')).isEqualTo(1);
assertThat(count(query, '&')).isEqualTo(0);
}
/**

View File

@ -12,10 +12,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.openid;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import org.junit.Test;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@ -33,7 +36,7 @@ import org.springframework.security.core.userdetails.UserDetailsService;
*
* @author Robin Bramley, Opsera Ltd
*/
public class OpenIDAuthenticationProviderTests extends TestCase {
public class OpenIDAuthenticationProviderTests {
// ~ Static fields/initializers
// =====================================================================================
@ -44,8 +47,10 @@ public class OpenIDAuthenticationProviderTests extends TestCase {
/*
* Test method for
* 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.authenticate(Authentication)'
* 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.
* authenticate(Authentication)'
*/
@Test
public void testAuthenticateCancel() {
OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider();
provider.setUserDetailsService(new MockUserDetailsService());
@ -67,8 +72,10 @@ public class OpenIDAuthenticationProviderTests extends TestCase {
/*
* Test method for
* 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.authenticate(Authentication)'
* 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.
* authenticate(Authentication)'
*/
@Test
public void testAuthenticateError() {
OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider();
provider.setUserDetailsService(new MockUserDetailsService());
@ -89,12 +96,15 @@ public class OpenIDAuthenticationProviderTests extends TestCase {
/*
* Test method for
* 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.authenticate(Authentication)'
* 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.
* authenticate(Authentication)'
*/
@Test
public void testAuthenticateFailure() {
OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider();
provider.setAuthenticationUserDetailsService(new UserDetailsByNameServiceWrapper<OpenIDAuthenticationToken>(
new MockUserDetailsService()));
provider.setAuthenticationUserDetailsService(
new UserDetailsByNameServiceWrapper<OpenIDAuthenticationToken>(
new MockUserDetailsService()));
Authentication preAuth = new OpenIDAuthenticationToken(
OpenIDAuthenticationStatus.FAILURE, USERNAME, "", null);
@ -106,15 +116,17 @@ public class OpenIDAuthenticationProviderTests extends TestCase {
fail("Should throw an AuthenticationException");
}
catch (BadCredentialsException expected) {
assertEquals("Log in failed - identity could not be verified",
assertThat("Log in failed - identity could not be verified").isEqualTo(
expected.getMessage());
}
}
/*
* Test method for
* 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.authenticate(Authentication)'
* 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.
* authenticate(Authentication)'
*/
@Test
public void testAuthenticateSetupNeeded() {
OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider();
provider.setUserDetailsService(new MockUserDetailsService());
@ -129,15 +141,18 @@ public class OpenIDAuthenticationProviderTests extends TestCase {
fail("Should throw an AuthenticationException");
}
catch (AuthenticationServiceException expected) {
assertEquals("The server responded setup was needed, which shouldn't happen",
expected.getMessage());
assertThat(
"The server responded setup was needed, which shouldn't happen").isEqualTo(
expected.getMessage());
}
}
/*
* Test method for
* 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.authenticate(Authentication)'
* 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.
* authenticate(Authentication)'
*/
@Test
public void testAuthenticateSuccess() {
OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider();
provider.setUserDetailsService(new MockUserDetailsService());
@ -156,10 +171,12 @@ public class OpenIDAuthenticationProviderTests extends TestCase {
assertThat(postAuth.getPrincipal() instanceof UserDetails).isTrue();
assertThat(postAuth.getAuthorities()).isNotNull();
assertThat(postAuth.getAuthorities().size() > 0).isTrue();
assertThat(((OpenIDAuthenticationToken) postAuth).getStatus() == OpenIDAuthenticationStatus.SUCCESS).isTrue();
assertThat(
((OpenIDAuthenticationToken) postAuth).getStatus() == OpenIDAuthenticationStatus.SUCCESS).isTrue();
assertThat(((OpenIDAuthenticationToken) postAuth).getMessage() == null).isTrue();
}
@Test
public void testDetectsMissingAuthoritiesPopulator() throws Exception {
OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider();
@ -174,19 +191,24 @@ public class OpenIDAuthenticationProviderTests extends TestCase {
/*
* Test method for
* 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.supports(Class)'
* 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.
* supports(Class)'
*/
@Test
public void testDoesntSupport() {
OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider();
provider.setUserDetailsService(new MockUserDetailsService());
assertThat(provider.supports(UsernamePasswordAuthenticationToken.class)).isFalse();
assertThat(
provider.supports(UsernamePasswordAuthenticationToken.class)).isFalse();
}
/*
* Test method for
* 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.authenticate(Authentication)'
* 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.
* authenticate(Authentication)'
*/
@Test
public void testIgnoresUserPassAuthToken() {
OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider();
provider.setUserDetailsService(new MockUserDetailsService());
@ -198,8 +220,10 @@ public class OpenIDAuthenticationProviderTests extends TestCase {
/*
* Test method for
* 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.supports(Class)'
* 'org.springframework.security.authentication.openid.OpenIDAuthenticationProvider.
* supports(Class)'
*/
@Test
public void testSupports() {
OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider();
provider.setUserDetailsService(new MockUserDetailsService());
@ -207,6 +231,7 @@ public class OpenIDAuthenticationProviderTests extends TestCase {
assertThat(provider.supports(OpenIDAuthenticationToken.class)).isTrue();
}
@Test
public void testValidation() throws Exception {
OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider();
try {
@ -223,6 +248,7 @@ public class OpenIDAuthenticationProviderTests extends TestCase {
}
static class MockUserDetailsService implements UserDetailsService {
public UserDetails loadUserByUsername(String ssoUserId)
throws AuthenticationException {
return new User(ssoUserId, "password", true, true, true, true,

View File

@ -15,40 +15,38 @@
package org.springframework.security.remoting.httpinvoker;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.junit.After;
import org.junit.Test;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.remoting.httpinvoker.AuthenticationSimpleHttpInvokerRequestExecutor;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* Tests {@link AuthenticationSimpleHttpInvokerRequestExecutor}.
*
* @author Ben Alex
* @author Rob Winch
*/
public class AuthenticationSimpleHttpInvokerRequestExecutorTests extends TestCase {
public class AuthenticationSimpleHttpInvokerRequestExecutorTests {
// ~ Methods
// ========================================================================================================
protected void tearDown() throws Exception {
super.tearDown();
@After
public void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
@Test
public void testNormalOperation() throws Exception {
// Setup client-side context
Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken(
@ -64,10 +62,11 @@ public class AuthenticationSimpleHttpInvokerRequestExecutorTests extends TestCas
// Check connection properties
// See http://www.faqs.org/rfcs/rfc1945.html section 11.1 for example
// we are comparing against
assertEquals("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
conn.getRequestProperty("Authorization"));
assertThat(conn.getRequestProperty("Authorization")).isEqualTo(
"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
}
@Test
public void testNullContextHolderIsNull() throws Exception {
SecurityContextHolder.getContext().setAuthentication(null);
@ -82,6 +81,7 @@ public class AuthenticationSimpleHttpInvokerRequestExecutorTests extends TestCas
}
// SEC-1975
@Test
public void testNullContextHolderWhenAnonymous() throws Exception {
AnonymousAuthenticationToken anonymous = new AnonymousAuthenticationToken("key",
"principal", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
@ -101,6 +101,7 @@ public class AuthenticationSimpleHttpInvokerRequestExecutorTests extends TestCas
// ==================================================================================================
private class MockHttpURLConnection extends HttpURLConnection {
private Map<String, String> requestProperties = new HashMap<String, String>();
public MockHttpURLConnection(URL u) {

View File

@ -15,8 +15,14 @@
package org.springframework.security.remoting.rmi;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.lang.reflect.Method;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.After;
import org.junit.Test;
import org.springframework.security.TargetObject;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
@ -24,21 +30,18 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.util.SimpleMethodInvocation;
import org.springframework.test.util.ReflectionTestUtils;
import java.lang.reflect.Method;
/**
* Tests {@link ContextPropagatingRemoteInvocation} and
* {@link ContextPropagatingRemoteInvocationFactory}.
*
* @author Ben Alex
*/
public class ContextPropagatingRemoteInvocationTests extends TestCase {
public class ContextPropagatingRemoteInvocationTests {
// ~ Methods
// ========================================================================================================
protected void tearDown() throws Exception {
super.tearDown();
@After
public void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
@ -53,6 +56,7 @@ public class ContextPropagatingRemoteInvocationTests extends TestCase {
return (ContextPropagatingRemoteInvocation) factory.createRemoteInvocation(mi);
}
@Test
public void testContextIsResetEvenIfExceptionOccurs() throws Exception {
// Setup client-side context
Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken(
@ -71,10 +75,12 @@ public class ContextPropagatingRemoteInvocationTests extends TestCase {
// expected
}
assertThat(SecurityContextHolder.getContext().as("Authentication must be null ").isNull()
.getAuthentication());
assertThat(
SecurityContextHolder.getContext().getAuthentication()).withFailMessage(
"Authentication must be null").isNull();
}
@Test
public void testNormalOperation() throws Exception {
// Setup client-side context
Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken(
@ -90,28 +96,31 @@ public class ContextPropagatingRemoteInvocationTests extends TestCase {
// The result from invoking the TargetObject should contain the
// Authentication class delivered via the SecurityContextHolder
assertEquals(
"some_string org.springframework.security.authentication.UsernamePasswordAuthenticationToken false",
remoteInvocation.invoke(new TargetObject()));
assertThat(remoteInvocation.invoke(new TargetObject())).isEqualTo(
"some_string org.springframework.security.authentication.UsernamePasswordAuthenticationToken false");
}
@Test
public void testNullContextHolderDoesNotCauseInvocationProblems() throws Exception {
SecurityContextHolder.clearContext(); // just to be explicit
ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation();
SecurityContextHolder.clearContext(); // unnecessary, but for explicitness
SecurityContextHolder.clearContext(); // unnecessary, but for
// explicitness
assertEquals("some_string Authentication empty",
remoteInvocation.invoke(new TargetObject()));
assertThat(remoteInvocation.invoke(new TargetObject())).isEqualTo(
"some_string Authentication empty");
}
// SEC-1867
@Test
public void testNullCredentials() throws Exception {
Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken(
"rod", null);
SecurityContextHolder.getContext().setAuthentication(clientSideAuthentication);
ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation();
assertThat("credentials")).isEqualTo(null, ReflectionTestUtils.getField(remoteInvocation);
assertThat(
ReflectionTestUtils.getField(remoteInvocation, "credentials")).isNull();
}
}

View File

@ -40,8 +40,8 @@ public class DmsIntegrationTests extends AbstractTransactionalJUnit4SpringContex
@Test
public void testBasePopulation() {
assertThat(Integer.class)).isEqualTo(9, (int) jdbcTemplate.queryForObject("select count(id) from DIRECTORY");
assertThat(Integer.class)).isEqualTo(90, (int) jdbcTemplate.queryForObject("select count(id) from FILE");
assertThat(jdbcTemplate.queryForObject("select count(id) from DIRECTORY", Integer.class)).isEqualTo(9);
assertThat((int) jdbcTemplate.queryForObject("select count(id) from FILE", Integer.class)).isEqualTo(90);
assertThat(documentDao.findElements(Directory.ROOT_DIRECTORY).length).isEqualTo(3);
}
@ -104,8 +104,7 @@ public class DmsIntegrationTests extends AbstractTransactionalJUnit4SpringContex
}
if (shouldBeFiltered) {
assertNull("Found confidential directory when we should not have",
nonHomeConfidentialDir);
assertThat(nonHomeConfidentialDir).withFailMessage("Found confidential directory when we should not have").isNull();
}
else {
System.out.println("Inaccessible dir....: "

View File

@ -1,4 +1,4 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
@ -14,24 +14,16 @@ import org.springframework.test.context.ContextConfiguration;
public class SecureDmsIntegrationTests extends DmsIntegrationTests {
@Test
public void testBasePopulation() {
assertEquals(9,
(int) jdbcTemplate.queryForObject("select count(id) from DIRECTORY", Integer.class));
assertEquals(90,
(int) jdbcTemplate.queryForObject("select count(id) from FILE", Integer.class));
assertEquals(4,
(int) jdbcTemplate.queryForObject("select count(id) from ACL_SID", Integer.class)); // 3
// users
// + 1
// role
assertEquals(2,
(int) jdbcTemplate.queryForObject("select count(id) from ACL_CLASS", Integer.class)); // Directory
// and
// File
assertEquals(100,
(int) jdbcTemplate.queryForObject("select count(id) from ACL_OBJECT_IDENTITY", Integer.class));
assertEquals(115,
(int) jdbcTemplate.queryForObject("select count(id) from ACL_ENTRY", Integer.class));
public void testBasePopulation() {
assertThat(jdbcTemplate.queryForObject("select count(id) from DIRECTORY", Integer.class)).isEqualTo(9);
assertThat(jdbcTemplate.queryForObject("select count(id) from FILE", Integer.class)).isEqualTo(90);
assertThat(jdbcTemplate.queryForObject("select count(id) from ACL_SID", Integer.class)).isEqualTo(4); // 3 users + 1 role
assertThat(jdbcTemplate.queryForObject("select count(id) from ACL_CLASS", Integer.class)).isEqualTo(2); // Directory
// and
// File
assertThat(jdbcTemplate.queryForObject("select count(id) from ACL_OBJECT_IDENTITY", Integer.class))
.isEqualTo(100);
assertThat(jdbcTemplate.queryForObject("select count(id) from ACL_ENTRY", Integer.class)).isEqualTo(115);
}
public void testMarissaRetrieval() {

View File

@ -44,8 +44,7 @@ public class AbstractCsrfTagTests {
int returned = this.tag.doEndTag();
assertThat(returned).as("The returned value is not correct.").isEqualTo(TagSupport.EVAL_PAGE);
assertEquals("The output value is not correct.", "",
this.response.getContentAsString());
assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.").isEqualTo("");
}
@Test
@ -61,8 +60,7 @@ public class AbstractCsrfTagTests {
int returned = this.tag.doEndTag();
assertThat(returned).as("The returned value is not correct.").isEqualTo(TagSupport.EVAL_PAGE);
assertEquals("The output value is not correct.", "fooBarBazQux",
this.response.getContentAsString());
assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.").isEqualTo("fooBarBazQux");
assertThat(this.tag.token).as("The token is not correct.").isSameAs(token);
}
@ -79,8 +77,7 @@ public class AbstractCsrfTagTests {
int returned = this.tag.doEndTag();
assertThat(returned).as("The returned value is not correct.").isEqualTo(TagSupport.EVAL_PAGE);
assertEquals("The output value is not correct.", "<input type=\"hidden\" />",
this.response.getContentAsString());
assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.").isEqualTo("<input type=\"hidden\" />");
assertThat(this.tag.token).as("The token is not correct.").isSameAs(token);
}

View File

@ -27,9 +27,8 @@ public class CsrfInputTagTests {
String value = this.tag.handleToken(token);
assertThat(value).as("The returned value should not be null.").isNotNull();
assertEquals("The output is not correct.",
"<input type=\"hidden\" name=\"_csrf\" value=\"abc123def456ghi789\" />",
value);
assertThat(
value).withFailMessage("The output is not correct.").isEqualTo("<input type=\"hidden\" name=\"_csrf\" value=\"abc123def456ghi789\" />");
}
@Test
@ -40,9 +39,6 @@ public class CsrfInputTagTests {
String value = this.tag.handleToken(token);
assertThat(value).as("The returned value should not be null.").isNotNull();
assertEquals(
"The output is not correct.",
"<input type=\"hidden\" name=\"csrfParameter\" value=\"fooBarBazQux\" />",
value);
assertThat(value).withFailMessage("The output is not correct.").isEqualTo("<input type=\"hidden\" name=\"csrfParameter\" value=\"fooBarBazQux\" />");
}
}

View File

@ -27,10 +27,9 @@ public class CsrfMetaTagsTagTests {
String value = this.tag.handleToken(token);
assertThat(value).as("The returned value should not be null.").isNotNull();
assertEquals("The output is not correct.",
"<meta name=\"_csrf_parameter\" content=\"_csrf\" />"
+ "<meta name=\"_csrf_header\" content=\"X-Csrf-Token\" />"
+ "<meta name=\"_csrf\" content=\"abc123def456ghi789\" />", value);
assertThat(value).withFailMessage("The output is not correct.").isEqualTo("<meta name=\"_csrf_parameter\" content=\"_csrf\" />"
+ "<meta name=\"_csrf_header\" content=\"X-Csrf-Token\" />"
+ "<meta name=\"_csrf\" content=\"abc123def456ghi789\" />");
}
@Test
@ -41,9 +40,8 @@ public class CsrfMetaTagsTagTests {
String value = this.tag.handleToken(token);
assertThat(value).as("The returned value should not be null.").isNotNull();
assertEquals("The output is not correct.",
"<meta name=\"_csrf_parameter\" content=\"csrfParameter\" />"
+ "<meta name=\"_csrf_header\" content=\"csrfHeader\" />"
+ "<meta name=\"_csrf\" content=\"fooBarBazQux\" />", value);
assertThat(value).withFailMessage("The output is not correct.").isEqualTo("<meta name=\"_csrf_parameter\" content=\"csrfParameter\" />"
+ "<meta name=\"_csrf_header\" content=\"csrfHeader\" />"
+ "<meta name=\"_csrf\" content=\"fooBarBazQux\" />");
}
}

View File

@ -74,7 +74,7 @@ public class WithMockUserSecurityContextFactoryTests {
assertThat(
factory.createSecurityContext(withUser).getAuthentication()
.getAuthorities()).onProperty("authority").containsOnly(
.getAuthorities()).extracting("authority").containsOnly(
"ROLE_USER", "ROLE_CUSTOM");
}
@ -87,7 +87,7 @@ public class WithMockUserSecurityContextFactoryTests {
assertThat(
factory.createSecurityContext(withUser).getAuthentication()
.getAuthorities()).onProperty("authority").containsOnly(
.getAuthorities()).extracting("authority").containsOnly(
"USER", "CUSTOM");
}

View File

@ -83,7 +83,7 @@ public class SecurityMockMvcRequestPostProcessorsUserTests {
UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getName()).isEqualTo(username);
assertThat(context.getAuthentication().getCredentials()).isEqualTo("password");
assertThat(context.getAuthentication().getAuthorities()).onProperty("authority")
assertThat(context.getAuthentication().getAuthorities()).extracting("authority")
.containsOnly("ROLE_USER");
}
@ -101,7 +101,7 @@ public class SecurityMockMvcRequestPostProcessorsUserTests {
UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getName()).isEqualTo(username);
assertThat(context.getAuthentication().getCredentials()).isEqualTo("newpass");
assertThat(context.getAuthentication().getAuthorities()).onProperty("authority")
assertThat(context.getAuthentication().getAuthorities()).extracting("authority")
.containsOnly("ROLE_CUSTOM", "ROLE_ADMIN");
}

View File

@ -16,34 +16,36 @@
package org.springframework.security.web;
import static org.assertj.core.api.Assertions.assertThat;
import junit.framework.TestCase;
import static org.assertj.core.api.Assertions.fail;
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.web.PortMapperImpl;
import org.junit.Test;
/**
* Tests {@link PortMapperImpl}.
*
* @author Ben Alex
*/
public class PortMapperImplTests extends TestCase {
public class PortMapperImplTests {
// ~ Methods
// ========================================================================================================
@Test
public void testDefaultMappingsAreKnown() throws Exception {
PortMapperImpl portMapper = new PortMapperImpl();
assertThat(portMapper.lookupHttpPort(Integer.valueOf(443))).isEqualTo(Integer.valueOf(80));
assertEquals(Integer.valueOf(8080),
assertThat(portMapper.lookupHttpPort(Integer.valueOf(443))).isEqualTo(
Integer.valueOf(80));
assertThat(Integer.valueOf(8080)).isEqualTo(
portMapper.lookupHttpPort(Integer.valueOf(8443)));
assertEquals(Integer.valueOf(443),
assertThat(Integer.valueOf(443)).isEqualTo(
portMapper.lookupHttpsPort(Integer.valueOf(80)));
assertEquals(Integer.valueOf(8443),
assertThat(Integer.valueOf(8443)).isEqualTo(
portMapper.lookupHttpsPort(Integer.valueOf(8080)));
}
@Test
public void testDetectsEmptyMap() throws Exception {
PortMapperImpl portMapper = new PortMapperImpl();
@ -56,6 +58,7 @@ public class PortMapperImplTests extends TestCase {
}
}
@Test
public void testDetectsNullMap() throws Exception {
PortMapperImpl portMapper = new PortMapperImpl();
@ -68,11 +71,13 @@ public class PortMapperImplTests extends TestCase {
}
}
@Test
public void testGetTranslatedPortMappings() {
PortMapperImpl portMapper = new PortMapperImpl();
assertThat(portMapper.getTranslatedPortMappings()).hasSize(2);
}
@Test
public void testRejectsOutOfRangeMappings() {
PortMapperImpl portMapper = new PortMapperImpl();
Map<String, String> map = new HashMap<String, String>();
@ -87,11 +92,13 @@ public class PortMapperImplTests extends TestCase {
}
}
@Test
public void testReturnsNullIfHttpPortCannotBeFound() {
PortMapperImpl portMapper = new PortMapperImpl();
assertThat(portMapper.lookupHttpPort(Integer.valueOf("34343")) == null).isTrue();
}
@Test
public void testSupportsCustomMappings() {
PortMapperImpl portMapper = new PortMapperImpl();
Map<String, String> map = new HashMap<String, String>();
@ -99,8 +106,9 @@ public class PortMapperImplTests extends TestCase {
portMapper.setPortMappings(map);
assertThat(portMapper.lookupHttpPort(Integer.valueOf(442))).isEqualTo(Integer.valueOf(79));
assertEquals(Integer.valueOf(442),
assertThat(portMapper.lookupHttpPort(Integer.valueOf(442))).isEqualTo(
Integer.valueOf(79));
assertThat(Integer.valueOf(442)).isEqualTo(
portMapper.lookupHttpsPort(Integer.valueOf(79)));
}
}

View File

@ -16,19 +16,17 @@
package org.springframework.security.web;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.web.PortMapperImpl;
import org.springframework.security.web.PortResolverImpl;
/**
* Tests {@link PortResolverImpl}.
*
* @author Ben Alex
*/
public class PortResolverImplTests extends TestCase {
public class PortResolverImplTests {
// ~ Constructors
// ===================================================================================================
@ -36,17 +34,9 @@ public class PortResolverImplTests extends TestCase {
super();
}
public PortResolverImplTests(String arg0) {
super(arg0);
}
// ~ Methods
// ========================================================================================================
public final void setUp() throws Exception {
super.setUp();
}
@Test
public void testDetectsBuggyIeHttpRequest() throws Exception {
PortResolverImpl pr = new PortResolverImpl();
@ -56,6 +46,7 @@ public class PortResolverImplTests extends TestCase {
assertThat(pr.getServerPort(request)).isEqualTo(8080);
}
@Test
public void testDetectsBuggyIeHttpsRequest() throws Exception {
PortResolverImpl pr = new PortResolverImpl();
@ -65,6 +56,7 @@ public class PortResolverImplTests extends TestCase {
assertThat(pr.getServerPort(request)).isEqualTo(8443);
}
@Test
public void testDetectsEmptyPortMapper() throws Exception {
PortResolverImpl pr = new PortResolverImpl();
@ -77,6 +69,7 @@ public class PortResolverImplTests extends TestCase {
}
}
@Test
public void testGettersSetters() throws Exception {
PortResolverImpl pr = new PortResolverImpl();
assertThat(pr.getPortMapper() != null).isTrue();
@ -84,6 +77,7 @@ public class PortResolverImplTests extends TestCase {
assertThat(pr.getPortMapper() != null).isTrue();
}
@Test
public void testNormalOperation() throws Exception {
PortResolverImpl pr = new PortResolverImpl();

View File

@ -16,6 +16,7 @@
package org.springframework.security.web.access.channel;
import static org.mockito.Mockito.mock;
import static org.assertj.core.api.Assertions.*;
import java.io.IOException;
import java.util.Collection;
@ -26,8 +27,7 @@ import java.util.Vector;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.access.ConfigAttribute;
@ -42,10 +42,10 @@ import org.springframework.security.web.access.channel.ChannelProcessor;
* @author Ben Alex
*/
@SuppressWarnings("unchecked")
public class ChannelDecisionManagerImplTests extends TestCase {
public class ChannelDecisionManagerImplTests {
// ~ Methods
// ========================================================================================================
@Test
public void testCannotSetEmptyChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
@ -58,7 +58,8 @@ public class ChannelDecisionManagerImplTests extends TestCase {
assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required");
}
}
@Test
public void testCannotSetIncorrectObjectTypesIntoChannelProcessorsList()
throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
@ -73,7 +74,8 @@ public class ChannelDecisionManagerImplTests extends TestCase {
}
}
@Test
public void testCannotSetNullChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
@ -86,7 +88,8 @@ public class ChannelDecisionManagerImplTests extends TestCase {
assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required");
}
}
@Test
public void testDecideIsOperational() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
@ -107,7 +110,8 @@ public class ChannelDecisionManagerImplTests extends TestCase {
cdm.decide(fi, cad);
assertThat(fi.getResponse().isCommitted()).isTrue();
}
@Test
public void testAnyChannelAttributeCausesProcessorsToBeSkipped() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", true);
@ -124,7 +128,8 @@ public class ChannelDecisionManagerImplTests extends TestCase {
cdm.decide(fi, SecurityConfig.createList(new String[] { "abc", "ANY_CHANNEL" }));
assertThat(fi.getResponse().isCommitted()).isFalse();
}
@Test
public void testDecideIteratesAllProcessorsIfNoneCommitAResponse() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
@ -143,7 +148,8 @@ public class ChannelDecisionManagerImplTests extends TestCase {
cdm.decide(fi, SecurityConfig.createList("SOME_ATTRIBUTE_NO_PROCESSORS_SUPPORT"));
assertThat(fi.getResponse().isCommitted()).isFalse();
}
@Test
public void testDelegatesSupports() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
@ -158,7 +164,8 @@ public class ChannelDecisionManagerImplTests extends TestCase {
assertThat(cdm.supports(new SecurityConfig("abc"))).isTrue();
assertThat(cdm.supports(new SecurityConfig("UNSUPPORTED"))).isFalse();
}
@Test
public void testGettersSetters() {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
assertThat(cdm.getChannelProcessors()).isNull();
@ -172,7 +179,8 @@ public class ChannelDecisionManagerImplTests extends TestCase {
assertThat(cdm.getChannelProcessors()).isEqualTo(list);
}
@Test
public void testStartupFailsWithEmptyChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();

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