Removal of some unused internal methods, plus additional tests for some areas lacking coverage.

This commit is contained in:
Luke Taylor 2011-02-07 00:24:20 +00:00
parent 20e65a93ea
commit eb9482b33b
15 changed files with 259 additions and 82 deletions

View File

@ -23,29 +23,13 @@ import java.lang.reflect.Field;
/**
* Offers static methods for directly manipulating static fields.
* Offers static methods for directly manipulating fields.
*
* @author Ben Alex
*/
public final class FieldUtils {
//~ Constructors ===================================================================================================
private FieldUtils() {
}
//~ Methods ========================================================================================================
public static String getAccessorName(String fieldName, Class<?> type) {
Assert.hasText(fieldName, "FieldName required");
Assert.notNull(type, "Type required");
if (type.getName().equals("boolean")) {
return "is" + org.springframework.util.StringUtils.capitalize(fieldName);
} else {
return "get" + org.springframework.util.StringUtils.capitalize(fieldName);
}
}
/**
* Attempts to locate the specified field on the class.
*
@ -98,12 +82,6 @@ public final class FieldUtils {
}
public static String getMutatorName(String fieldName) {
Assert.hasText(fieldName, "FieldName required");
return "set" + org.springframework.util.StringUtils.capitalize(fieldName);
}
public static Object getProtectedFieldValue(String protectedField, Object object) {
Field field = FieldUtils.getField(object.getClass(), protectedField);

View File

@ -63,7 +63,7 @@ public class InMemoryResource extends AbstractResource {
}
public int hashCode() {
return source.hashCode();
return 1;
}
public boolean equals(Object res) {

View File

@ -31,10 +31,6 @@ import org.springframework.util.Assert;
* @author Ben Alex
*/
public final class MethodInvocationUtils {
//~ Constructors ===================================================================================================
private MethodInvocationUtils() {
}
//~ Methods ========================================================================================================

View File

@ -15,13 +15,15 @@
package org.springframework.security.access;
import static org.junit.Assert.assertSame;
import org.junit.Test;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.event.AuthorizationFailureEvent;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.util.SimpleMethodInvocation;
import java.util.*;
/**
* Tests {@link AuthorizationFailureEvent}.
@ -29,28 +31,35 @@ import org.springframework.security.util.SimpleMethodInvocation;
* @author Ben Alex
*/
public class AuthorizationFailureEventTests {
private final UsernamePasswordAuthenticationToken foo = new UsernamePasswordAuthenticationToken("foo", "bar");
private List<ConfigAttribute> attributes = SecurityConfig.createList("TEST");
private AccessDeniedException exception = new AuthorizationServiceException("error", new Throwable());
@Test(expected=IllegalArgumentException.class)
public void testRejectsNulls() {
new AuthorizationFailureEvent(null, SecurityConfig.createList("TEST"),
new UsernamePasswordAuthenticationToken("foo", "bar"), new AccessDeniedException("error"));
public void rejectsNullSecureObject() {
new AuthorizationFailureEvent(null, attributes, foo, exception);
}
@Test(expected=IllegalArgumentException.class)
public void testRejectsNulls2() {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), null,
new UsernamePasswordAuthenticationToken("foo", "bar"), new AccessDeniedException("error"));
public void rejectsNullAttributesList() {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), null, foo, exception);
}
@Test(expected=IllegalArgumentException.class)
public void testRejectsNulls3() {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), SecurityConfig.createList("TEST"), null,
new AccessDeniedException("error"));
public void rejectsNullAuthentication() {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), attributes, null, exception);
}
@Test(expected=IllegalArgumentException.class)
public void testRejectsNulls4() {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), SecurityConfig.createList("TEST"),
new UsernamePasswordAuthenticationToken("foo", "bar"), null);
public void rejectsNullException() {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), attributes, foo, null);
}
@Test
public void gettersReturnCtorSuppliedData() throws Exception {
AuthorizationFailureEvent event = new AuthorizationFailureEvent(new Object(), attributes , foo, exception);
assertSame(attributes, event.getConfigAttributes());
assertSame(exception, event.getAccessDeniedException());
assertSame(foo, event.getAuthentication());
}
}

View File

@ -0,0 +1,39 @@
package org.springframework.security.util;
import static org.junit.Assert.*;
import org.junit.*;
/**
* @author Luke Taylor
*/
public class FieldUtilsTests {
@Test
public void gettingAndSettingProtectedFieldIsSuccessful() throws Exception {
new FieldUtils();
Object tc = new TestClass();
assertEquals("x", FieldUtils.getProtectedFieldValue("protectedField", tc));
assertEquals("z", FieldUtils.getFieldValue(tc, "nested.protectedField"));
FieldUtils.setProtectedFieldValue("protectedField", tc, "y");
assertEquals("y", FieldUtils.getProtectedFieldValue("protectedField", tc));
try {
FieldUtils.getProtectedFieldValue("nonExistentField", tc);
} catch (IllegalStateException expected) {
}
}
}
@SuppressWarnings("unused")
class TestClass {
private String protectedField = "x";
private Nested nested = new Nested();
}
@SuppressWarnings("unused")
class Nested {
private String protectedField = "z";
}

View File

@ -0,0 +1,26 @@
package org.springframework.security.util;
import static org.junit.Assert.*;
import org.junit.*;
/**
* @author Luke Taylor
*/
public class InMemoryResourceTests {
@Test
public void resourceContainsExpectedData() throws Exception {
InMemoryResource resource = new InMemoryResource("blah");
assertNull(resource.getDescription());
assertEquals(1, resource.hashCode());
assertNotNull(resource.getInputStream());
}
@Test
public void resourceIsEqualToOneWithSameContent() throws Exception {
assertEquals(new InMemoryResource("xxx"), new InMemoryResource("xxx"));
assertFalse(new InMemoryResource("xxx").equals(new InMemoryResource("xxxx")));
assertFalse(new InMemoryResource("xxx").equals(new Object()));
}
}

View File

@ -3,9 +3,12 @@ package org.springframework.security.util;
import static org.junit.Assert.*;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.Test;
import org.junit.*;
import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.security.access.annotation.BusinessServiceImpl;
import java.io.Serializable;
/**
*
* @author Luke Taylor
@ -14,6 +17,8 @@ public class MethodInvocationUtilsTests {
@Test
public void createFromClassReturnsMethodWithNoArgInfoForMethodWithNoArgs() {
new MethodInvocationUtils();
MethodInvocation mi = MethodInvocationUtils.createFromClass(String.class, "length");
assertNotNull(mi);
}
@ -36,4 +41,28 @@ public class MethodInvocationUtilsTests {
assertNotNull(mi);
}
@Test
public void createFromObjectLocatesExistingMethods() throws Exception {
AdvisedTarget t = new AdvisedTarget();
// Just lie about interfaces
t.setInterfaces(new Class[] {Serializable.class, MethodInvocation.class, Blah.class});
MethodInvocation mi = MethodInvocationUtils.create(t, "blah");
assertNotNull(mi);
t.setProxyTargetClass(true);
mi = MethodInvocationUtils.create(t, "blah");
assertNotNull(mi);
assertNull(MethodInvocationUtils.create(t, "blah", "non-existent arg"));
}
interface Blah {
void blah();
}
class AdvisedTarget extends AdvisedSupport implements Blah {
public void blah() {
}
}
}

View File

@ -53,7 +53,7 @@ public class PasswordPolicyAwareContextSource extends DefaultSpringSecurityConte
PasswordPolicyResponseControl ctrl = PasswordPolicyControlExtractor.extractControl(ctx);
if (debug) {
logger.debug("Failed to obtain context", ne);
logger.debug("Pasword policy response: " + ctrl);
logger.debug("Password policy response: " + ctrl);
}
LdapUtils.closeContext(ctx);

View File

@ -0,0 +1,62 @@
package org.springframework.security.ldap.ppolicy;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.*;
import org.junit.*;
import org.springframework.ldap.UncategorizedLdapException;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.ldap.Control;
import javax.naming.ldap.LdapContext;
import java.util.*;
/**
* @author Luke Taylor
*/
public class PasswordPolicyAwareContextSourceTests {
private PasswordPolicyAwareContextSource ctxSource;
private final LdapContext ctx = mock(LdapContext.class);
@Before
public void setUp() throws Exception {
reset(ctx);
ctxSource = new PasswordPolicyAwareContextSource("ldap://blah:789/dc=springframework,dc=org") {
@Override
protected DirContext createContext(Hashtable env) {
if ("manager".equals(env.get(Context.SECURITY_PRINCIPAL))) {
return ctx;
}
return null;
}
};
ctxSource.setUserDn("manager");
ctxSource.setPassword("password");
ctxSource.afterPropertiesSet();
}
@Test
public void contextIsReturnedWhenNoControlsAreSetAndReconnectIsSuccessful() throws Exception {
assertNotNull(ctxSource.getContext("user", "ignored"));
}
@Test(expected=UncategorizedLdapException.class)
public void standardExceptionIsPropagatedWhenExceptionRaisedAndNoControlsAreSet() throws Exception {
doThrow(new NamingException("some LDAP exception")).when(ctx).reconnect(any(Control[].class));
ctxSource.getContext("user", "ignored");
}
@Test(expected=PasswordPolicyException.class)
public void lockedPasswordPolicyControlRaisesPasswordPolicyException() throws Exception {
when(ctx.getResponseControls()).thenReturn(new Control[] {
new PasswordPolicyResponseControl(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL) });
doThrow(new NamingException("locked message")).when(ctx).reconnect(any(Control[].class));
ctxSource.getContext("user", "ignored");
}
}

View File

@ -0,0 +1,36 @@
package org.springframework.security.ldap.ppolicy;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.*;
import javax.naming.ldap.Control;
import java.util.*;
/**
* @author Luke Taylor
*/
public class PasswordPolicyControlFactoryTests {
@Test
public void returnsNullForUnrecognisedOID() throws Exception {
PasswordPolicyControlFactory ctrlFactory = new PasswordPolicyControlFactory();
Control wrongCtrl = mock(Control.class);
when(wrongCtrl.getID()).thenReturn("wrongId");
assertNull(ctrlFactory.getControlInstance(wrongCtrl));
}
@Test
public void returnsControlForCorrectOID() throws Exception {
PasswordPolicyControlFactory ctrlFactory = new PasswordPolicyControlFactory();
Control control = mock(Control.class);
when(control.getID()).thenReturn(PasswordPolicyControl.OID);
when(control.getEncodedValue()).thenReturn(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL);
Control result = ctrlFactory.getControlInstance(control);
assertNotNull(result);
assertTrue(Arrays.equals(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL, result.getEncodedValue()));
}
}

View File

@ -15,14 +15,19 @@
package org.springframework.security.ldap.ppolicy;
import junit.framework.TestCase;
import static org.junit.Assert.*;
import org.junit.Test;
import javax.naming.ldap.Control;
import java.util.*;
/**
* Tests for <tt>PasswordPolicyResponse</tt>.
*
* @author Luke Taylor
*/
public class PasswordPolicyResponseControlTests extends TestCase {
public class PasswordPolicyResponseControlTests {
//~ Methods ========================================================================================================
/**
@ -76,7 +81,8 @@ public class PasswordPolicyResponseControlTests extends TestCase {
// return null;
// }
public void testOpenLDAP33SecondsTillPasswordExpiryCtrlIsParsedCorrectly() {
@Test
public void openLDAP33SecondsTillPasswordExpiryCtrlIsParsedCorrectly() {
byte[] ctrlBytes = {0x30, 0x05, (byte) 0xA0, 0x03, (byte) 0xA0, 0x1, 0x21};
PasswordPolicyResponseControl ctrl = new PasswordPolicyResponseControl(ctrlBytes);
@ -85,7 +91,8 @@ public class PasswordPolicyResponseControlTests extends TestCase {
assertEquals(33, ctrl.getTimeBeforeExpiration());
}
public void testOpenLDAP496GraceLoginsRemainingCtrlIsParsedCorrectly() {
@Test
public void openLDAP496GraceLoginsRemainingCtrlIsParsedCorrectly() {
byte[] ctrlBytes = {0x30, 0x06, (byte) 0xA0, 0x04, (byte) 0xA1, 0x02, 0x01, (byte) 0xF0};
PasswordPolicyResponseControl ctrl = new PasswordPolicyResponseControl(ctrlBytes);
@ -94,25 +101,28 @@ public class PasswordPolicyResponseControlTests extends TestCase {
assertEquals(496, ctrl.getGraceLoginsRemaining());
}
public void testOpenLDAP5GraceLoginsRemainingCtrlIsParsedCorrectly() {
byte[] ctrlBytes = {0x30, 0x05, (byte) 0xA0, 0x03, (byte) 0xA1, 0x01, 0x05};
static final byte[] OPENLDAP_5_LOGINS_REMAINING_CTRL = {0x30, 0x05, (byte) 0xA0, 0x03, (byte) 0xA1, 0x01, 0x05};
PasswordPolicyResponseControl ctrl = new PasswordPolicyResponseControl(ctrlBytes);
@Test
public void openLDAP5GraceLoginsRemainingCtrlIsParsedCorrectly() {
PasswordPolicyResponseControl ctrl = new PasswordPolicyResponseControl(OPENLDAP_5_LOGINS_REMAINING_CTRL);
assertTrue(ctrl.hasWarning());
assertEquals(5, ctrl.getGraceLoginsRemaining());
}
public void testOpenLDAPAccountLockedCtrlIsParsedCorrectly() {
byte[] ctrlBytes = {0x30, 0x03, (byte) 0xA1, 0x01, 0x01};
static final byte[] OPENLDAP_LOCKED_CTRL = {0x30, 0x03, (byte) 0xA1, 0x01, 0x01};
PasswordPolicyResponseControl ctrl = new PasswordPolicyResponseControl(ctrlBytes);
@Test
public void openLDAPAccountLockedCtrlIsParsedCorrectly() {
PasswordPolicyResponseControl ctrl = new PasswordPolicyResponseControl(OPENLDAP_LOCKED_CTRL);
assertTrue(ctrl.hasError() && ctrl.isLocked());
assertFalse(ctrl.hasWarning());
}
public void testOpenLDAPPasswordExpiredCtrlIsParsedCorrectly() {
@Test
public void openLDAPPasswordExpiredCtrlIsParsedCorrectly() {
byte[] ctrlBytes = {0x30, 0x03, (byte) 0xA1, 0x01, 0x00};
PasswordPolicyResponseControl ctrl = new PasswordPolicyResponseControl(ctrlBytes);

View File

@ -19,7 +19,6 @@ package org.springframework.security.web.util;
import javax.servlet.http.HttpServletRequest;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
@ -28,10 +27,10 @@ import org.springframework.security.web.authentication.DelegatingAuthenticationE
/**
* A RequestMatcher implementation which uses a SpEL expression
*
* <p>With the default EvalutationContext ({@link ELRequestMatcherContext}) you can use
* <p>With the default EvaluationContext ({@link ELRequestMatcherContext}) you can use
* <code>hasIpAdress()</code> and <code>hasHeader()</code></p>
*
* <p>See {@link DelegatingAuthenticationEntryPoint} for a example configuration.</p>
* <p>See {@link DelegatingAuthenticationEntryPoint} for an example configuration.</p>
*
*
* @author Mike Wiesner
@ -48,7 +47,7 @@ public class ELRequestMatcher implements RequestMatcher {
public boolean matches(HttpServletRequest request) {
EvaluationContext context = createELContext(request);
return evaluateAsBoolean(expression, context);
return expression.getValue(context, Boolean.class).booleanValue();
}
/**
@ -60,11 +59,4 @@ public class ELRequestMatcher implements RequestMatcher {
return new StandardEvaluationContext(new ELRequestMatcherContext(request));
}
private boolean evaluateAsBoolean(Expression expr, EvaluationContext ctx) {
try {
return ((Boolean) expr.getValue(ctx, Boolean.class)).booleanValue();
} catch (EvaluationException e) {
throw new IllegalArgumentException("Failed to evaluate expression '" + expr.getExpressionString() + "'", e);
}
}
}

View File

@ -175,7 +175,7 @@ public class ThrowableAnalyzer {
for (Map.Entry<Class<? extends Throwable>, ThrowableCauseExtractor> entry : extractorMap.entrySet()) {
Class<? extends Throwable> throwableType = entry.getKey();
if (throwableType.isInstance(throwable)) {
ThrowableCauseExtractor extractor = (ThrowableCauseExtractor) entry.getValue();
ThrowableCauseExtractor extractor = entry.getValue();
return extractor.extractCause(throwable);
}
}

View File

@ -94,8 +94,9 @@ public class ExceptionTranslationFilterTests {
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter();
filter.setAuthenticationEntryPoint(mockEntryPoint());
filter.setAuthenticationEntryPoint(mockEntryPoint);
filter.setAuthenticationTrustResolver(new AuthenticationTrustResolverImpl());
assertNotNull(filter.getAuthenticationTrustResolver());
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, fc);
@ -123,7 +124,7 @@ public class ExceptionTranslationFilterTests {
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter();
filter.setAuthenticationEntryPoint(mockEntryPoint());
filter.setAuthenticationEntryPoint(mockEntryPoint);
filter.setAccessDeniedHandler(adh);
MockHttpServletResponse response = new MockHttpServletResponse();
@ -149,7 +150,7 @@ public class ExceptionTranslationFilterTests {
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter();
filter.setAuthenticationEntryPoint(mockEntryPoint());
filter.setAuthenticationEntryPoint(mockEntryPoint);
filter.afterPropertiesSet();
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, fc);
@ -175,7 +176,7 @@ public class ExceptionTranslationFilterTests {
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter();
filter.setAuthenticationEntryPoint(mockEntryPoint());
filter.setAuthenticationEntryPoint(mockEntryPoint);
HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
requestCache.setPortResolver(new MockPortResolver(8080, 8443));
filter.setRequestCache(requestCache);
@ -197,7 +198,7 @@ public class ExceptionTranslationFilterTests {
@Test(expected=IllegalArgumentException.class)
public void startupDetectsMissingRequestCache() throws Exception {
ExceptionTranslationFilter filter = new ExceptionTranslationFilter();
filter.setAuthenticationEntryPoint(mockEntryPoint());
filter.setAuthenticationEntryPoint(mockEntryPoint);
filter.setRequestCache(null);
}
@ -210,7 +211,8 @@ public class ExceptionTranslationFilterTests {
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter();
filter.setAuthenticationEntryPoint(mockEntryPoint());
filter.setAuthenticationEntryPoint(mockEntryPoint);
assertSame(mockEntryPoint, filter.getAuthenticationEntryPoint());
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, mock(FilterChain.class));
@ -220,7 +222,7 @@ public class ExceptionTranslationFilterTests {
public void thrownIOExceptionServletExceptionAndRuntimeExceptionsAreRethrown() throws Exception {
ExceptionTranslationFilter filter = new ExceptionTranslationFilter();
filter.setAuthenticationEntryPoint(mockEntryPoint());
filter.setAuthenticationEntryPoint(mockEntryPoint);
filter.afterPropertiesSet();
Exception[] exceptions = {new IOException(), new ServletException(), new RuntimeException()};
for (Exception e : exceptions) {
@ -237,12 +239,10 @@ public class ExceptionTranslationFilterTests {
}
}
private AuthenticationEntryPoint mockEntryPoint() {
return new AuthenticationEntryPoint() {
public void commence(HttpServletRequest request, HttpServletResponse response,
private final AuthenticationEntryPoint mockEntryPoint = new AuthenticationEntryPoint() {
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.sendRedirect(request.getContextPath() + "/login.jsp");
}
};
}
response.sendRedirect(request.getContextPath() + "/login.jsp");
}
};
}

View File

@ -24,7 +24,7 @@ import org.springframework.mock.web.MockHttpServletRequest;
* @author Mike Wiesner
* @since 3.0.2
*/
public class ELRequestMatcherTest {
public class ELRequestMatcherTests {
@Test
public void testHasIpAddressTrue() throws Exception {