Upgraded to jmock 2.5.1

This commit is contained in:
Luke Taylor 2008-11-04 05:37:56 +00:00
parent 514bca669f
commit b42fc7221f
10 changed files with 245 additions and 276 deletions

View File

@ -129,10 +129,8 @@
<optional>true</optional>
</dependency>
<dependency>
<groupId>jmock</groupId>
<artifactId>jmock</artifactId>
<version>1.0.1</version>
<scope>test</scope>
<groupId>org.jmock</groupId>
<artifactId>jmock-junit4</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>

View File

@ -0,0 +1,63 @@
package org.springframework.security.expression;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.SpelExpressionParser;
import org.springframework.expression.spel.standard.StandardEvaluationContext;
import org.springframework.security.Authentication;
import org.springframework.security.expression.SecurityExpressionRoot;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
/**
* Sandbox class for checking feasibility of different security-related expressions.
*
* @author Luke Taylor
* @version $Id$
*/
public class SecurityExpressionRootTests {
SpelExpressionParser parser = new SpelExpressionParser();
UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password");
SecurityExpressionRoot root;
StandardEvaluationContext ctx;
@Before
public void createContext() {
root = new SecurityExpressionRoot(joe);
ctx = new StandardEvaluationContext();
ctx.setRootObject(root);
}
@Test
public void canCallMethodsOnVariables() throws Exception {
ctx.setVariable("var", "somestring");
Expression e = parser.parseExpression("#var.length() == 10");
assertTrue(ExpressionUtils.evaluateAsBoolean(e, ctx));
}
@Test
public void hasPermissionWorksWithIntegerExpressions() throws Exception {
final Object dummyDomainObject = new Object();
ctx.setVariable("domainObject", dummyDomainObject);
root.setPermissionEvaluator(new PermissionEvaluator () {
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
// Check the correct target object is passed in
assertEquals(dummyDomainObject, targetDomainObject);
return permission instanceof Integer && ((Integer)permission).intValue() == 10;
}
});
Expression e = parser.parseExpression("hasPermission(#domainObject, 0xA)");
assertTrue(ExpressionUtils.evaluateAsBoolean(e, ctx));
e = parser.parseExpression("hasPermission(#domainObject, 10)");
assertTrue(ExpressionUtils.evaluateAsBoolean(e, ctx));
e = parser.parseExpression("hasPermission(#domainObject, 0xFF)");
assertFalse(ExpressionUtils.evaluateAsBoolean(e, ctx));
}
}

View File

@ -1,30 +0,0 @@
package org.springframework.security.expression;
import org.junit.Test;
import org.springframework.expression.spel.standard.StandardEvaluationContext;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
/**
*
* @author Luke Taylor
* @version $Id$
*/
public class SecurityExpressionTests {
@Test
public void someTestMethod() throws Exception {
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken("joe", "password");
SecurityExpressionRoot root = new SecurityExpressionRoot(authToken);
StandardEvaluationContext ctx = new StandardEvaluationContext();
}
@Test
public void someTestMethod2() throws Exception {
}
}

View File

@ -15,17 +15,15 @@
package org.springframework.security.intercept.web;
import static org.junit.Assert.*;
import org.springframework.security.MockFilterChain;
import org.jmock.MockObjectTestCase;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* Tests {@link FilterInvocation}.
*
@ -33,27 +31,11 @@ import javax.servlet.ServletResponse;
* @author colin sampaleanu
* @version $Id$
*/
public class FilterInvocationTests extends MockObjectTestCase {
//~ Constructors ===================================================================================================
public FilterInvocationTests() {
super();
}
public FilterInvocationTests(String arg0) {
super(arg0);
}
public class FilterInvocationTests {
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(FilterInvocationTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
@Test
public void testGettersAndStringMethods() {
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
request.setServletPath("/HelloWorld");
@ -77,79 +59,31 @@ public class FilterInvocationTests extends MockObjectTestCase {
assertEquals("http://www.example.com/mycontext/HelloWorld/some/more/segments.html", fi.getFullRequestUrl());
}
public void testNoArgConstructorDoesntExist() {
Class clazz = FilterInvocation.class;
try {
clazz.getDeclaredConstructor((Class[]) null);
fail("Should have thrown NoSuchMethodException");
} catch (NoSuchMethodException expected) {
assertTrue(true);
}
}
@Test(expected=IllegalArgumentException.class)
public void testRejectsNullFilterChain() {
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
MockHttpServletResponse response = new MockHttpServletResponse();
try {
new FilterInvocation(request, response, null);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
new FilterInvocation(request, response, null);
}
@Test(expected=IllegalArgumentException.class)
public void testRejectsNullServletRequest() {
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
try {
new FilterInvocation(null, response, chain);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
new FilterInvocation(null, response, chain);
}
@Test(expected=IllegalArgumentException.class)
public void testRejectsNullServletResponse() {
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
MockFilterChain chain = new MockFilterChain();
try {
new FilterInvocation(request, null, chain);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testRejectsServletRequestWhichIsNotHttpServletRequest() {
ServletRequest request = (ServletRequest) newDummy(ServletRequest.class);
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
try {
new FilterInvocation(request, response, chain);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("Can only process HttpServletRequest", expected.getMessage());
}
}
public void testRejectsServletResponseWhichIsNotHttpServletResponse() {
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
ServletResponse response = (ServletResponse) newDummy(ServletResponse.class);
MockFilterChain chain = new MockFilterChain();
try {
new FilterInvocation(request, response, chain);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("Can only process HttpServletResponse", expected.getMessage());
}
new FilterInvocation(request, null, chain);
}
@Test
public void testStringMethodsWithAQueryString() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setQueryString("foo=bar");
@ -168,6 +102,7 @@ public class FilterInvocationTests extends MockObjectTestCase {
assertEquals("http://www.example.com/mycontext/HelloWorld?foo=bar", fi.getFullRequestUrl());
}
@Test
public void testStringMethodsWithoutAnyQueryString() {
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
request.setServletPath("/HelloWorld");

View File

@ -15,8 +15,14 @@
package org.springframework.security.ldap;
import org.jmock.Mock;
import org.jmock.MockObjectTestCase;
import static org.junit.Assert.*;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.naming.Context;
import javax.naming.NamingException;
@ -29,49 +35,62 @@ import javax.naming.directory.DirContext;
* @author Luke Taylor
* @version $Id$
*/
public class LdapUtilsTests extends MockObjectTestCase {
@RunWith(JMock.class)
public class LdapUtilsTests {
Mockery context = new JUnit4Mockery();
//~ Methods ========================================================================================================
public void testCloseContextSwallowsNamingException() {
Mock mockCtx = mock(DirContext.class);
@Test
public void testCloseContextSwallowsNamingException() throws Exception {
final DirContext dirCtx = context.mock(DirContext.class);
mockCtx.expects(once()).method("close").will(throwException(new NamingException()));
context.checking(new Expectations() {{
oneOf(dirCtx).close(); will(throwException(new NamingException()));
}});
LdapUtils.closeContext((Context) mockCtx.proxy());
LdapUtils.closeContext(dirCtx);
}
public void testGetRelativeNameReturnsEmptyStringForDnEqualToBaseName()
throws Exception {
Mock mockCtx = mock(DirContext.class);
@Test
public void testGetRelativeNameReturnsEmptyStringForDnEqualToBaseName() throws Exception {
final DirContext mockCtx = context.mock(DirContext.class);
mockCtx.expects(atLeastOnce()).method("getNameInNamespace").will(returnValue("dc=springframework,dc=org"));
context.checking(new Expectations() {{
atLeast(1).of(mockCtx).getNameInNamespace(); will(returnValue("dc=springframework,dc=org"));
}});
assertEquals("", LdapUtils.getRelativeName("dc=springframework,dc=org", (Context) mockCtx.proxy()));
assertEquals("", LdapUtils.getRelativeName("dc=springframework,dc=org", mockCtx));
}
public void testGetRelativeNameReturnsFullDnWithEmptyBaseName()
throws Exception {
Mock mockCtx = mock(DirContext.class);
@Test
public void testGetRelativeNameReturnsFullDnWithEmptyBaseName() throws Exception {
final DirContext mockCtx = context.mock(DirContext.class);
mockCtx.expects(atLeastOnce()).method("getNameInNamespace").will(returnValue(""));
context.checking(new Expectations() {{
atLeast(1).of(mockCtx).getNameInNamespace(); will(returnValue(""));
}});
assertEquals("cn=jane,dc=springframework,dc=org",
LdapUtils.getRelativeName("cn=jane,dc=springframework,dc=org", (Context) mockCtx.proxy()));
LdapUtils.getRelativeName("cn=jane,dc=springframework,dc=org", mockCtx));
}
@Test
public void testGetRelativeNameWorksWithArbitrarySpaces() throws Exception {
Mock mockCtx = mock(DirContext.class);
final DirContext mockCtx = context.mock(DirContext.class);
mockCtx.expects(atLeastOnce()).method("getNameInNamespace").will(returnValue("dc=springsecurity,dc = org"));
context.checking(new Expectations() {{
atLeast(1).of(mockCtx).getNameInNamespace(); will(returnValue("dc=springsecurity,dc = org"));
}});
assertEquals("cn=jane smith",
LdapUtils.getRelativeName("cn=jane smith, dc = springsecurity , dc=org", (Context) mockCtx.proxy()));
LdapUtils.getRelativeName("cn=jane smith, dc = springsecurity , dc=org", mockCtx));
}
@Test
public void testRootDnsAreParsedFromUrlsCorrectly() {
assertEquals("", LdapUtils.parseRootDnFromUrl("ldap://monkeymachine"));
assertEquals("", LdapUtils.parseRootDnFromUrl("ldap://monkeymachine:11389"));
assertEquals("", LdapUtils.parseRootDnFromUrl("ldap://monkeymachine:11389"));
assertEquals("", LdapUtils.parseRootDnFromUrl("ldap://monkeymachine/"));
assertEquals("", LdapUtils.parseRootDnFromUrl("ldap://monkeymachine.co.uk/"));
assertEquals("dc=springframework,dc=org",

View File

@ -15,16 +15,18 @@
package org.springframework.security.providers.ldap.authenticator;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Test;
import org.springframework.security.ldap.MockSpringSecurityContextSource;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.jmock.Mock;
import org.jmock.MockObjectTestCase;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.SearchControls;
/**
@ -32,33 +34,42 @@ import javax.naming.directory.BasicAttribute;
* @author Luke Taylor
* @version $Id$
*/
public class PasswordComparisonAuthenticatorMockTests extends MockObjectTestCase {
public class PasswordComparisonAuthenticatorMockTests {
Mockery context = new JUnit4Mockery();
//~ Methods ========================================================================================================
public void testLdapCompareIsUsedWhenPasswordIsNotRetrieved() throws Exception {
Mock mockCtx = mock(DirContext.class);
BasicAttributes attrs = new BasicAttributes();
@Test
public void ldapCompareOperationIsUsedWhenPasswordIsNotRetrieved() throws Exception {
final DirContext dirCtx = context.mock(DirContext.class);
final BasicAttributes attrs = new BasicAttributes();
attrs.put(new BasicAttribute("uid", "bob"));
PasswordComparisonAuthenticator authenticator = new PasswordComparisonAuthenticator(new MockSpringSecurityContextSource(
(DirContext) mockCtx.proxy(), ""));
PasswordComparisonAuthenticator authenticator =
new PasswordComparisonAuthenticator(new MockSpringSecurityContextSource(dirCtx, ""));
authenticator.setUserDnPatterns(new String[] {"cn={0},ou=people"});
// Get the mock to return an empty attribute set
// mockCtx.expects(atLeastOnce()).method("getNameInNamespace").will(returnValue("dc=springframework,dc=org"));
// mockCtx.expects(once()).method("lookup").with(eq("cn=Bob,ou=people")).will(returnValue(true));
mockCtx.expects(once()).method("getAttributes").with(eq("cn=Bob,ou=people"), NULL)
.will(returnValue(attrs));
mockCtx.expects(once()).method("getNameInNamespace").will(returnValue("dc=springframework,dc=org"));
context.checking(new Expectations() {{
oneOf(dirCtx).getAttributes(with(equal("cn=Bob,ou=people")), with(aNull(String[].class))); will(returnValue(attrs));
oneOf(dirCtx).getNameInNamespace(); will(returnValue("dc=springframework,dc=org"));
}});
// Setup a single return value (i.e. success)
Attributes searchResults = new BasicAttributes("", null);
mockCtx.expects(once())
.method("search")
.with(eq("cn=Bob, ou=people"), eq("(userPassword={0})"), NOT_NULL, NOT_NULL)
.will(returnValue(searchResults.getAll()));
mockCtx.expects(atLeastOnce()).method("close");
final Attributes searchResults = new BasicAttributes("", null);
context.checking(new Expectations() {{
oneOf(dirCtx).search(with(equal("cn=Bob, ou=people")),
with(equal("(userPassword={0})")),
with(aNonNull(Object[].class)),
with(aNonNull(SearchControls.class)));
will(returnValue(searchResults.getAll()));
atLeast(1).of(dirCtx).close();
}});
authenticator.authenticate(new UsernamePasswordAuthenticationToken("Bob","bobspassword"));
context.assertIsSatisfied();
}
}

View File

@ -15,9 +15,16 @@
package org.springframework.security.ui.basicauth;
import static org.junit.Assert.*;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.MockAuthenticationEntryPoint;
import org.springframework.security.MockAuthenticationManager;
import org.springframework.security.MockFilterChain;
import org.springframework.security.MockFilterConfig;
import org.springframework.security.MockApplicationEventPublisher;
@ -33,9 +40,6 @@ import org.springframework.security.userdetails.memory.UserMapEditor;
import org.apache.commons.codec.binary.Base64;
import org.jmock.Mock;
import org.jmock.MockObjectTestCase;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
@ -56,40 +60,33 @@ import javax.servlet.ServletRequest;
* @author Ben Alex
* @version $Id$
*/
public class BasicProcessingFilterTests extends MockObjectTestCase {
public class BasicProcessingFilterTests {
//~ Instance fields ================================================================================================
private BasicProcessingFilter filter;
//~ Constructors ===================================================================================================
public BasicProcessingFilterTests() {
}
public BasicProcessingFilterTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
private MockHttpServletResponse executeFilterInContainerSimulator(Filter filter, ServletRequest request,
boolean expectChainToProceed) throws ServletException, IOException {
private MockHttpServletResponse executeFilterInContainerSimulator(Filter filter, final ServletRequest request,
final boolean expectChainToProceed) throws ServletException, IOException {
filter.init(new MockFilterConfig());
MockHttpServletResponse response = new MockHttpServletResponse();
Mock mockChain = mock(FilterChain.class);
FilterChain chain = (FilterChain) mockChain.proxy();
final MockHttpServletResponse response = new MockHttpServletResponse();
Mockery jmockContext = new JUnit4Mockery();
mockChain.expects(expectChainToProceed ? once() : never()).method("doFilter");
final FilterChain chain = jmockContext.mock(FilterChain.class);
jmockContext.checking(new Expectations() {{
exactly(expectChainToProceed ? 1 : 0).of(chain).doFilter(request, response);
}});
filter.doFilter(request, response, chain);
filter.destroy();
jmockContext.assertIsSatisfied();
return response;
}
protected void setUp() throws Exception {
super.setUp();
@Before
public void setUp() throws Exception {
SecurityContextHolder.clearContext();
// Create User Details Service, provider and authentication manager
@ -111,33 +108,12 @@ public class BasicProcessingFilterTests extends MockObjectTestCase {
filter.setAuthenticationEntryPoint(new BasicProcessingFilterEntryPoint());
}
protected void tearDown() throws Exception {
super.tearDown();
@After
public void clearContext() throws Exception {
SecurityContextHolder.clearContext();
}
public void testDoFilterWithNonHttpServletRequestDetected() throws Exception {
BasicProcessingFilter filter = new BasicProcessingFilter();
try {
filter.doFilter(null, new MockHttpServletResponse(), new MockFilterChain());
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("Can only process HttpServletRequest", expected.getMessage());
}
}
public void testDoFilterWithNonHttpServletResponseDetected() throws Exception {
BasicProcessingFilter filter = new BasicProcessingFilter();
try {
filter.doFilter(new MockHttpServletRequest(null, null), null, new MockFilterChain());
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("Can only process HttpServletResponse", expected.getMessage());
}
}
@Test
public void testFilterIgnoresRequestsContainingNoAuthorizationHeader() throws Exception {
// Setup our HTTP request
MockHttpServletRequest request = new MockHttpServletRequest();
@ -149,6 +125,7 @@ public class BasicProcessingFilterTests extends MockObjectTestCase {
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
@Test
public void testGettersSetters() {
BasicProcessingFilter filter = new BasicProcessingFilter();
filter.setAuthenticationManager(new MockAuthenticationManager());
@ -158,6 +135,7 @@ public class BasicProcessingFilterTests extends MockObjectTestCase {
assertTrue(filter.getAuthenticationEntryPoint() != null);
}
@Test
public void testInvalidBasicAuthorizationTokenIsIgnored() throws Exception {
// Setup our HTTP request
String token = "NOT_A_VALID_TOKEN_AS_MISSING_COLON";
@ -172,6 +150,7 @@ public class BasicProcessingFilterTests extends MockObjectTestCase {
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
@Test
public void testNormalOperation() throws Exception {
// Setup our HTTP request
String token = "rod:koala";
@ -189,6 +168,7 @@ public class BasicProcessingFilterTests extends MockObjectTestCase {
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
}
@Test
public void testOtherAuthorizationSchemeIsIgnored() throws Exception {
// Setup our HTTP request
MockHttpServletRequest request = new MockHttpServletRequest();
@ -201,6 +181,7 @@ public class BasicProcessingFilterTests extends MockObjectTestCase {
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
@Test
public void testStartupDetectsMissingAuthenticationEntryPoint() throws Exception {
try {
BasicProcessingFilter filter = new BasicProcessingFilter();
@ -212,6 +193,7 @@ public class BasicProcessingFilterTests extends MockObjectTestCase {
}
}
@Test
public void testStartupDetectsMissingAuthenticationManager() throws Exception {
try {
BasicProcessingFilter filter = new BasicProcessingFilter();
@ -223,6 +205,7 @@ public class BasicProcessingFilterTests extends MockObjectTestCase {
}
}
@Test
public void testSuccessLoginThenFailureLoginResultsInSessionLosingToken() throws Exception {
// Setup our HTTP request
String token = "rod:koala";
@ -253,6 +236,7 @@ public class BasicProcessingFilterTests extends MockObjectTestCase {
assertEquals(401, response.getStatus());
}
@Test
public void testWrongPasswordContinuesFilterChainIfIgnoreFailureIsTrue() throws Exception {
// Setup our HTTP request
String token = "rod:WRONG_PASSWORD";
@ -270,6 +254,7 @@ public class BasicProcessingFilterTests extends MockObjectTestCase {
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
@Test
public void testWrongPasswordReturnsForbiddenIfIgnoreFailureIsFalse() throws Exception {
// Setup our HTTP request
String token = "rod:WRONG_PASSWORD";

View File

@ -15,7 +15,14 @@
package org.springframework.security.ui.digestauth;
import org.springframework.security.MockFilterChain;
import static org.junit.Assert.*;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.MockFilterConfig;
import org.springframework.security.context.SecurityContextHolder;
@ -32,9 +39,6 @@ import org.springframework.security.util.StringSplitUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.jmock.Mock;
import org.jmock.MockObjectTestCase;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@ -57,7 +61,7 @@ import javax.servlet.ServletRequest;
* @author Luke Taylor
* @version $Id$
*/
public class DigestProcessingFilterTests extends MockObjectTestCase {
public class DigestProcessingFilterTests {
//~ Static fields/initializers =====================================================================================
private static final String NC = "00000002";
@ -80,14 +84,6 @@ public class DigestProcessingFilterTests extends MockObjectTestCase {
private DigestProcessingFilter filter;
private MockHttpServletRequest request;
//~ Constructors ===================================================================================================
public DigestProcessingFilterTests() {
}
public DigestProcessingFilterTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
@ -97,19 +93,22 @@ public class DigestProcessingFilterTests extends MockObjectTestCase {
+ "\", response=\"" + responseDigest + "\", qop=" + qop + ", nc=" + nc + ", cnonce=\"" + cnonce + "\"";
}
private MockHttpServletResponse executeFilterInContainerSimulator(Filter filter, ServletRequest request,
boolean expectChainToProceed) throws ServletException, IOException {
private MockHttpServletResponse executeFilterInContainerSimulator(Filter filter, final ServletRequest request,
final boolean expectChainToProceed) throws ServletException, IOException {
filter.init(new MockFilterConfig());
MockHttpServletResponse response = new MockHttpServletResponse();
Mock mockChain = mock(FilterChain.class);
FilterChain chain = (FilterChain) mockChain.proxy();
final MockHttpServletResponse response = new MockHttpServletResponse();
mockChain.expects(expectChainToProceed ? once() : never()).method("doFilter");
Mockery jmockContext = new JUnit4Mockery();
final FilterChain chain = jmockContext.mock(FilterChain.class);
jmockContext.checking(new Expectations() {{
exactly(expectChainToProceed ? 1 : 0).of(chain).doFilter(request, response);
}});
filter.doFilter(request, response, chain);
filter.destroy();
jmockContext.assertIsSatisfied();
return response;
}
@ -121,8 +120,13 @@ public class DigestProcessingFilterTests extends MockObjectTestCase {
return new String(Base64.encodeBase64(nonceValue.getBytes()));
}
protected void setUp() throws Exception {
super.setUp();
@After
public void clearContext() throws Exception {
SecurityContextHolder.clearContext();
}
@Before
public void setUp() throws Exception {
SecurityContextHolder.clearContext();
// Create User Details Service
@ -143,35 +147,7 @@ public class DigestProcessingFilterTests extends MockObjectTestCase {
request.setServletPath(REQUEST_URI);
}
protected void tearDown() throws Exception {
super.tearDown();
SecurityContextHolder.clearContext();
}
public void testDoFilterWithNonHttpServletRequestDetected()
throws Exception {
DigestProcessingFilter filter = new DigestProcessingFilter();
try {
filter.doFilter(null, new MockHttpServletResponse(), new MockFilterChain());
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("Can only process HttpServletRequest", expected.getMessage());
}
}
public void testDoFilterWithNonHttpServletResponseDetected()
throws Exception {
DigestProcessingFilter filter = new DigestProcessingFilter();
try {
filter.doFilter(new MockHttpServletRequest(null, null), null, new MockFilterChain());
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("Can only process HttpServletResponse", expected.getMessage());
}
}
@Test
public void testExpiredNonceReturnsForbiddenWithStaleHeader()
throws Exception {
String nonce = generateNonce(0);
@ -194,6 +170,7 @@ public class DigestProcessingFilterTests extends MockObjectTestCase {
assertEquals("true", headerMap.get("stale"));
}
@Test
public void testFilterIgnoresRequestsContainingNoAuthorizationHeader()
throws Exception {
executeFilterInContainerSimulator(filter, request, true);
@ -201,6 +178,7 @@ public class DigestProcessingFilterTests extends MockObjectTestCase {
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
@Test
public void testGettersSetters() {
DigestProcessingFilter filter = new DigestProcessingFilter();
filter.setUserDetailsService(new InMemoryDaoImpl());
@ -215,6 +193,7 @@ public class DigestProcessingFilterTests extends MockObjectTestCase {
assertNotNull(filter.getUserCache());
}
@Test
public void testInvalidDigestAuthorizationTokenGeneratesError()
throws Exception {
String token = "NOT_A_VALID_TOKEN_AS_MISSING_COLON";
@ -227,6 +206,7 @@ public class DigestProcessingFilterTests extends MockObjectTestCase {
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
@Test
public void testMalformedHeaderReturnsForbidden() throws Exception {
request.addHeader("Authorization", "Digest scsdcsdc");

View File

@ -1,50 +1,50 @@
package org.springframework.security.userdetails.hierarchicalroles;
import junit.textui.TestRunner;
import static org.junit.Assert.*;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.User;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.jmock.Mock;
import org.jmock.MockObjectTestCase;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
public class UserDetailsServiceWrapperTests extends MockObjectTestCase {
@RunWith(JMock.class)
public class UserDetailsServiceWrapperTests {
private UserDetailsService wrappedUserDetailsService = null;
private UserDetailsServiceWrapper userDetailsServiceWrapper = null;
private Mockery jmockContext = new JUnit4Mockery();
public UserDetailsServiceWrapperTests() {
super();
}
public UserDetailsServiceWrapperTests(String testCaseName) {
super(testCaseName);
}
public static void main(String[] args) {
TestRunner.run(UserDetailsServiceWrapperTests.class);
}
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
roleHierarchy.setHierarchy("ROLE_A > ROLE_B");
GrantedAuthority[] authorities = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_A") };
UserDetails user = new User("EXISTING_USER", "PASSWORD", true, true, true, true, authorities);
Mock wrappedUserDetailsServiceMock = mock(UserDetailsService.class);
wrappedUserDetailsServiceMock.stubs().method("loadUserByUsername").with(eq("EXISTING_USER")).will(returnValue(user));
wrappedUserDetailsServiceMock.stubs().method("loadUserByUsername").with(eq("USERNAME_NOT_FOUND_EXCEPTION")).will(throwException(new UsernameNotFoundException("USERNAME_NOT_FOUND_EXCEPTION")));
wrappedUserDetailsServiceMock.stubs().method("loadUserByUsername").with(eq("DATA_ACCESS_EXCEPTION")).will(throwException(new EmptyResultDataAccessException(1234)));
wrappedUserDetailsService = (UserDetailsService) wrappedUserDetailsServiceMock.proxy();
final UserDetails user = new User("EXISTING_USER", "PASSWORD", true, true, true, true, authorities);
final UserDetailsService wrappedUserDetailsService = jmockContext.mock(UserDetailsService.class);
jmockContext.checking( new Expectations() {{
allowing(wrappedUserDetailsService).loadUserByUsername("EXISTING_USER"); will(returnValue(user));
allowing(wrappedUserDetailsService).loadUserByUsername("USERNAME_NOT_FOUND_EXCEPTION"); will(throwException(new UsernameNotFoundException("USERNAME_NOT_FOUND_EXCEPTION")));
allowing(wrappedUserDetailsService).loadUserByUsername("DATA_ACCESS_EXCEPTION"); will(throwException(new EmptyResultDataAccessException(1234)));
}});
this.wrappedUserDetailsService = wrappedUserDetailsService;
userDetailsServiceWrapper = new UserDetailsServiceWrapper();
userDetailsServiceWrapper.setRoleHierarchy(roleHierarchy);
userDetailsServiceWrapper.setUserDetailsService(wrappedUserDetailsService);
}
@Test
public void testLoadUserByUsername() {
GrantedAuthority[] authorities = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_B") };
UserDetails expectedUserDetails = new User("EXISTING_USER", "PASSWORD", true, true, true, true, authorities);
@ -68,8 +68,9 @@ public class UserDetailsServiceWrapperTests extends MockObjectTestCase {
} catch (DataAccessException e) {}
}
@Test
public void testGetWrappedUserDetailsService() {
assertTrue(userDetailsServiceWrapper.getWrappedUserDetailsService() == wrappedUserDetailsService);
}
}
}

View File

@ -233,7 +233,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.4</version>
<version>4.5</version>
<scope>test</scope>
</dependency>
</dependencies>
@ -682,10 +682,17 @@
<artifactId>hsqldb</artifactId>
<version>1.8.0.7</version>
</dependency>
<dependency>
<groupId>org.jmock</groupId>
<artifactId>jmock-junit4</artifactId>
<version>2.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>commons-codec</groupId>